1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // InstructionCombining - Combine instructions to form fewer, simple
4 // instructions. This pass does not modify the CFG This pass is where algebraic
5 // simplification happens.
7 // This pass combines things like:
13 // This is a simple worklist driven algorithm.
15 // This pass guarantees that the following cannonicalizations are performed on
17 // 1. If a binary operator has a constant operand, it is moved to the RHS
18 // 2. Bitwise operators with constant operands are always grouped so that
19 // shifts are performed first, then or's, then and's, then xor's.
20 // 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
21 // 4. All SetCC instructions on boolean values are replaced with logical ops
22 // 5. add X, X is represented as (X*2) => (X << 1)
23 // 6. Multiplies with a power-of-two constant argument are transformed into
25 // N. This list is incomplete
27 //===----------------------------------------------------------------------===//
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Constants.h"
35 #include "llvm/ConstantHandling.h"
36 #include "llvm/DerivedTypes.h"
37 #include "llvm/GlobalVariable.h"
38 #include "llvm/Support/InstIterator.h"
39 #include "llvm/Support/InstVisitor.h"
40 #include "llvm/Support/CallSite.h"
41 #include "Support/Statistic.h"
45 Statistic<> NumCombined ("instcombine", "Number of insts combined");
46 Statistic<> NumConstProp("instcombine", "Number of constant folds");
47 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
49 class InstCombiner : public FunctionPass,
50 public InstVisitor<InstCombiner, Instruction*> {
51 // Worklist of all of the instructions that need to be simplified.
52 std::vector<Instruction*> WorkList;
54 void AddUsesToWorkList(Instruction &I) {
55 // The instruction was simplified, add all users of the instruction to
56 // the work lists because they might get more simplified now...
58 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
60 WorkList.push_back(cast<Instruction>(*UI));
63 // removeFromWorkList - remove all instances of I from the worklist.
64 void removeFromWorkList(Instruction *I);
66 virtual bool runOnFunction(Function &F);
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
72 // Visitation implementation - Implement instruction combining for different
73 // instruction types. The semantics are as follows:
75 // null - No change was made
76 // I - Change was made, I is still valid, I may be dead though
77 // otherwise - Change was made, replace I with returned instruction
79 Instruction *visitAdd(BinaryOperator &I);
80 Instruction *visitSub(BinaryOperator &I);
81 Instruction *visitMul(BinaryOperator &I);
82 Instruction *visitDiv(BinaryOperator &I);
83 Instruction *visitRem(BinaryOperator &I);
84 Instruction *visitAnd(BinaryOperator &I);
85 Instruction *visitOr (BinaryOperator &I);
86 Instruction *visitXor(BinaryOperator &I);
87 Instruction *visitSetCondInst(BinaryOperator &I);
88 Instruction *visitShiftInst(ShiftInst &I);
89 Instruction *visitCastInst(CastInst &CI);
90 Instruction *visitCallInst(CallInst &CI);
91 Instruction *visitInvokeInst(InvokeInst &II);
92 Instruction *visitPHINode(PHINode &PN);
93 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
94 Instruction *visitAllocationInst(AllocationInst &AI);
95 Instruction *visitLoadInst(LoadInst &LI);
96 Instruction *visitBranchInst(BranchInst &BI);
98 // visitInstruction - Specify what to return for unhandled instructions...
99 Instruction *visitInstruction(Instruction &I) { return 0; }
102 bool transformConstExprCastCall(CallSite CS);
104 // InsertNewInstBefore - insert an instruction New before instruction Old
105 // in the program. Add the new instruction to the worklist.
107 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
108 assert(New && New->getParent() == 0 &&
109 "New instruction already inserted into a basic block!");
110 BasicBlock *BB = Old.getParent();
111 BB->getInstList().insert(&Old, New); // Insert inst
112 WorkList.push_back(New); // Add to worklist
115 // ReplaceInstUsesWith - This method is to be used when an instruction is
116 // found to be dead, replacable with another preexisting expression. Here
117 // we add all uses of I to the worklist, replace all uses of I with the new
118 // value, then return I, so that the inst combiner will know that I was
121 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
122 AddUsesToWorkList(I); // Add all modified instrs to worklist
123 I.replaceAllUsesWith(V);
127 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
128 /// InsertBefore instruction. This is specialized a bit to avoid inserting
129 /// casts that are known to not do anything...
131 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
132 Instruction *InsertBefore);
134 // SimplifyCommutative - This performs a few simplifications for commutative
136 bool SimplifyCommutative(BinaryOperator &I);
139 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
142 // getComplexity: Assign a complexity or rank value to LLVM Values...
143 // 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
144 static unsigned getComplexity(Value *V) {
145 if (isa<Instruction>(V)) {
146 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
150 if (isa<Argument>(V)) return 2;
151 return isa<Constant>(V) ? 0 : 1;
154 // isOnlyUse - Return true if this instruction will be deleted if we stop using
156 static bool isOnlyUse(Value *V) {
157 return V->use_size() == 1 || isa<Constant>(V);
160 // SimplifyCommutative - This performs a few simplifications for commutative
163 // 1. Order operands such that they are listed from right (least complex) to
164 // left (most complex). This puts constants before unary operators before
167 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
168 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
170 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
171 bool Changed = false;
172 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
173 Changed = !I.swapOperands();
175 if (!I.isAssociative()) return Changed;
176 Instruction::BinaryOps Opcode = I.getOpcode();
177 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
178 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
179 if (isa<Constant>(I.getOperand(1))) {
180 Constant *Folded = ConstantExpr::get(I.getOpcode(),
181 cast<Constant>(I.getOperand(1)),
182 cast<Constant>(Op->getOperand(1)));
183 I.setOperand(0, Op->getOperand(0));
184 I.setOperand(1, Folded);
186 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
187 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
188 isOnlyUse(Op) && isOnlyUse(Op1)) {
189 Constant *C1 = cast<Constant>(Op->getOperand(1));
190 Constant *C2 = cast<Constant>(Op1->getOperand(1));
192 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
193 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
194 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
197 WorkList.push_back(New);
198 I.setOperand(0, New);
199 I.setOperand(1, Folded);
206 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
207 // if the LHS is a constant zero (which is the 'negate' form).
209 static inline Value *dyn_castNegVal(Value *V) {
210 if (BinaryOperator::isNeg(V))
211 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
213 // Constants can be considered to be negated values if they can be folded...
214 if (Constant *C = dyn_cast<Constant>(V))
215 return ConstantExpr::get(Instruction::Sub,
216 Constant::getNullValue(V->getType()), C);
220 static inline Value *dyn_castNotVal(Value *V) {
221 if (BinaryOperator::isNot(V))
222 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
224 // Constants can be considered to be not'ed values...
225 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
226 return ConstantExpr::get(Instruction::Xor,
227 ConstantIntegral::getAllOnesValue(C->getType()),C);
231 // dyn_castFoldableMul - If this value is a multiply that can be folded into
232 // other computations (because it has a constant operand), return the
233 // non-constant operand of the multiply.
235 static inline Value *dyn_castFoldableMul(Value *V) {
236 if (V->use_size() == 1 && V->getType()->isInteger())
237 if (Instruction *I = dyn_cast<Instruction>(V))
238 if (I->getOpcode() == Instruction::Mul)
239 if (isa<Constant>(I->getOperand(1)))
240 return I->getOperand(0);
244 // dyn_castMaskingAnd - If this value is an And instruction masking a value with
245 // a constant, return the constant being anded with.
247 template<class ValueType>
248 static inline Constant *dyn_castMaskingAnd(ValueType *V) {
249 if (Instruction *I = dyn_cast<Instruction>(V))
250 if (I->getOpcode() == Instruction::And)
251 return dyn_cast<Constant>(I->getOperand(1));
253 // If this is a constant, it acts just like we were masking with it.
254 return dyn_cast<Constant>(V);
257 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
259 static unsigned Log2(uint64_t Val) {
260 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
263 if (Val & 1) return 0; // Multiple bits set?
270 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
271 bool Changed = SimplifyCommutative(I);
272 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
274 // Eliminate 'add int %X, 0'
275 if (RHS == Constant::getNullValue(I.getType()))
276 return ReplaceInstUsesWith(I, LHS);
278 // Convert 'add X, X' to 'shl X, 1'
279 if (LHS == RHS && I.getType()->isInteger())
280 return new ShiftInst(Instruction::Shl, LHS,
281 ConstantInt::get(Type::UByteTy, 1));
284 if (Value *V = dyn_castNegVal(LHS))
285 return BinaryOperator::create(Instruction::Sub, RHS, V);
288 if (!isa<Constant>(RHS))
289 if (Value *V = dyn_castNegVal(RHS))
290 return BinaryOperator::create(Instruction::Sub, LHS, V);
292 // X*C + X --> X * (C+1)
293 if (dyn_castFoldableMul(LHS) == RHS) {
295 ConstantExpr::get(Instruction::Add,
296 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
297 ConstantInt::get(I.getType(), 1));
298 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
301 // X + X*C --> X * (C+1)
302 if (dyn_castFoldableMul(RHS) == LHS) {
304 ConstantExpr::get(Instruction::Add,
305 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
306 ConstantInt::get(I.getType(), 1));
307 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
310 // (A & C1)+(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
311 if (Constant *C1 = dyn_castMaskingAnd(LHS))
312 if (Constant *C2 = dyn_castMaskingAnd(RHS))
313 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
314 return BinaryOperator::create(Instruction::Or, LHS, RHS);
316 return Changed ? &I : 0;
319 // isSignBit - Return true if the value represented by the constant only has the
320 // highest order bit set.
321 static bool isSignBit(ConstantInt *CI) {
322 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
323 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
326 static unsigned getTypeSizeInBits(const Type *Ty) {
327 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
330 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
331 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
333 if (Op0 == Op1) // sub X, X -> 0
334 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
336 // If this is a 'B = x-(-A)', change to B = x+A...
337 if (Value *V = dyn_castNegVal(Op1))
338 return BinaryOperator::create(Instruction::Add, Op0, V);
340 // Replace (-1 - A) with (~A)...
341 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
342 if (C->isAllOnesValue())
343 return BinaryOperator::createNot(Op1);
345 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
346 if (Op1I->use_size() == 1) {
347 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
348 // is not used by anyone else...
350 if (Op1I->getOpcode() == Instruction::Sub) {
351 // Swap the two operands of the subexpr...
352 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
353 Op1I->setOperand(0, IIOp1);
354 Op1I->setOperand(1, IIOp0);
356 // Create the new top level add instruction...
357 return BinaryOperator::create(Instruction::Add, Op0, Op1);
360 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
362 if (Op1I->getOpcode() == Instruction::And &&
363 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
364 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
366 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
367 return BinaryOperator::create(Instruction::And, Op0, NewNot);
370 // X - X*C --> X * (1-C)
371 if (dyn_castFoldableMul(Op1I) == Op0) {
373 ConstantExpr::get(Instruction::Sub,
374 ConstantInt::get(I.getType(), 1),
375 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
376 assert(CP1 && "Couldn't constant fold 1-C?");
377 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
381 // X*C - X --> X * (C-1)
382 if (dyn_castFoldableMul(Op0) == Op1) {
384 ConstantExpr::get(Instruction::Sub,
385 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
386 ConstantInt::get(I.getType(), 1));
387 assert(CP1 && "Couldn't constant fold C - 1?");
388 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
394 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
395 bool Changed = SimplifyCommutative(I);
396 Value *Op0 = I.getOperand(0);
398 // Simplify mul instructions with a constant RHS...
399 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
400 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
402 // ((X << C1)*C2) == (X * (C2 << C1))
403 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
404 if (SI->getOpcode() == Instruction::Shl)
405 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
406 return BinaryOperator::create(Instruction::Mul, SI->getOperand(0),
409 const Type *Ty = CI->getType();
410 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
412 case -1: // X * -1 -> -X
413 return BinaryOperator::createNeg(Op0, I.getName());
415 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
417 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
420 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
421 return new ShiftInst(Instruction::Shl, Op0,
422 ConstantUInt::get(Type::UByteTy, C));
424 ConstantFP *Op1F = cast<ConstantFP>(Op1);
425 if (Op1F->isNullValue())
426 return ReplaceInstUsesWith(I, Op1);
428 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
429 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
430 if (Op1F->getValue() == 1.0)
431 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
435 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
436 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
437 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
439 return Changed ? &I : 0;
442 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
444 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
445 if (RHS->equalsInt(1))
446 return ReplaceInstUsesWith(I, I.getOperand(0));
448 // Check to see if this is an unsigned division with an exact power of 2,
449 // if so, convert to a right shift.
450 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
451 if (uint64_t Val = C->getValue()) // Don't break X / 0
452 if (uint64_t C = Log2(Val))
453 return new ShiftInst(Instruction::Shr, I.getOperand(0),
454 ConstantUInt::get(Type::UByteTy, C));
457 // 0 / X == 0, we don't need to preserve faults!
458 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
459 if (LHS->equalsInt(0))
460 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
466 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
467 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
468 if (RHS->equalsInt(1)) // X % 1 == 0
469 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
471 // Check to see if this is an unsigned remainder with an exact power of 2,
472 // if so, convert to a bitwise and.
473 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
474 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
476 return BinaryOperator::create(Instruction::And, I.getOperand(0),
477 ConstantUInt::get(I.getType(), Val-1));
480 // 0 % X == 0, we don't need to preserve faults!
481 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
482 if (LHS->equalsInt(0))
483 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
488 // isMaxValueMinusOne - return true if this is Max-1
489 static bool isMaxValueMinusOne(const ConstantInt *C) {
490 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
491 // Calculate -1 casted to the right type...
492 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
493 uint64_t Val = ~0ULL; // All ones
494 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
495 return CU->getValue() == Val-1;
498 const ConstantSInt *CS = cast<ConstantSInt>(C);
500 // Calculate 0111111111..11111
501 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
502 int64_t Val = INT64_MAX; // All ones
503 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
504 return CS->getValue() == Val-1;
507 // isMinValuePlusOne - return true if this is Min+1
508 static bool isMinValuePlusOne(const ConstantInt *C) {
509 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
510 return CU->getValue() == 1;
512 const ConstantSInt *CS = cast<ConstantSInt>(C);
514 // Calculate 1111111111000000000000
515 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
516 int64_t Val = -1; // All ones
517 Val <<= TypeBits-1; // Shift over to the right spot
518 return CS->getValue() == Val+1;
522 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
523 bool Changed = SimplifyCommutative(I);
524 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
526 // and X, X = X and X, 0 == 0
527 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
528 return ReplaceInstUsesWith(I, Op1);
531 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
532 if (RHS->isAllOnesValue())
533 return ReplaceInstUsesWith(I, Op0);
535 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
536 Value *X = Op0I->getOperand(0);
537 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
538 if (Op0I->getOpcode() == Instruction::Xor) {
539 if ((*RHS & *Op0CI)->isNullValue()) {
540 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
541 return BinaryOperator::create(Instruction::And, X, RHS);
542 } else if (isOnlyUse(Op0)) {
543 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
544 std::string Op0Name = Op0I->getName(); Op0I->setName("");
545 Instruction *And = BinaryOperator::create(Instruction::And,
547 InsertNewInstBefore(And, I);
548 return BinaryOperator::create(Instruction::Xor, And, *RHS & *Op0CI);
550 } else if (Op0I->getOpcode() == Instruction::Or) {
551 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
552 if ((*RHS & *Op0CI)->isNullValue())
553 return BinaryOperator::create(Instruction::And, X, RHS);
555 Constant *Together = *RHS & *Op0CI;
556 if (Together == RHS) // (X | C) & C --> C
557 return ReplaceInstUsesWith(I, RHS);
559 if (isOnlyUse(Op0)) {
560 if (Together != Op0CI) {
561 // (X | C1) & C2 --> (X | (C1&C2)) & C2
562 std::string Op0Name = Op0I->getName(); Op0I->setName("");
563 Instruction *Or = BinaryOperator::create(Instruction::Or, X,
565 InsertNewInstBefore(Or, I);
566 return BinaryOperator::create(Instruction::And, Or, RHS);
573 Value *Op0NotVal = dyn_castNotVal(Op0);
574 Value *Op1NotVal = dyn_castNotVal(Op1);
576 // (~A & ~B) == (~(A | B)) - Demorgan's Law
577 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
578 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
579 Op1NotVal,I.getName()+".demorgan");
580 InsertNewInstBefore(Or, I);
581 return BinaryOperator::createNot(Or);
584 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
585 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
587 return Changed ? &I : 0;
592 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
593 bool Changed = SimplifyCommutative(I);
594 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
596 // or X, X = X or X, 0 == X
597 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
598 return ReplaceInstUsesWith(I, Op0);
601 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
602 if (RHS->isAllOnesValue())
603 return ReplaceInstUsesWith(I, Op1);
605 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
606 // (X & C1) | C2 --> (X | C2) & (C1|C2)
607 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
608 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
609 std::string Op0Name = Op0I->getName(); Op0I->setName("");
610 Instruction *Or = BinaryOperator::create(Instruction::Or,
611 Op0I->getOperand(0), RHS,
613 InsertNewInstBefore(Or, I);
614 return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
617 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
618 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
619 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
620 std::string Op0Name = Op0I->getName(); Op0I->setName("");
621 Instruction *Or = BinaryOperator::create(Instruction::Or,
622 Op0I->getOperand(0), RHS,
624 InsertNewInstBefore(Or, I);
625 return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
630 // (A & C1)|(A & C2) == A & (C1|C2)
631 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
632 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
633 if (LHS->getOperand(0) == RHS->getOperand(0))
634 if (Constant *C0 = dyn_castMaskingAnd(LHS))
635 if (Constant *C1 = dyn_castMaskingAnd(RHS))
636 return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
639 Value *Op0NotVal = dyn_castNotVal(Op0);
640 Value *Op1NotVal = dyn_castNotVal(Op1);
642 if (Op1 == Op0NotVal) // ~A | A == -1
643 return ReplaceInstUsesWith(I,
644 ConstantIntegral::getAllOnesValue(I.getType()));
646 if (Op0 == Op1NotVal) // A | ~A == -1
647 return ReplaceInstUsesWith(I,
648 ConstantIntegral::getAllOnesValue(I.getType()));
650 // (~A | ~B) == (~(A & B)) - Demorgan's Law
651 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
652 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
653 Op1NotVal,I.getName()+".demorgan",
655 WorkList.push_back(And);
656 return BinaryOperator::createNot(And);
659 return Changed ? &I : 0;
664 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
665 bool Changed = SimplifyCommutative(I);
666 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
670 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
672 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
674 if (RHS->isNullValue())
675 return ReplaceInstUsesWith(I, Op0);
677 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
678 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
679 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
680 if (RHS == ConstantBool::True && SCI->use_size() == 1)
681 return new SetCondInst(SCI->getInverseCondition(),
682 SCI->getOperand(0), SCI->getOperand(1));
684 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
685 if (Op0I->getOpcode() == Instruction::And) {
686 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
687 if ((*RHS & *Op0CI)->isNullValue())
688 return BinaryOperator::create(Instruction::Or, Op0, RHS);
689 } else if (Op0I->getOpcode() == Instruction::Or) {
690 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
691 if ((*RHS & *Op0CI) == RHS)
692 return BinaryOperator::create(Instruction::And, Op0, ~*RHS);
697 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
699 return ReplaceInstUsesWith(I,
700 ConstantIntegral::getAllOnesValue(I.getType()));
702 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
704 return ReplaceInstUsesWith(I,
705 ConstantIntegral::getAllOnesValue(I.getType()));
707 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
708 if (Op1I->getOpcode() == Instruction::Or)
709 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
710 cast<BinaryOperator>(Op1I)->swapOperands();
713 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
718 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
719 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
720 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
721 cast<BinaryOperator>(Op0I)->swapOperands();
722 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
723 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
724 WorkList.push_back(cast<Instruction>(NotB));
725 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
730 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
731 if (Constant *C1 = dyn_castMaskingAnd(Op0))
732 if (Constant *C2 = dyn_castMaskingAnd(Op1))
733 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
734 return BinaryOperator::create(Instruction::Or, Op0, Op1);
736 return Changed ? &I : 0;
739 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
740 static Constant *AddOne(ConstantInt *C) {
741 Constant *Result = ConstantExpr::get(Instruction::Add, C,
742 ConstantInt::get(C->getType(), 1));
743 assert(Result && "Constant folding integer addition failed!");
746 static Constant *SubOne(ConstantInt *C) {
747 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
748 ConstantInt::get(C->getType(), 1));
749 assert(Result && "Constant folding integer addition failed!");
753 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
754 // true when both operands are equal...
756 static bool isTrueWhenEqual(Instruction &I) {
757 return I.getOpcode() == Instruction::SetEQ ||
758 I.getOpcode() == Instruction::SetGE ||
759 I.getOpcode() == Instruction::SetLE;
762 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
763 bool Changed = SimplifyCommutative(I);
764 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
765 const Type *Ty = Op0->getType();
769 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
771 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
772 if (isa<ConstantPointerNull>(Op1) &&
773 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
774 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
777 // setcc's with boolean values can always be turned into bitwise operations
778 if (Ty == Type::BoolTy) {
779 // If this is <, >, or !=, we can change this into a simple xor instruction
780 if (!isTrueWhenEqual(I))
781 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
783 // Otherwise we need to make a temporary intermediate instruction and insert
784 // it into the instruction stream. This is what we are after:
786 // seteq bool %A, %B -> ~(A^B)
787 // setle bool %A, %B -> ~A | B
788 // setge bool %A, %B -> A | ~B
790 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
791 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
793 InsertNewInstBefore(Xor, I);
794 return BinaryOperator::createNot(Xor, I.getName());
797 // Handle the setXe cases...
798 assert(I.getOpcode() == Instruction::SetGE ||
799 I.getOpcode() == Instruction::SetLE);
801 if (I.getOpcode() == Instruction::SetGE)
802 std::swap(Op0, Op1); // Change setge -> setle
804 // Now we just have the SetLE case.
805 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
806 InsertNewInstBefore(Not, I);
807 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
810 // Check to see if we are doing one of many comparisons against constant
811 // integers at the end of their ranges...
813 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
814 // Simplify seteq and setne instructions...
815 if (I.getOpcode() == Instruction::SetEQ ||
816 I.getOpcode() == Instruction::SetNE) {
817 bool isSetNE = I.getOpcode() == Instruction::SetNE;
819 // If the first operand is (and|or|xor) with a constant, and the second
820 // operand is a constant, simplify a bit.
821 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
822 switch (BO->getOpcode()) {
823 case Instruction::Add:
824 if (CI->isNullValue()) {
825 // Replace ((add A, B) != 0) with (A != -B) if A or B is
826 // efficiently invertible, or if the add has just this one use.
827 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
828 if (Value *NegVal = dyn_castNegVal(BOp1))
829 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
830 else if (Value *NegVal = dyn_castNegVal(BOp0))
831 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
832 else if (BO->use_size() == 1) {
833 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
835 InsertNewInstBefore(Neg, I);
836 return new SetCondInst(I.getOpcode(), BOp0, Neg);
840 case Instruction::Xor:
841 // For the xor case, we can xor two constants together, eliminating
843 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
844 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
848 case Instruction::Sub:
849 // Replace (([sub|xor] A, B) != 0) with (A != B)
850 if (CI->isNullValue())
851 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
855 case Instruction::Or:
856 // If bits are being or'd in that are not present in the constant we
857 // are comparing against, then the comparison could never succeed!
858 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
859 if (!(*BOC & *~*CI)->isNullValue())
860 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
863 case Instruction::And:
864 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
865 // If bits are being compared against that are and'd out, then the
866 // comparison can never succeed!
867 if (!(*CI & *~*BOC)->isNullValue())
868 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
870 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
871 // to be a signed value as appropriate.
872 if (isSignBit(BOC)) {
873 Value *X = BO->getOperand(0);
874 // If 'X' is not signed, insert a cast now...
875 if (!BOC->getType()->isSigned()) {
877 switch (BOC->getType()->getPrimitiveID()) {
878 case Type::UByteTyID: DestTy = Type::SByteTy; break;
879 case Type::UShortTyID: DestTy = Type::ShortTy; break;
880 case Type::UIntTyID: DestTy = Type::IntTy; break;
881 case Type::ULongTyID: DestTy = Type::LongTy; break;
882 default: assert(0 && "Invalid unsigned integer type!"); abort();
884 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
885 InsertNewInstBefore(NewCI, I);
888 return new SetCondInst(isSetNE ? Instruction::SetLT :
889 Instruction::SetGE, X,
890 Constant::getNullValue(X->getType()));
898 // Check to see if we are comparing against the minimum or maximum value...
899 if (CI->isMinValue()) {
900 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
901 return ReplaceInstUsesWith(I, ConstantBool::False);
902 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
903 return ReplaceInstUsesWith(I, ConstantBool::True);
904 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
905 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
906 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
907 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
909 } else if (CI->isMaxValue()) {
910 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
911 return ReplaceInstUsesWith(I, ConstantBool::False);
912 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
913 return ReplaceInstUsesWith(I, ConstantBool::True);
914 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
915 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
916 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
917 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
919 // Comparing against a value really close to min or max?
920 } else if (isMinValuePlusOne(CI)) {
921 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
922 return BinaryOperator::create(Instruction::SetEQ, Op0,
923 SubOne(CI), I.getName());
924 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
925 return BinaryOperator::create(Instruction::SetNE, Op0,
926 SubOne(CI), I.getName());
928 } else if (isMaxValueMinusOne(CI)) {
929 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
930 return BinaryOperator::create(Instruction::SetEQ, Op0,
931 AddOne(CI), I.getName());
932 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
933 return BinaryOperator::create(Instruction::SetNE, Op0,
934 AddOne(CI), I.getName());
938 return Changed ? &I : 0;
943 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
944 assert(I.getOperand(1)->getType() == Type::UByteTy);
945 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
946 bool isLeftShift = I.getOpcode() == Instruction::Shl;
948 // shl X, 0 == X and shr X, 0 == X
949 // shl 0, X == 0 and shr 0, X == 0
950 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
951 Op0 == Constant::getNullValue(Op0->getType()))
952 return ReplaceInstUsesWith(I, Op0);
954 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
956 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
957 if (CSI->isAllOnesValue())
958 return ReplaceInstUsesWith(I, CSI);
960 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
961 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
962 // of a signed value.
964 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
965 if (CUI->getValue() >= TypeBits &&
966 (!Op0->getType()->isSigned() || isLeftShift))
967 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
969 // ((X*C1) << C2) == (X * (C1 << C2))
970 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
971 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
972 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
973 return BinaryOperator::create(Instruction::Mul, BO->getOperand(0),
977 // If the operand is an bitwise operator with a constant RHS, and the
978 // shift is the only use, we can pull it out of the shift.
979 if (Op0->use_size() == 1)
980 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
981 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
982 bool isValid = true; // Valid only for And, Or, Xor
983 bool highBitSet = false; // Transform if high bit of constant set?
985 switch (Op0BO->getOpcode()) {
986 default: isValid = false; break; // Do not perform transform!
987 case Instruction::Or:
988 case Instruction::Xor:
991 case Instruction::And:
996 // If this is a signed shift right, and the high bit is modified
997 // by the logical operation, do not perform the transformation.
998 // The highBitSet boolean indicates the value of the high bit of
999 // the constant which would cause it to be modified for this
1002 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1003 uint64_t Val = Op0C->getRawValue();
1004 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1009 ConstantFoldShiftInstruction(I.getOpcode(), Op0C, CUI);
1011 Instruction *NewShift =
1012 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1015 InsertNewInstBefore(NewShift, I);
1017 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1022 // If this is a shift of a shift, see if we can fold the two together...
1023 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
1024 if (ConstantUInt *ShiftAmt1C =
1025 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
1026 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1027 unsigned ShiftAmt2 = CUI->getValue();
1029 // Check for (A << c1) << c2 and (A >> c1) >> c2
1030 if (I.getOpcode() == Op0SI->getOpcode()) {
1031 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
1032 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1033 ConstantUInt::get(Type::UByteTy, Amt));
1036 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1037 // signed types, we can only support the (A >> c1) << c2 configuration,
1038 // because it can not turn an arbitrary bit of A into a sign bit.
1039 if (I.getType()->isUnsigned() || isLeftShift) {
1040 // Calculate bitmask for what gets shifted off the edge...
1041 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
1043 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
1045 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
1048 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
1049 C, Op0SI->getOperand(0)->getName()+".mask");
1050 InsertNewInstBefore(Mask, I);
1052 // Figure out what flavor of shift we should use...
1053 if (ShiftAmt1 == ShiftAmt2)
1054 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1055 else if (ShiftAmt1 < ShiftAmt2) {
1056 return new ShiftInst(I.getOpcode(), Mask,
1057 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1059 return new ShiftInst(Op0SI->getOpcode(), Mask,
1060 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1070 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1073 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1074 const Type *DstTy) {
1076 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1077 // are identical and the bits don't get reinterpreted (for example
1078 // int->float->int would not be allowed)
1079 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
1082 // Allow free casting and conversion of sizes as long as the sign doesn't
1084 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
1085 unsigned SrcSize = SrcTy->getPrimitiveSize();
1086 unsigned MidSize = MidTy->getPrimitiveSize();
1087 unsigned DstSize = DstTy->getPrimitiveSize();
1089 // Cases where we are monotonically decreasing the size of the type are
1090 // always ok, regardless of what sign changes are going on.
1092 if (SrcSize >= MidSize && MidSize >= DstSize)
1095 // Cases where the source and destination type are the same, but the middle
1096 // type is bigger are noops.
1098 if (SrcSize == DstSize && MidSize > SrcSize)
1101 // If we are monotonically growing, things are more complex.
1103 if (SrcSize <= MidSize && MidSize <= DstSize) {
1104 // We have eight combinations of signedness to worry about. Here's the
1106 static const int SignTable[8] = {
1107 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1108 1, // U U U Always ok
1109 1, // U U S Always ok
1110 3, // U S U Ok iff SrcSize != MidSize
1111 3, // U S S Ok iff SrcSize != MidSize
1112 0, // S U U Never ok
1113 2, // S U S Ok iff MidSize == DstSize
1114 1, // S S U Always ok
1115 1, // S S S Always ok
1118 // Choose an action based on the current entry of the signtable that this
1119 // cast of cast refers to...
1120 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1121 switch (SignTable[Row]) {
1122 case 0: return false; // Never ok
1123 case 1: return true; // Always ok
1124 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1125 case 3: // Ok iff SrcSize != MidSize
1126 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1127 default: assert(0 && "Bad entry in sign table!");
1132 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1133 // like: short -> ushort -> uint, because this can create wrong results if
1134 // the input short is negative!
1139 static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1140 if (V->getType() == Ty || isa<Constant>(V)) return false;
1141 if (const CastInst *CI = dyn_cast<CastInst>(V))
1142 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1147 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1148 /// InsertBefore instruction. This is specialized a bit to avoid inserting
1149 /// casts that are known to not do anything...
1151 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1152 Instruction *InsertBefore) {
1153 if (V->getType() == DestTy) return V;
1154 if (Constant *C = dyn_cast<Constant>(V))
1155 return ConstantExpr::getCast(C, DestTy);
1157 CastInst *CI = new CastInst(V, DestTy, V->getName());
1158 InsertNewInstBefore(CI, *InsertBefore);
1162 // CastInst simplification
1164 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
1165 Value *Src = CI.getOperand(0);
1167 // If the user is casting a value to the same type, eliminate this cast
1169 if (CI.getType() == Src->getType())
1170 return ReplaceInstUsesWith(CI, Src);
1172 // If casting the result of another cast instruction, try to eliminate this
1175 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
1176 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1177 CSrc->getType(), CI.getType())) {
1178 // This instruction now refers directly to the cast's src operand. This
1179 // has a good chance of making CSrc dead.
1180 CI.setOperand(0, CSrc->getOperand(0));
1184 // If this is an A->B->A cast, and we are dealing with integral types, try
1185 // to convert this into a logical 'and' instruction.
1187 if (CSrc->getOperand(0)->getType() == CI.getType() &&
1188 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
1189 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1190 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1191 assert(CSrc->getType() != Type::ULongTy &&
1192 "Cannot have type bigger than ulong!");
1193 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
1194 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1195 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1200 // If casting the result of a getelementptr instruction with no offset, turn
1201 // this into a cast of the original pointer!
1203 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1204 bool AllZeroOperands = true;
1205 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1206 if (!isa<Constant>(GEP->getOperand(i)) ||
1207 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1208 AllZeroOperands = false;
1211 if (AllZeroOperands) {
1212 CI.setOperand(0, GEP->getOperand(0));
1217 // If the source value is an instruction with only this use, we can attempt to
1218 // propagate the cast into the instruction. Also, only handle integral types
1220 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
1221 if (SrcI->use_size() == 1 && Src->getType()->isIntegral() &&
1222 CI.getType()->isInteger()) { // Don't mess with casts to bool here
1223 const Type *DestTy = CI.getType();
1224 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1225 unsigned DestBitSize = getTypeSizeInBits(DestTy);
1227 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1228 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1230 switch (SrcI->getOpcode()) {
1231 case Instruction::Add:
1232 case Instruction::Mul:
1233 case Instruction::And:
1234 case Instruction::Or:
1235 case Instruction::Xor:
1236 // If we are discarding information, or just changing the sign, rewrite.
1237 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1238 // Don't insert two casts if they cannot be eliminated. We allow two
1239 // casts to be inserted if the sizes are the same. This could only be
1240 // converting signedness, which is a noop.
1241 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1242 !ValueRequiresCast(Op0, DestTy)) {
1243 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1244 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1245 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1246 ->getOpcode(), Op0c, Op1c);
1250 case Instruction::Shl:
1251 // Allow changing the sign of the source operand. Do not allow changing
1252 // the size of the shift, UNLESS the shift amount is a constant. We
1253 // mush not change variable sized shifts to a smaller size, because it
1254 // is undefined to shift more bits out than exist in the value.
1255 if (DestBitSize == SrcBitSize ||
1256 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1257 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1258 return new ShiftInst(Instruction::Shl, Op0c, Op1);
1267 // CallInst simplification
1269 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1270 if (transformConstExprCastCall(&CI)) return 0;
1274 // InvokeInst simplification
1276 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1277 if (transformConstExprCastCall(&II)) return 0;
1281 // getPromotedType - Return the specified type promoted as it would be to pass
1282 // though a va_arg area...
1283 static const Type *getPromotedType(const Type *Ty) {
1284 switch (Ty->getPrimitiveID()) {
1285 case Type::SByteTyID:
1286 case Type::ShortTyID: return Type::IntTy;
1287 case Type::UByteTyID:
1288 case Type::UShortTyID: return Type::UIntTy;
1289 case Type::FloatTyID: return Type::DoubleTy;
1294 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
1295 // attempt to move the cast to the arguments of the call/invoke.
1297 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1298 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1299 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1300 if (CE->getOpcode() != Instruction::Cast ||
1301 !isa<ConstantPointerRef>(CE->getOperand(0)))
1303 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1304 if (!isa<Function>(CPR->getValue())) return false;
1305 Function *Callee = cast<Function>(CPR->getValue());
1306 Instruction *Caller = CS.getInstruction();
1308 // Okay, this is a cast from a function to a different type. Unless doing so
1309 // would cause a type conversion of one of our arguments, change this call to
1310 // be a direct call with arguments casted to the appropriate types.
1312 const FunctionType *FT = Callee->getFunctionType();
1313 const Type *OldRetTy = Caller->getType();
1315 if (Callee->isExternal() &&
1316 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1317 return false; // Cannot transform this return value...
1319 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1320 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1322 CallSite::arg_iterator AI = CS.arg_begin();
1323 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1324 const Type *ParamTy = FT->getParamType(i);
1325 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1326 if (Callee->isExternal() && !isConvertible) return false;
1329 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1330 Callee->isExternal())
1331 return false; // Do not delete arguments unless we have a function body...
1333 // Okay, we decided that this is a safe thing to do: go ahead and start
1334 // inserting cast instructions as necessary...
1335 std::vector<Value*> Args;
1336 Args.reserve(NumActualArgs);
1338 AI = CS.arg_begin();
1339 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1340 const Type *ParamTy = FT->getParamType(i);
1341 if ((*AI)->getType() == ParamTy) {
1342 Args.push_back(*AI);
1344 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1345 InsertNewInstBefore(Cast, *Caller);
1346 Args.push_back(Cast);
1350 // If the function takes more arguments than the call was taking, add them
1352 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1353 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1355 // If we are removing arguments to the function, emit an obnoxious warning...
1356 if (FT->getNumParams() < NumActualArgs)
1357 if (!FT->isVarArg()) {
1358 std::cerr << "WARNING: While resolving call to function '"
1359 << Callee->getName() << "' arguments were dropped!\n";
1361 // Add all of the arguments in their promoted form to the arg list...
1362 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1363 const Type *PTy = getPromotedType((*AI)->getType());
1364 if (PTy != (*AI)->getType()) {
1365 // Must promote to pass through va_arg area!
1366 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1367 InsertNewInstBefore(Cast, *Caller);
1368 Args.push_back(Cast);
1370 Args.push_back(*AI);
1375 if (FT->getReturnType() == Type::VoidTy)
1376 Caller->setName(""); // Void type should not have a name...
1379 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1380 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1381 Args, Caller->getName(), Caller);
1383 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1386 // Insert a cast of the return type as necessary...
1388 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1389 if (NV->getType() != Type::VoidTy) {
1390 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1391 InsertNewInstBefore(NC, *Caller);
1392 AddUsesToWorkList(*Caller);
1394 NV = Constant::getNullValue(Caller->getType());
1398 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1399 Caller->replaceAllUsesWith(NV);
1400 Caller->getParent()->getInstList().erase(Caller);
1401 removeFromWorkList(Caller);
1407 // PHINode simplification
1409 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
1410 // If the PHI node only has one incoming value, eliminate the PHI node...
1411 if (PN.getNumIncomingValues() == 1)
1412 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
1414 // Otherwise if all of the incoming values are the same for the PHI, replace
1415 // the PHI node with the incoming value.
1418 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1419 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1420 if (InVal && PN.getIncomingValue(i) != InVal)
1421 return 0; // Not the same, bail out.
1423 InVal = PN.getIncomingValue(i);
1425 // The only case that could cause InVal to be null is if we have a PHI node
1426 // that only has entries for itself. In this case, there is no entry into the
1427 // loop, so kill the PHI.
1429 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
1431 // All of the incoming values are the same, replace the PHI node now.
1432 return ReplaceInstUsesWith(PN, InVal);
1436 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1437 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
1438 // If so, eliminate the noop.
1439 if ((GEP.getNumOperands() == 2 &&
1440 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
1441 GEP.getNumOperands() == 1)
1442 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
1444 // Combine Indices - If the source pointer to this getelementptr instruction
1445 // is a getelementptr instruction, combine the indices of the two
1446 // getelementptr instructions into a single instruction.
1448 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
1449 std::vector<Value *> Indices;
1451 // Can we combine the two pointer arithmetics offsets?
1452 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1453 isa<Constant>(GEP.getOperand(1))) {
1454 // Replace: gep (gep %P, long C1), long C2, ...
1455 // With: gep %P, long (C1+C2), ...
1456 Value *Sum = ConstantExpr::get(Instruction::Add,
1457 cast<Constant>(Src->getOperand(1)),
1458 cast<Constant>(GEP.getOperand(1)));
1459 assert(Sum && "Constant folding of longs failed!?");
1460 GEP.setOperand(0, Src->getOperand(0));
1461 GEP.setOperand(1, Sum);
1462 AddUsesToWorkList(*Src); // Reduce use count of Src
1464 } else if (Src->getNumOperands() == 2) {
1465 // Replace: gep (gep %P, long B), long A, ...
1466 // With: T = long A+B; gep %P, T, ...
1468 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1470 Src->getName()+".sum", &GEP);
1471 GEP.setOperand(0, Src->getOperand(0));
1472 GEP.setOperand(1, Sum);
1473 WorkList.push_back(cast<Instruction>(Sum));
1475 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
1476 Src->getNumOperands() != 1) {
1477 // Otherwise we can do the fold if the first index of the GEP is a zero
1478 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1479 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
1480 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1481 Constant::getNullValue(Type::LongTy)) {
1482 // If the src gep ends with a constant array index, merge this get into
1483 // it, even if we have a non-zero array index.
1484 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1485 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
1488 if (!Indices.empty())
1489 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
1491 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1492 // GEP of global variable. If all of the indices for this GEP are
1493 // constants, we can promote this to a constexpr instead of an instruction.
1495 // Scan for nonconstants...
1496 std::vector<Constant*> Indices;
1497 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1498 for (; I != E && isa<Constant>(*I); ++I)
1499 Indices.push_back(cast<Constant>(*I));
1501 if (I == E) { // If they are all constants...
1503 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1505 // Replace all uses of the GEP with the new constexpr...
1506 return ReplaceInstUsesWith(GEP, CE);
1513 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1514 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1515 if (AI.isArrayAllocation()) // Check C != 1
1516 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1517 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
1518 AllocationInst *New = 0;
1520 // Create and insert the replacement instruction...
1521 if (isa<MallocInst>(AI))
1522 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
1524 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
1525 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
1528 // Scan to the end of the allocation instructions, to skip over a block of
1529 // allocas if possible...
1531 BasicBlock::iterator It = New;
1532 while (isa<AllocationInst>(*It)) ++It;
1534 // Now that I is pointing to the first non-allocation-inst in the block,
1535 // insert our getelementptr instruction...
1537 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1538 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1540 // Now make everything use the getelementptr instead of the original
1542 ReplaceInstUsesWith(AI, V);
1548 /// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1549 /// constantexpr, return the constant value being addressed by the constant
1550 /// expression, or null if something is funny.
1552 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1553 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1554 return 0; // Do not allow stepping over the value!
1556 // Loop over all of the operands, tracking down which value we are
1558 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1559 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1560 ConstantStruct *CS = cast<ConstantStruct>(C);
1561 if (CU->getValue() >= CS->getValues().size()) return 0;
1562 C = cast<Constant>(CS->getValues()[CU->getValue()]);
1563 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1564 ConstantArray *CA = cast<ConstantArray>(C);
1565 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1566 C = cast<Constant>(CA->getValues()[CS->getValue()]);
1572 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1573 Value *Op = LI.getOperand(0);
1574 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1575 Op = CPR->getValue();
1577 // Instcombine load (constant global) into the value loaded...
1578 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
1579 if (GV->isConstant() && !GV->isExternal())
1580 return ReplaceInstUsesWith(LI, GV->getInitializer());
1582 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1583 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1584 if (CE->getOpcode() == Instruction::GetElementPtr)
1585 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1586 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
1587 if (GV->isConstant() && !GV->isExternal())
1588 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1589 return ReplaceInstUsesWith(LI, V);
1594 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1595 // Change br (not X), label True, label False to: br X, label False, True
1596 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
1597 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1598 BasicBlock *TrueDest = BI.getSuccessor(0);
1599 BasicBlock *FalseDest = BI.getSuccessor(1);
1600 // Swap Destinations and condition...
1602 BI.setSuccessor(0, FalseDest);
1603 BI.setSuccessor(1, TrueDest);
1610 void InstCombiner::removeFromWorkList(Instruction *I) {
1611 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1615 bool InstCombiner::runOnFunction(Function &F) {
1616 bool Changed = false;
1618 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
1620 while (!WorkList.empty()) {
1621 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1622 WorkList.pop_back();
1624 // Check to see if we can DCE or ConstantPropagate the instruction...
1625 // Check to see if we can DIE the instruction...
1626 if (isInstructionTriviallyDead(I)) {
1627 // Add operands to the worklist...
1628 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1629 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1630 WorkList.push_back(Op);
1633 BasicBlock::iterator BBI = I;
1634 if (dceInstruction(BBI)) {
1635 removeFromWorkList(I);
1640 // Instruction isn't dead, see if we can constant propagate it...
1641 if (Constant *C = ConstantFoldInstruction(I)) {
1642 // Add operands to the worklist...
1643 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1644 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1645 WorkList.push_back(Op);
1646 ReplaceInstUsesWith(*I, C);
1649 BasicBlock::iterator BBI = I;
1650 if (dceInstruction(BBI)) {
1651 removeFromWorkList(I);
1656 // Now that we have an instruction, try combining it to simplify it...
1657 if (Instruction *Result = visit(*I)) {
1659 // Should we replace the old instruction with a new one?
1661 // Instructions can end up on the worklist more than once. Make sure
1662 // we do not process an instruction that has been deleted.
1663 removeFromWorkList(I);
1664 ReplaceInstWithInst(I, Result);
1666 BasicBlock::iterator II = I;
1668 // If the instruction was modified, it's possible that it is now dead.
1669 // if so, remove it.
1670 if (dceInstruction(II)) {
1671 // Instructions may end up in the worklist more than once. Erase them
1673 removeFromWorkList(I);
1679 WorkList.push_back(Result);
1680 AddUsesToWorkList(*Result);
1689 Pass *createInstructionCombiningPass() {
1690 return new InstCombiner();