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 canonicalizations 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
116 // ReplaceInstUsesWith - This method is to be used when an instruction is
117 // found to be dead, replacable with another preexisting expression. Here
118 // we add all uses of I to the worklist, replace all uses of I with the new
119 // value, then return I, so that the inst combiner will know that I was
122 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
123 AddUsesToWorkList(I); // Add all modified instrs to worklist
124 I.replaceAllUsesWith(V);
128 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
129 /// InsertBefore instruction. This is specialized a bit to avoid inserting
130 /// casts that are known to not do anything...
132 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
133 Instruction *InsertBefore);
135 // SimplifyCommutative - This performs a few simplifications for commutative
137 bool SimplifyCommutative(BinaryOperator &I);
139 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
140 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
143 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
146 // getComplexity: Assign a complexity or rank value to LLVM Values...
147 // 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
148 static unsigned getComplexity(Value *V) {
149 if (isa<Instruction>(V)) {
150 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
154 if (isa<Argument>(V)) return 2;
155 return isa<Constant>(V) ? 0 : 1;
158 // isOnlyUse - Return true if this instruction will be deleted if we stop using
160 static bool isOnlyUse(Value *V) {
161 return V->use_size() == 1 || isa<Constant>(V);
164 // SimplifyCommutative - This performs a few simplifications for commutative
167 // 1. Order operands such that they are listed from right (least complex) to
168 // left (most complex). This puts constants before unary operators before
171 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
172 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
174 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
175 bool Changed = false;
176 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
177 Changed = !I.swapOperands();
179 if (!I.isAssociative()) return Changed;
180 Instruction::BinaryOps Opcode = I.getOpcode();
181 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
182 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
183 if (isa<Constant>(I.getOperand(1))) {
184 Constant *Folded = ConstantExpr::get(I.getOpcode(),
185 cast<Constant>(I.getOperand(1)),
186 cast<Constant>(Op->getOperand(1)));
187 I.setOperand(0, Op->getOperand(0));
188 I.setOperand(1, Folded);
190 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
191 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
192 isOnlyUse(Op) && isOnlyUse(Op1)) {
193 Constant *C1 = cast<Constant>(Op->getOperand(1));
194 Constant *C2 = cast<Constant>(Op1->getOperand(1));
196 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
197 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
198 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
201 WorkList.push_back(New);
202 I.setOperand(0, New);
203 I.setOperand(1, Folded);
210 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
211 // if the LHS is a constant zero (which is the 'negate' form).
213 static inline Value *dyn_castNegVal(Value *V) {
214 if (BinaryOperator::isNeg(V))
215 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
217 // Constants can be considered to be negated values if they can be folded...
218 if (Constant *C = dyn_cast<Constant>(V))
219 return ConstantExpr::get(Instruction::Sub,
220 Constant::getNullValue(V->getType()), C);
224 static inline Value *dyn_castNotVal(Value *V) {
225 if (BinaryOperator::isNot(V))
226 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
228 // Constants can be considered to be not'ed values...
229 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
230 return ConstantExpr::get(Instruction::Xor,
231 ConstantIntegral::getAllOnesValue(C->getType()),C);
235 // dyn_castFoldableMul - If this value is a multiply that can be folded into
236 // other computations (because it has a constant operand), return the
237 // non-constant operand of the multiply.
239 static inline Value *dyn_castFoldableMul(Value *V) {
240 if (V->use_size() == 1 && V->getType()->isInteger())
241 if (Instruction *I = dyn_cast<Instruction>(V))
242 if (I->getOpcode() == Instruction::Mul)
243 if (isa<Constant>(I->getOperand(1)))
244 return I->getOperand(0);
248 // dyn_castMaskingAnd - If this value is an And instruction masking a value with
249 // a constant, return the constant being anded with.
251 template<class ValueType>
252 static inline Constant *dyn_castMaskingAnd(ValueType *V) {
253 if (Instruction *I = dyn_cast<Instruction>(V))
254 if (I->getOpcode() == Instruction::And)
255 return dyn_cast<Constant>(I->getOperand(1));
257 // If this is a constant, it acts just like we were masking with it.
258 return dyn_cast<Constant>(V);
261 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
263 static unsigned Log2(uint64_t Val) {
264 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
267 if (Val & 1) return 0; // Multiple bits set?
275 /// AssociativeOpt - Perform an optimization on an associative operator. This
276 /// function is designed to check a chain of associative operators for a
277 /// potential to apply a certain optimization. Since the optimization may be
278 /// applicable if the expression was reassociated, this checks the chain, then
279 /// reassociates the expression as necessary to expose the optimization
280 /// opportunity. This makes use of a special Functor, which must define
281 /// 'shouldApply' and 'apply' methods.
283 template<typename Functor>
284 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
285 unsigned Opcode = Root.getOpcode();
286 Value *LHS = Root.getOperand(0);
288 // Quick check, see if the immediate LHS matches...
289 if (F.shouldApply(LHS))
290 return F.apply(Root);
292 // Otherwise, if the LHS is not of the same opcode as the root, return.
293 Instruction *LHSI = dyn_cast<Instruction>(LHS);
294 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->use_size() == 1) {
295 // Should we apply this transform to the RHS?
296 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
298 // If not to the RHS, check to see if we should apply to the LHS...
299 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
300 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
304 // If the functor wants to apply the optimization to the RHS of LHSI,
305 // reassociate the expression from ((? op A) op B) to (? op (A op B))
307 BasicBlock *BB = Root.getParent();
308 // All of the instructions have a single use and have no side-effects,
309 // because of this, we can pull them all into the current basic block.
310 if (LHSI->getParent() != BB) {
311 // Move all of the instructions from root to LHSI into the current
313 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
314 Instruction *LastUse = &Root;
315 while (TmpLHSI->getParent() == BB) {
317 TmpLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
320 // Loop over all of the instructions in other blocks, moving them into
322 Value *TmpLHS = TmpLHSI;
324 TmpLHSI = cast<Instruction>(TmpLHS);
325 // Remove from current block...
326 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
327 // Insert before the last instruction...
328 BB->getInstList().insert(LastUse, TmpLHSI);
329 TmpLHS = TmpLHSI->getOperand(0);
330 } while (TmpLHSI != LHSI);
333 // Now all of the instructions are in the current basic block, go ahead
334 // and perform the reassociation.
335 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
337 // First move the selected RHS to the LHS of the root...
338 Root.setOperand(0, LHSI->getOperand(1));
340 // Make what used to be the LHS of the root be the user of the root...
341 Value *ExtraOperand = TmpLHSI->getOperand(1);
342 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
343 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
344 BB->getInstList().remove(&Root); // Remove root from the BB
345 BB->getInstList().insert(TmpLHSI, &Root); // Insert root before TmpLHSI
347 // Now propagate the ExtraOperand down the chain of instructions until we
349 while (TmpLHSI != LHSI) {
350 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
351 Value *NextOp = NextLHSI->getOperand(1);
352 NextLHSI->setOperand(1, ExtraOperand);
354 ExtraOperand = NextOp;
357 // Now that the instructions are reassociated, have the functor perform
358 // the transformation...
359 return F.apply(Root);
362 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
368 // AddRHS - Implements: X + X --> X << 1
371 AddRHS(Value *rhs) : RHS(rhs) {}
372 bool shouldApply(Value *LHS) const { return LHS == RHS; }
373 Instruction *apply(BinaryOperator &Add) const {
374 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
375 ConstantInt::get(Type::UByteTy, 1));
379 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
381 struct AddMaskingAnd {
383 AddMaskingAnd(Constant *c) : C2(c) {}
384 bool shouldApply(Value *LHS) const {
385 if (Constant *C1 = dyn_castMaskingAnd(LHS))
386 return ConstantExpr::get(Instruction::And, C1, C2)->isNullValue();
389 Instruction *apply(BinaryOperator &Add) const {
390 return BinaryOperator::create(Instruction::Or, Add.getOperand(0),
397 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
398 bool Changed = SimplifyCommutative(I);
399 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
402 if (RHS == Constant::getNullValue(I.getType()))
403 return ReplaceInstUsesWith(I, LHS);
406 if (I.getType()->isInteger())
407 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
410 if (Value *V = dyn_castNegVal(LHS))
411 return BinaryOperator::create(Instruction::Sub, RHS, V);
414 if (!isa<Constant>(RHS))
415 if (Value *V = dyn_castNegVal(RHS))
416 return BinaryOperator::create(Instruction::Sub, LHS, V);
418 // X*C + X --> X * (C+1)
419 if (dyn_castFoldableMul(LHS) == RHS) {
421 ConstantExpr::get(Instruction::Add,
422 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
423 ConstantInt::get(I.getType(), 1));
424 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
427 // X + X*C --> X * (C+1)
428 if (dyn_castFoldableMul(RHS) == LHS) {
430 ConstantExpr::get(Instruction::Add,
431 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
432 ConstantInt::get(I.getType(), 1));
433 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
436 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
437 if (Constant *C2 = dyn_castMaskingAnd(RHS))
438 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
440 return Changed ? &I : 0;
443 // isSignBit - Return true if the value represented by the constant only has the
444 // highest order bit set.
445 static bool isSignBit(ConstantInt *CI) {
446 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
447 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
450 static unsigned getTypeSizeInBits(const Type *Ty) {
451 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
454 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
455 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
457 if (Op0 == Op1) // sub X, X -> 0
458 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
460 // If this is a 'B = x-(-A)', change to B = x+A...
461 if (Value *V = dyn_castNegVal(Op1))
462 return BinaryOperator::create(Instruction::Add, Op0, V);
464 // Replace (-1 - A) with (~A)...
465 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
466 if (C->isAllOnesValue())
467 return BinaryOperator::createNot(Op1);
469 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
470 if (Op1I->use_size() == 1) {
471 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
472 // is not used by anyone else...
474 if (Op1I->getOpcode() == Instruction::Sub) {
475 // Swap the two operands of the subexpr...
476 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
477 Op1I->setOperand(0, IIOp1);
478 Op1I->setOperand(1, IIOp0);
480 // Create the new top level add instruction...
481 return BinaryOperator::create(Instruction::Add, Op0, Op1);
484 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
486 if (Op1I->getOpcode() == Instruction::And &&
487 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
488 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
490 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
491 return BinaryOperator::create(Instruction::And, Op0, NewNot);
494 // X - X*C --> X * (1-C)
495 if (dyn_castFoldableMul(Op1I) == Op0) {
497 ConstantExpr::get(Instruction::Sub,
498 ConstantInt::get(I.getType(), 1),
499 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
500 assert(CP1 && "Couldn't constant fold 1-C?");
501 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
505 // X*C - X --> X * (C-1)
506 if (dyn_castFoldableMul(Op0) == Op1) {
508 ConstantExpr::get(Instruction::Sub,
509 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
510 ConstantInt::get(I.getType(), 1));
511 assert(CP1 && "Couldn't constant fold C - 1?");
512 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
518 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
519 bool Changed = SimplifyCommutative(I);
520 Value *Op0 = I.getOperand(0);
522 // Simplify mul instructions with a constant RHS...
523 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
524 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
526 // ((X << C1)*C2) == (X * (C2 << C1))
527 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
528 if (SI->getOpcode() == Instruction::Shl)
529 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
530 return BinaryOperator::create(Instruction::Mul, SI->getOperand(0),
533 if (CI->isNullValue())
534 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
535 if (CI->equalsInt(1)) // X * 1 == X
536 return ReplaceInstUsesWith(I, Op0);
537 if (CI->isAllOnesValue()) // X * -1 == 0 - X
538 return BinaryOperator::createNeg(Op0, I.getName());
540 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
541 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
542 return new ShiftInst(Instruction::Shl, Op0,
543 ConstantUInt::get(Type::UByteTy, C));
545 ConstantFP *Op1F = cast<ConstantFP>(Op1);
546 if (Op1F->isNullValue())
547 return ReplaceInstUsesWith(I, Op1);
549 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
550 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
551 if (Op1F->getValue() == 1.0)
552 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
556 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
557 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
558 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
560 return Changed ? &I : 0;
563 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
565 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
566 if (RHS->equalsInt(1))
567 return ReplaceInstUsesWith(I, I.getOperand(0));
569 // Check to see if this is an unsigned division with an exact power of 2,
570 // if so, convert to a right shift.
571 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
572 if (uint64_t Val = C->getValue()) // Don't break X / 0
573 if (uint64_t C = Log2(Val))
574 return new ShiftInst(Instruction::Shr, I.getOperand(0),
575 ConstantUInt::get(Type::UByteTy, C));
578 // 0 / X == 0, we don't need to preserve faults!
579 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
580 if (LHS->equalsInt(0))
581 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
587 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
588 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
589 if (RHS->equalsInt(1)) // X % 1 == 0
590 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
592 // Check to see if this is an unsigned remainder with an exact power of 2,
593 // if so, convert to a bitwise and.
594 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
595 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
597 return BinaryOperator::create(Instruction::And, I.getOperand(0),
598 ConstantUInt::get(I.getType(), Val-1));
601 // 0 % X == 0, we don't need to preserve faults!
602 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
603 if (LHS->equalsInt(0))
604 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
609 // isMaxValueMinusOne - return true if this is Max-1
610 static bool isMaxValueMinusOne(const ConstantInt *C) {
611 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
612 // Calculate -1 casted to the right type...
613 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
614 uint64_t Val = ~0ULL; // All ones
615 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
616 return CU->getValue() == Val-1;
619 const ConstantSInt *CS = cast<ConstantSInt>(C);
621 // Calculate 0111111111..11111
622 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
623 int64_t Val = INT64_MAX; // All ones
624 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
625 return CS->getValue() == Val-1;
628 // isMinValuePlusOne - return true if this is Min+1
629 static bool isMinValuePlusOne(const ConstantInt *C) {
630 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
631 return CU->getValue() == 1;
633 const ConstantSInt *CS = cast<ConstantSInt>(C);
635 // Calculate 1111111111000000000000
636 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
637 int64_t Val = -1; // All ones
638 Val <<= TypeBits-1; // Shift over to the right spot
639 return CS->getValue() == Val+1;
642 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
643 /// are carefully arranged to allow folding of expressions such as:
645 /// (A < B) | (A > B) --> (A != B)
647 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
648 /// represents that the comparison is true if A == B, and bit value '1' is true
651 static unsigned getSetCondCode(const SetCondInst *SCI) {
652 switch (SCI->getOpcode()) {
654 case Instruction::SetGT: return 1;
655 case Instruction::SetEQ: return 2;
656 case Instruction::SetGE: return 3;
657 case Instruction::SetLT: return 4;
658 case Instruction::SetNE: return 5;
659 case Instruction::SetLE: return 6;
662 assert(0 && "Invalid SetCC opcode!");
667 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
668 /// opcode and two operands into either a constant true or false, or a brand new
669 /// SetCC instruction.
670 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
672 case 0: return ConstantBool::False;
673 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
674 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
675 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
676 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
677 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
678 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
679 case 7: return ConstantBool::True;
680 default: assert(0 && "Illegal SetCCCode!"); return 0;
684 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
685 struct FoldSetCCLogical {
688 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
689 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
690 bool shouldApply(Value *V) const {
691 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
692 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
693 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
696 Instruction *apply(BinaryOperator &Log) const {
697 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
698 if (SCI->getOperand(0) != LHS) {
699 assert(SCI->getOperand(1) == LHS);
700 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
703 unsigned LHSCode = getSetCondCode(SCI);
704 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
706 switch (Log.getOpcode()) {
707 case Instruction::And: Code = LHSCode & RHSCode; break;
708 case Instruction::Or: Code = LHSCode | RHSCode; break;
709 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
710 default: assert(0 && "Illegal logical opcode!");
713 Value *RV = getSetCCValue(Code, LHS, RHS);
714 if (Instruction *I = dyn_cast<Instruction>(RV))
716 // Otherwise, it's a constant boolean value...
717 return IC.ReplaceInstUsesWith(Log, RV);
722 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
723 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
724 // guaranteed to be either a shift instruction or a binary operator.
725 Instruction *InstCombiner::OptAndOp(Instruction *Op,
726 ConstantIntegral *OpRHS,
727 ConstantIntegral *AndRHS,
728 BinaryOperator &TheAnd) {
729 Value *X = Op->getOperand(0);
730 switch (Op->getOpcode()) {
731 case Instruction::Xor:
732 if ((*AndRHS & *OpRHS)->isNullValue()) {
733 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
734 return BinaryOperator::create(Instruction::And, X, AndRHS);
735 } else if (Op->use_size() == 1) {
736 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
737 std::string OpName = Op->getName(); Op->setName("");
738 Instruction *And = BinaryOperator::create(Instruction::And,
740 InsertNewInstBefore(And, TheAnd);
741 return BinaryOperator::create(Instruction::Xor, And, *AndRHS & *OpRHS);
744 case Instruction::Or:
745 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
746 if ((*AndRHS & *OpRHS)->isNullValue())
747 return BinaryOperator::create(Instruction::And, X, AndRHS);
749 Constant *Together = *AndRHS & *OpRHS;
750 if (Together == AndRHS) // (X | C) & C --> C
751 return ReplaceInstUsesWith(TheAnd, AndRHS);
753 if (Op->use_size() == 1 && Together != OpRHS) {
754 // (X | C1) & C2 --> (X | (C1&C2)) & C2
755 std::string Op0Name = Op->getName(); Op->setName("");
756 Instruction *Or = BinaryOperator::create(Instruction::Or, X,
758 InsertNewInstBefore(Or, TheAnd);
759 return BinaryOperator::create(Instruction::And, Or, AndRHS);
763 case Instruction::Add:
764 if (Op->use_size() == 1) {
765 // Adding a one to a single bit bit-field should be turned into an XOR
766 // of the bit. First thing to check is to see if this AND is with a
767 // single bit constant.
768 unsigned long long AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
770 // Clear bits that are not part of the constant.
771 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
773 // If there is only one bit set...
774 if ((AndRHSV & (AndRHSV-1)) == 0) {
775 // Ok, at this point, we know that we are masking the result of the
776 // ADD down to exactly one bit. If the constant we are adding has
777 // no bits set below this bit, then we can eliminate the ADD.
778 unsigned long long AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
780 // Check to see if any bits below the one bit set in AndRHSV are set.
781 if ((AddRHS & (AndRHSV-1)) == 0) {
782 // If not, the only thing that can effect the output of the AND is
783 // the bit specified by AndRHSV. If that bit is set, the effect of
784 // the XOR is to toggle the bit. If it is clear, then the ADD has
786 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
787 TheAnd.setOperand(0, X);
790 std::string Name = Op->getName(); Op->setName("");
791 // Pull the XOR out of the AND.
792 Instruction *NewAnd =
793 BinaryOperator::create(Instruction::And, X, AndRHS, Name);
794 InsertNewInstBefore(NewAnd, TheAnd);
795 return BinaryOperator::create(Instruction::Xor, NewAnd, AndRHS);
802 case Instruction::Shl: {
803 // We know that the AND will not produce any of the bits shifted in, so if
804 // the anded constant includes them, clear them now!
806 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
807 Constant *CI = *AndRHS & *(*AllOne << *OpRHS);
809 TheAnd.setOperand(1, CI);
814 case Instruction::Shr:
815 // We know that the AND will not produce any of the bits shifted in, so if
816 // the anded constant includes them, clear them now! This only applies to
817 // unsigned shifts, because a signed shr may bring in set bits!
819 if (AndRHS->getType()->isUnsigned()) {
820 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
821 Constant *CI = *AndRHS & *(*AllOne >> *OpRHS);
823 TheAnd.setOperand(1, CI);
833 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
834 bool Changed = SimplifyCommutative(I);
835 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
837 // and X, X = X and X, 0 == 0
838 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
839 return ReplaceInstUsesWith(I, Op1);
842 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
843 if (RHS->isAllOnesValue())
844 return ReplaceInstUsesWith(I, Op0);
846 // Optimize a variety of ((val OP C1) & C2) combinations...
847 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
848 Instruction *Op0I = cast<Instruction>(Op0);
849 Value *X = Op0I->getOperand(0);
850 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
851 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
856 Value *Op0NotVal = dyn_castNotVal(Op0);
857 Value *Op1NotVal = dyn_castNotVal(Op1);
859 // (~A & ~B) == (~(A | B)) - Demorgan's Law
860 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
861 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
862 Op1NotVal,I.getName()+".demorgan");
863 InsertNewInstBefore(Or, I);
864 return BinaryOperator::createNot(Or);
867 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
868 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
870 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
871 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
872 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
875 return Changed ? &I : 0;
880 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
881 bool Changed = SimplifyCommutative(I);
882 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
884 // or X, X = X or X, 0 == X
885 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
886 return ReplaceInstUsesWith(I, Op0);
889 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
890 if (RHS->isAllOnesValue())
891 return ReplaceInstUsesWith(I, Op1);
893 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
894 // (X & C1) | C2 --> (X | C2) & (C1|C2)
895 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
896 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
897 std::string Op0Name = Op0I->getName(); Op0I->setName("");
898 Instruction *Or = BinaryOperator::create(Instruction::Or,
899 Op0I->getOperand(0), RHS,
901 InsertNewInstBefore(Or, I);
902 return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
905 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
906 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
907 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
908 std::string Op0Name = Op0I->getName(); Op0I->setName("");
909 Instruction *Or = BinaryOperator::create(Instruction::Or,
910 Op0I->getOperand(0), RHS,
912 InsertNewInstBefore(Or, I);
913 return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
918 // (A & C1)|(A & C2) == A & (C1|C2)
919 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
920 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
921 if (LHS->getOperand(0) == RHS->getOperand(0))
922 if (Constant *C0 = dyn_castMaskingAnd(LHS))
923 if (Constant *C1 = dyn_castMaskingAnd(RHS))
924 return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
927 Value *Op0NotVal = dyn_castNotVal(Op0);
928 Value *Op1NotVal = dyn_castNotVal(Op1);
930 if (Op1 == Op0NotVal) // ~A | A == -1
931 return ReplaceInstUsesWith(I,
932 ConstantIntegral::getAllOnesValue(I.getType()));
934 if (Op0 == Op1NotVal) // A | ~A == -1
935 return ReplaceInstUsesWith(I,
936 ConstantIntegral::getAllOnesValue(I.getType()));
938 // (~A | ~B) == (~(A & B)) - Demorgan's Law
939 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
940 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
941 Op1NotVal,I.getName()+".demorgan",
943 WorkList.push_back(And);
944 return BinaryOperator::createNot(And);
947 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
948 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
949 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
952 return Changed ? &I : 0;
957 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
958 bool Changed = SimplifyCommutative(I);
959 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
963 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
965 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
967 if (RHS->isNullValue())
968 return ReplaceInstUsesWith(I, Op0);
970 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
971 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
972 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
973 if (RHS == ConstantBool::True && SCI->use_size() == 1)
974 return new SetCondInst(SCI->getInverseCondition(),
975 SCI->getOperand(0), SCI->getOperand(1));
977 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
978 if (Op0I->getOpcode() == Instruction::And) {
979 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
980 if ((*RHS & *Op0CI)->isNullValue())
981 return BinaryOperator::create(Instruction::Or, Op0, RHS);
982 } else if (Op0I->getOpcode() == Instruction::Or) {
983 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
984 if ((*RHS & *Op0CI) == RHS)
985 return BinaryOperator::create(Instruction::And, Op0, ~*RHS);
990 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
992 return ReplaceInstUsesWith(I,
993 ConstantIntegral::getAllOnesValue(I.getType()));
995 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
997 return ReplaceInstUsesWith(I,
998 ConstantIntegral::getAllOnesValue(I.getType()));
1000 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
1001 if (Op1I->getOpcode() == Instruction::Or)
1002 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1003 cast<BinaryOperator>(Op1I)->swapOperands();
1005 std::swap(Op0, Op1);
1006 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1008 std::swap(Op0, Op1);
1011 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
1012 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
1013 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1014 cast<BinaryOperator>(Op0I)->swapOperands();
1015 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
1016 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
1017 WorkList.push_back(cast<Instruction>(NotB));
1018 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
1023 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
1024 if (Constant *C1 = dyn_castMaskingAnd(Op0))
1025 if (Constant *C2 = dyn_castMaskingAnd(Op1))
1026 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
1027 return BinaryOperator::create(Instruction::Or, Op0, Op1);
1029 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1030 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1031 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1034 return Changed ? &I : 0;
1037 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
1038 static Constant *AddOne(ConstantInt *C) {
1039 Constant *Result = ConstantExpr::get(Instruction::Add, C,
1040 ConstantInt::get(C->getType(), 1));
1041 assert(Result && "Constant folding integer addition failed!");
1044 static Constant *SubOne(ConstantInt *C) {
1045 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
1046 ConstantInt::get(C->getType(), 1));
1047 assert(Result && "Constant folding integer addition failed!");
1051 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1052 // true when both operands are equal...
1054 static bool isTrueWhenEqual(Instruction &I) {
1055 return I.getOpcode() == Instruction::SetEQ ||
1056 I.getOpcode() == Instruction::SetGE ||
1057 I.getOpcode() == Instruction::SetLE;
1060 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
1061 bool Changed = SimplifyCommutative(I);
1062 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1063 const Type *Ty = Op0->getType();
1067 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
1069 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1070 if (isa<ConstantPointerNull>(Op1) &&
1071 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
1072 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1075 // setcc's with boolean values can always be turned into bitwise operations
1076 if (Ty == Type::BoolTy) {
1077 // If this is <, >, or !=, we can change this into a simple xor instruction
1078 if (!isTrueWhenEqual(I))
1079 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
1081 // Otherwise we need to make a temporary intermediate instruction and insert
1082 // it into the instruction stream. This is what we are after:
1084 // seteq bool %A, %B -> ~(A^B)
1085 // setle bool %A, %B -> ~A | B
1086 // setge bool %A, %B -> A | ~B
1088 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
1089 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
1091 InsertNewInstBefore(Xor, I);
1092 return BinaryOperator::createNot(Xor, I.getName());
1095 // Handle the setXe cases...
1096 assert(I.getOpcode() == Instruction::SetGE ||
1097 I.getOpcode() == Instruction::SetLE);
1099 if (I.getOpcode() == Instruction::SetGE)
1100 std::swap(Op0, Op1); // Change setge -> setle
1102 // Now we just have the SetLE case.
1103 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1104 InsertNewInstBefore(Not, I);
1105 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
1108 // Check to see if we are doing one of many comparisons against constant
1109 // integers at the end of their ranges...
1111 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1112 // Simplify seteq and setne instructions...
1113 if (I.getOpcode() == Instruction::SetEQ ||
1114 I.getOpcode() == Instruction::SetNE) {
1115 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1117 // If the first operand is (and|or|xor) with a constant, and the second
1118 // operand is a constant, simplify a bit.
1119 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1120 switch (BO->getOpcode()) {
1121 case Instruction::Add:
1122 if (CI->isNullValue()) {
1123 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1124 // efficiently invertible, or if the add has just this one use.
1125 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1126 if (Value *NegVal = dyn_castNegVal(BOp1))
1127 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1128 else if (Value *NegVal = dyn_castNegVal(BOp0))
1129 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
1130 else if (BO->use_size() == 1) {
1131 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1133 InsertNewInstBefore(Neg, I);
1134 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1138 case Instruction::Xor:
1139 // For the xor case, we can xor two constants together, eliminating
1140 // the explicit xor.
1141 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1142 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
1146 case Instruction::Sub:
1147 // Replace (([sub|xor] A, B) != 0) with (A != B)
1148 if (CI->isNullValue())
1149 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1153 case Instruction::Or:
1154 // If bits are being or'd in that are not present in the constant we
1155 // are comparing against, then the comparison could never succeed!
1156 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1157 if (!(*BOC & *~*CI)->isNullValue())
1158 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
1161 case Instruction::And:
1162 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1163 // If bits are being compared against that are and'd out, then the
1164 // comparison can never succeed!
1165 if (!(*CI & *~*BOC)->isNullValue())
1166 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
1168 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1169 // to be a signed value as appropriate.
1170 if (isSignBit(BOC)) {
1171 Value *X = BO->getOperand(0);
1172 // If 'X' is not signed, insert a cast now...
1173 if (!BOC->getType()->isSigned()) {
1175 switch (BOC->getType()->getPrimitiveID()) {
1176 case Type::UByteTyID: DestTy = Type::SByteTy; break;
1177 case Type::UShortTyID: DestTy = Type::ShortTy; break;
1178 case Type::UIntTyID: DestTy = Type::IntTy; break;
1179 case Type::ULongTyID: DestTy = Type::LongTy; break;
1180 default: assert(0 && "Invalid unsigned integer type!"); abort();
1182 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1183 InsertNewInstBefore(NewCI, I);
1186 return new SetCondInst(isSetNE ? Instruction::SetLT :
1187 Instruction::SetGE, X,
1188 Constant::getNullValue(X->getType()));
1196 // Check to see if we are comparing against the minimum or maximum value...
1197 if (CI->isMinValue()) {
1198 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1199 return ReplaceInstUsesWith(I, ConstantBool::False);
1200 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1201 return ReplaceInstUsesWith(I, ConstantBool::True);
1202 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1203 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1204 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1205 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1207 } else if (CI->isMaxValue()) {
1208 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1209 return ReplaceInstUsesWith(I, ConstantBool::False);
1210 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1211 return ReplaceInstUsesWith(I, ConstantBool::True);
1212 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1213 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1214 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1215 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1217 // Comparing against a value really close to min or max?
1218 } else if (isMinValuePlusOne(CI)) {
1219 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1220 return BinaryOperator::create(Instruction::SetEQ, Op0,
1221 SubOne(CI), I.getName());
1222 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1223 return BinaryOperator::create(Instruction::SetNE, Op0,
1224 SubOne(CI), I.getName());
1226 } else if (isMaxValueMinusOne(CI)) {
1227 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1228 return BinaryOperator::create(Instruction::SetEQ, Op0,
1229 AddOne(CI), I.getName());
1230 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1231 return BinaryOperator::create(Instruction::SetNE, Op0,
1232 AddOne(CI), I.getName());
1236 return Changed ? &I : 0;
1241 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
1242 assert(I.getOperand(1)->getType() == Type::UByteTy);
1243 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1244 bool isLeftShift = I.getOpcode() == Instruction::Shl;
1246 // shl X, 0 == X and shr X, 0 == X
1247 // shl 0, X == 0 and shr 0, X == 0
1248 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
1249 Op0 == Constant::getNullValue(Op0->getType()))
1250 return ReplaceInstUsesWith(I, Op0);
1252 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1254 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1255 if (CSI->isAllOnesValue())
1256 return ReplaceInstUsesWith(I, CSI);
1258 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
1259 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1260 // of a signed value.
1262 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
1263 if (CUI->getValue() >= TypeBits &&
1264 (!Op0->getType()->isSigned() || isLeftShift))
1265 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1267 // ((X*C1) << C2) == (X * (C1 << C2))
1268 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1269 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1270 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
1271 return BinaryOperator::create(Instruction::Mul, BO->getOperand(0),
1275 // If the operand is an bitwise operator with a constant RHS, and the
1276 // shift is the only use, we can pull it out of the shift.
1277 if (Op0->use_size() == 1)
1278 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1279 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1280 bool isValid = true; // Valid only for And, Or, Xor
1281 bool highBitSet = false; // Transform if high bit of constant set?
1283 switch (Op0BO->getOpcode()) {
1284 default: isValid = false; break; // Do not perform transform!
1285 case Instruction::Or:
1286 case Instruction::Xor:
1289 case Instruction::And:
1294 // If this is a signed shift right, and the high bit is modified
1295 // by the logical operation, do not perform the transformation.
1296 // The highBitSet boolean indicates the value of the high bit of
1297 // the constant which would cause it to be modified for this
1300 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1301 uint64_t Val = Op0C->getRawValue();
1302 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1307 ConstantFoldShiftInstruction(I.getOpcode(), Op0C, CUI);
1309 Instruction *NewShift =
1310 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1313 InsertNewInstBefore(NewShift, I);
1315 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1320 // If this is a shift of a shift, see if we can fold the two together...
1321 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
1322 if (ConstantUInt *ShiftAmt1C =
1323 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
1324 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1325 unsigned ShiftAmt2 = CUI->getValue();
1327 // Check for (A << c1) << c2 and (A >> c1) >> c2
1328 if (I.getOpcode() == Op0SI->getOpcode()) {
1329 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
1330 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1331 ConstantUInt::get(Type::UByteTy, Amt));
1334 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1335 // signed types, we can only support the (A >> c1) << c2 configuration,
1336 // because it can not turn an arbitrary bit of A into a sign bit.
1337 if (I.getType()->isUnsigned() || isLeftShift) {
1338 // Calculate bitmask for what gets shifted off the edge...
1339 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
1341 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
1343 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
1346 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
1347 C, Op0SI->getOperand(0)->getName()+".mask");
1348 InsertNewInstBefore(Mask, I);
1350 // Figure out what flavor of shift we should use...
1351 if (ShiftAmt1 == ShiftAmt2)
1352 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1353 else if (ShiftAmt1 < ShiftAmt2) {
1354 return new ShiftInst(I.getOpcode(), Mask,
1355 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1357 return new ShiftInst(Op0SI->getOpcode(), Mask,
1358 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1368 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1371 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1372 const Type *DstTy) {
1374 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1375 // are identical and the bits don't get reinterpreted (for example
1376 // int->float->int would not be allowed)
1377 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
1380 // Allow free casting and conversion of sizes as long as the sign doesn't
1382 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
1383 unsigned SrcSize = SrcTy->getPrimitiveSize();
1384 unsigned MidSize = MidTy->getPrimitiveSize();
1385 unsigned DstSize = DstTy->getPrimitiveSize();
1387 // Cases where we are monotonically decreasing the size of the type are
1388 // always ok, regardless of what sign changes are going on.
1390 if (SrcSize >= MidSize && MidSize >= DstSize)
1393 // Cases where the source and destination type are the same, but the middle
1394 // type is bigger are noops.
1396 if (SrcSize == DstSize && MidSize > SrcSize)
1399 // If we are monotonically growing, things are more complex.
1401 if (SrcSize <= MidSize && MidSize <= DstSize) {
1402 // We have eight combinations of signedness to worry about. Here's the
1404 static const int SignTable[8] = {
1405 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1406 1, // U U U Always ok
1407 1, // U U S Always ok
1408 3, // U S U Ok iff SrcSize != MidSize
1409 3, // U S S Ok iff SrcSize != MidSize
1410 0, // S U U Never ok
1411 2, // S U S Ok iff MidSize == DstSize
1412 1, // S S U Always ok
1413 1, // S S S Always ok
1416 // Choose an action based on the current entry of the signtable that this
1417 // cast of cast refers to...
1418 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1419 switch (SignTable[Row]) {
1420 case 0: return false; // Never ok
1421 case 1: return true; // Always ok
1422 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1423 case 3: // Ok iff SrcSize != MidSize
1424 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1425 default: assert(0 && "Bad entry in sign table!");
1430 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1431 // like: short -> ushort -> uint, because this can create wrong results if
1432 // the input short is negative!
1437 static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1438 if (V->getType() == Ty || isa<Constant>(V)) return false;
1439 if (const CastInst *CI = dyn_cast<CastInst>(V))
1440 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1445 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1446 /// InsertBefore instruction. This is specialized a bit to avoid inserting
1447 /// casts that are known to not do anything...
1449 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1450 Instruction *InsertBefore) {
1451 if (V->getType() == DestTy) return V;
1452 if (Constant *C = dyn_cast<Constant>(V))
1453 return ConstantExpr::getCast(C, DestTy);
1455 CastInst *CI = new CastInst(V, DestTy, V->getName());
1456 InsertNewInstBefore(CI, *InsertBefore);
1460 // CastInst simplification
1462 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
1463 Value *Src = CI.getOperand(0);
1465 // If the user is casting a value to the same type, eliminate this cast
1467 if (CI.getType() == Src->getType())
1468 return ReplaceInstUsesWith(CI, Src);
1470 // If casting the result of another cast instruction, try to eliminate this
1473 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
1474 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1475 CSrc->getType(), CI.getType())) {
1476 // This instruction now refers directly to the cast's src operand. This
1477 // has a good chance of making CSrc dead.
1478 CI.setOperand(0, CSrc->getOperand(0));
1482 // If this is an A->B->A cast, and we are dealing with integral types, try
1483 // to convert this into a logical 'and' instruction.
1485 if (CSrc->getOperand(0)->getType() == CI.getType() &&
1486 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
1487 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1488 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1489 assert(CSrc->getType() != Type::ULongTy &&
1490 "Cannot have type bigger than ulong!");
1491 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
1492 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1493 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1498 // If casting the result of a getelementptr instruction with no offset, turn
1499 // this into a cast of the original pointer!
1501 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1502 bool AllZeroOperands = true;
1503 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1504 if (!isa<Constant>(GEP->getOperand(i)) ||
1505 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1506 AllZeroOperands = false;
1509 if (AllZeroOperands) {
1510 CI.setOperand(0, GEP->getOperand(0));
1515 // If the source value is an instruction with only this use, we can attempt to
1516 // propagate the cast into the instruction. Also, only handle integral types
1518 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
1519 if (SrcI->use_size() == 1 && Src->getType()->isIntegral() &&
1520 CI.getType()->isInteger()) { // Don't mess with casts to bool here
1521 const Type *DestTy = CI.getType();
1522 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1523 unsigned DestBitSize = getTypeSizeInBits(DestTy);
1525 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1526 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1528 switch (SrcI->getOpcode()) {
1529 case Instruction::Add:
1530 case Instruction::Mul:
1531 case Instruction::And:
1532 case Instruction::Or:
1533 case Instruction::Xor:
1534 // If we are discarding information, or just changing the sign, rewrite.
1535 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1536 // Don't insert two casts if they cannot be eliminated. We allow two
1537 // casts to be inserted if the sizes are the same. This could only be
1538 // converting signedness, which is a noop.
1539 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1540 !ValueRequiresCast(Op0, DestTy)) {
1541 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1542 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1543 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1544 ->getOpcode(), Op0c, Op1c);
1548 case Instruction::Shl:
1549 // Allow changing the sign of the source operand. Do not allow changing
1550 // the size of the shift, UNLESS the shift amount is a constant. We
1551 // mush not change variable sized shifts to a smaller size, because it
1552 // is undefined to shift more bits out than exist in the value.
1553 if (DestBitSize == SrcBitSize ||
1554 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1555 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1556 return new ShiftInst(Instruction::Shl, Op0c, Op1);
1565 // CallInst simplification
1567 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1568 if (transformConstExprCastCall(&CI)) return 0;
1572 // InvokeInst simplification
1574 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1575 if (transformConstExprCastCall(&II)) return 0;
1579 // getPromotedType - Return the specified type promoted as it would be to pass
1580 // though a va_arg area...
1581 static const Type *getPromotedType(const Type *Ty) {
1582 switch (Ty->getPrimitiveID()) {
1583 case Type::SByteTyID:
1584 case Type::ShortTyID: return Type::IntTy;
1585 case Type::UByteTyID:
1586 case Type::UShortTyID: return Type::UIntTy;
1587 case Type::FloatTyID: return Type::DoubleTy;
1592 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
1593 // attempt to move the cast to the arguments of the call/invoke.
1595 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1596 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1597 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1598 if (CE->getOpcode() != Instruction::Cast ||
1599 !isa<ConstantPointerRef>(CE->getOperand(0)))
1601 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1602 if (!isa<Function>(CPR->getValue())) return false;
1603 Function *Callee = cast<Function>(CPR->getValue());
1604 Instruction *Caller = CS.getInstruction();
1606 // Okay, this is a cast from a function to a different type. Unless doing so
1607 // would cause a type conversion of one of our arguments, change this call to
1608 // be a direct call with arguments casted to the appropriate types.
1610 const FunctionType *FT = Callee->getFunctionType();
1611 const Type *OldRetTy = Caller->getType();
1613 if (Callee->isExternal() &&
1614 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1615 return false; // Cannot transform this return value...
1617 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1618 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1620 CallSite::arg_iterator AI = CS.arg_begin();
1621 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1622 const Type *ParamTy = FT->getParamType(i);
1623 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1624 if (Callee->isExternal() && !isConvertible) return false;
1627 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1628 Callee->isExternal())
1629 return false; // Do not delete arguments unless we have a function body...
1631 // Okay, we decided that this is a safe thing to do: go ahead and start
1632 // inserting cast instructions as necessary...
1633 std::vector<Value*> Args;
1634 Args.reserve(NumActualArgs);
1636 AI = CS.arg_begin();
1637 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1638 const Type *ParamTy = FT->getParamType(i);
1639 if ((*AI)->getType() == ParamTy) {
1640 Args.push_back(*AI);
1642 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1643 InsertNewInstBefore(Cast, *Caller);
1644 Args.push_back(Cast);
1648 // If the function takes more arguments than the call was taking, add them
1650 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1651 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1653 // If we are removing arguments to the function, emit an obnoxious warning...
1654 if (FT->getNumParams() < NumActualArgs)
1655 if (!FT->isVarArg()) {
1656 std::cerr << "WARNING: While resolving call to function '"
1657 << Callee->getName() << "' arguments were dropped!\n";
1659 // Add all of the arguments in their promoted form to the arg list...
1660 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1661 const Type *PTy = getPromotedType((*AI)->getType());
1662 if (PTy != (*AI)->getType()) {
1663 // Must promote to pass through va_arg area!
1664 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1665 InsertNewInstBefore(Cast, *Caller);
1666 Args.push_back(Cast);
1668 Args.push_back(*AI);
1673 if (FT->getReturnType() == Type::VoidTy)
1674 Caller->setName(""); // Void type should not have a name...
1677 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1678 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1679 Args, Caller->getName(), Caller);
1681 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1684 // Insert a cast of the return type as necessary...
1686 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1687 if (NV->getType() != Type::VoidTy) {
1688 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1689 InsertNewInstBefore(NC, *Caller);
1690 AddUsesToWorkList(*Caller);
1692 NV = Constant::getNullValue(Caller->getType());
1696 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1697 Caller->replaceAllUsesWith(NV);
1698 Caller->getParent()->getInstList().erase(Caller);
1699 removeFromWorkList(Caller);
1705 // PHINode simplification
1707 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
1708 // If the PHI node only has one incoming value, eliminate the PHI node...
1709 if (PN.getNumIncomingValues() == 1)
1710 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
1712 // Otherwise if all of the incoming values are the same for the PHI, replace
1713 // the PHI node with the incoming value.
1716 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1717 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1718 if (InVal && PN.getIncomingValue(i) != InVal)
1719 return 0; // Not the same, bail out.
1721 InVal = PN.getIncomingValue(i);
1723 // The only case that could cause InVal to be null is if we have a PHI node
1724 // that only has entries for itself. In this case, there is no entry into the
1725 // loop, so kill the PHI.
1727 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
1729 // All of the incoming values are the same, replace the PHI node now.
1730 return ReplaceInstUsesWith(PN, InVal);
1734 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1735 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
1736 // If so, eliminate the noop.
1737 if ((GEP.getNumOperands() == 2 &&
1738 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
1739 GEP.getNumOperands() == 1)
1740 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
1742 // Combine Indices - If the source pointer to this getelementptr instruction
1743 // is a getelementptr instruction, combine the indices of the two
1744 // getelementptr instructions into a single instruction.
1746 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
1747 std::vector<Value *> Indices;
1749 // Can we combine the two pointer arithmetics offsets?
1750 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1751 isa<Constant>(GEP.getOperand(1))) {
1752 // Replace: gep (gep %P, long C1), long C2, ...
1753 // With: gep %P, long (C1+C2), ...
1754 Value *Sum = ConstantExpr::get(Instruction::Add,
1755 cast<Constant>(Src->getOperand(1)),
1756 cast<Constant>(GEP.getOperand(1)));
1757 assert(Sum && "Constant folding of longs failed!?");
1758 GEP.setOperand(0, Src->getOperand(0));
1759 GEP.setOperand(1, Sum);
1760 AddUsesToWorkList(*Src); // Reduce use count of Src
1762 } else if (Src->getNumOperands() == 2) {
1763 // Replace: gep (gep %P, long B), long A, ...
1764 // With: T = long A+B; gep %P, T, ...
1766 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1768 Src->getName()+".sum", &GEP);
1769 GEP.setOperand(0, Src->getOperand(0));
1770 GEP.setOperand(1, Sum);
1771 WorkList.push_back(cast<Instruction>(Sum));
1773 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
1774 Src->getNumOperands() != 1) {
1775 // Otherwise we can do the fold if the first index of the GEP is a zero
1776 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1777 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
1778 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1779 Constant::getNullValue(Type::LongTy)) {
1780 // If the src gep ends with a constant array index, merge this get into
1781 // it, even if we have a non-zero array index.
1782 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1783 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
1786 if (!Indices.empty())
1787 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
1789 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1790 // GEP of global variable. If all of the indices for this GEP are
1791 // constants, we can promote this to a constexpr instead of an instruction.
1793 // Scan for nonconstants...
1794 std::vector<Constant*> Indices;
1795 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1796 for (; I != E && isa<Constant>(*I); ++I)
1797 Indices.push_back(cast<Constant>(*I));
1799 if (I == E) { // If they are all constants...
1801 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1803 // Replace all uses of the GEP with the new constexpr...
1804 return ReplaceInstUsesWith(GEP, CE);
1811 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1812 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1813 if (AI.isArrayAllocation()) // Check C != 1
1814 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1815 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
1816 AllocationInst *New = 0;
1818 // Create and insert the replacement instruction...
1819 if (isa<MallocInst>(AI))
1820 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
1822 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
1823 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
1826 // Scan to the end of the allocation instructions, to skip over a block of
1827 // allocas if possible...
1829 BasicBlock::iterator It = New;
1830 while (isa<AllocationInst>(*It)) ++It;
1832 // Now that I is pointing to the first non-allocation-inst in the block,
1833 // insert our getelementptr instruction...
1835 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1836 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1838 // Now make everything use the getelementptr instead of the original
1840 ReplaceInstUsesWith(AI, V);
1846 /// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1847 /// constantexpr, return the constant value being addressed by the constant
1848 /// expression, or null if something is funny.
1850 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1851 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1852 return 0; // Do not allow stepping over the value!
1854 // Loop over all of the operands, tracking down which value we are
1856 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1857 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1858 ConstantStruct *CS = cast<ConstantStruct>(C);
1859 if (CU->getValue() >= CS->getValues().size()) return 0;
1860 C = cast<Constant>(CS->getValues()[CU->getValue()]);
1861 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1862 ConstantArray *CA = cast<ConstantArray>(C);
1863 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1864 C = cast<Constant>(CA->getValues()[CS->getValue()]);
1870 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1871 Value *Op = LI.getOperand(0);
1872 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1873 Op = CPR->getValue();
1875 // Instcombine load (constant global) into the value loaded...
1876 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
1877 if (GV->isConstant() && !GV->isExternal())
1878 return ReplaceInstUsesWith(LI, GV->getInitializer());
1880 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1881 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1882 if (CE->getOpcode() == Instruction::GetElementPtr)
1883 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1884 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
1885 if (GV->isConstant() && !GV->isExternal())
1886 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1887 return ReplaceInstUsesWith(LI, V);
1892 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1893 // Change br (not X), label True, label False to: br X, label False, True
1894 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
1895 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1896 BasicBlock *TrueDest = BI.getSuccessor(0);
1897 BasicBlock *FalseDest = BI.getSuccessor(1);
1898 // Swap Destinations and condition...
1900 BI.setSuccessor(0, FalseDest);
1901 BI.setSuccessor(1, TrueDest);
1908 void InstCombiner::removeFromWorkList(Instruction *I) {
1909 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1913 bool InstCombiner::runOnFunction(Function &F) {
1914 bool Changed = false;
1916 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
1918 while (!WorkList.empty()) {
1919 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1920 WorkList.pop_back();
1922 // Check to see if we can DCE or ConstantPropagate the instruction...
1923 // Check to see if we can DIE the instruction...
1924 if (isInstructionTriviallyDead(I)) {
1925 // Add operands to the worklist...
1926 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1927 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1928 WorkList.push_back(Op);
1931 BasicBlock::iterator BBI = I;
1932 if (dceInstruction(BBI)) {
1933 removeFromWorkList(I);
1938 // Instruction isn't dead, see if we can constant propagate it...
1939 if (Constant *C = ConstantFoldInstruction(I)) {
1940 // Add operands to the worklist...
1941 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1942 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1943 WorkList.push_back(Op);
1944 ReplaceInstUsesWith(*I, C);
1947 BasicBlock::iterator BBI = I;
1948 if (dceInstruction(BBI)) {
1949 removeFromWorkList(I);
1954 // Now that we have an instruction, try combining it to simplify it...
1955 if (Instruction *Result = visit(*I)) {
1957 // Should we replace the old instruction with a new one?
1959 // Instructions can end up on the worklist more than once. Make sure
1960 // we do not process an instruction that has been deleted.
1961 removeFromWorkList(I);
1962 ReplaceInstWithInst(I, Result);
1964 BasicBlock::iterator II = I;
1966 // If the instruction was modified, it's possible that it is now dead.
1967 // if so, remove it.
1968 if (dceInstruction(II)) {
1969 // Instructions may end up in the worklist more than once. Erase them
1971 removeFromWorkList(I);
1977 WorkList.push_back(Result);
1978 AddUsesToWorkList(*Result);
1987 Pass *createInstructionCombiningPass() {
1988 return new InstCombiner();