1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // InstructionCombining - Combine instructions to form fewer, simple
4 // instructions. This pass does not modify the CFG, and has a tendancy to
5 // make instructions dead, so a subsequent DIE pass is useful. This pass is
6 // where algebraic simplification happens.
8 // This pass combines things like:
14 // This is a simple worklist driven algorithm.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/Scalar.h"
19 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
20 #include "llvm/Transforms/Utils/Local.h"
21 #include "llvm/ConstantHandling.h"
22 #include "llvm/iMemory.h"
23 #include "llvm/iOther.h"
24 #include "llvm/iPHINode.h"
25 #include "llvm/iOperators.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/InstIterator.h"
28 #include "llvm/Support/InstVisitor.h"
29 #include "Support/StatisticReporter.h"
32 static Statistic<> NumCombined("instcombine\t- Number of insts combined");
35 class InstCombiner : public FunctionPass,
36 public InstVisitor<InstCombiner, Instruction*> {
37 // Worklist of all of the instructions that need to be simplified.
38 std::vector<Instruction*> WorkList;
40 void AddUsesToWorkList(Instruction &I) {
41 // The instruction was simplified, add all users of the instruction to
42 // the work lists because they might get more simplified now...
44 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
46 WorkList.push_back(cast<Instruction>(*UI));
50 virtual bool runOnFunction(Function &F);
52 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56 // Visitation implementation - Implement instruction combining for different
57 // instruction types. The semantics are as follows:
59 // null - No change was made
60 // I - Change was made, I is still valid, I may be dead though
61 // otherwise - Change was made, replace I with returned instruction
63 Instruction *visitAdd(BinaryOperator &I);
64 Instruction *visitSub(BinaryOperator &I);
65 Instruction *visitMul(BinaryOperator &I);
66 Instruction *visitDiv(BinaryOperator &I);
67 Instruction *visitRem(BinaryOperator &I);
68 Instruction *visitAnd(BinaryOperator &I);
69 Instruction *visitOr (BinaryOperator &I);
70 Instruction *visitXor(BinaryOperator &I);
71 Instruction *visitSetCondInst(BinaryOperator &I);
72 Instruction *visitShiftInst(Instruction &I);
73 Instruction *visitCastInst(CastInst &CI);
74 Instruction *visitPHINode(PHINode &PN);
75 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
77 // visitInstruction - Specify what to return for unhandled instructions...
78 Instruction *visitInstruction(Instruction &I) { return 0; }
80 // InsertNewInstBefore - insert an instruction New before instruction Old
81 // in the program. Add the new instruction to the worklist.
83 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
84 BasicBlock *BB = Old.getParent();
85 BB->getInstList().insert(&Old, New); // Insert inst
86 WorkList.push_back(New); // Add to worklist
89 // ReplaceInstUsesWith - This method is to be used when an instruction is
90 // found to be dead, replacable with another preexisting expression. Here
91 // we add all uses of I to the worklist, replace all uses of I with the new
92 // value, then return I, so that the inst combiner will know that I was
95 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
96 AddUsesToWorkList(I); // Add all modified instrs to worklist
97 I.replaceAllUsesWith(V);
102 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
106 // Make sure that this instruction has a constant on the right hand side if it
107 // has any constant arguments. If not, fix it an return true.
109 static bool SimplifyBinOp(BinaryOperator &I) {
110 if (isa<Constant>(I.getOperand(0)) && !isa<Constant>(I.getOperand(1)))
111 return !I.swapOperands();
115 // dyn_castNegInst - Given a 'sub' instruction, return the RHS of the
116 // instruction if the LHS is a constant zero (which is the 'negate' form).
118 static inline Value *dyn_castNegInst(Value *V) {
119 Instruction *I = dyn_cast<Instruction>(V);
120 if (!I || I->getOpcode() != Instruction::Sub) return 0;
122 if (I->getOperand(0) == Constant::getNullValue(I->getType()))
123 return I->getOperand(1);
127 static inline Value *dyn_castNotInst(Value *V) {
128 Instruction *I = dyn_cast<Instruction>(V);
129 if (!I || I->getOpcode() != Instruction::Xor) return 0;
131 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
132 if (CI->isAllOnesValue())
133 return I->getOperand(0);
137 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
138 bool Changed = SimplifyBinOp(I);
139 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
141 // Eliminate 'add int %X, 0'
142 if (RHS == Constant::getNullValue(I.getType()))
143 return ReplaceInstUsesWith(I, LHS);
146 if (Value *V = dyn_castNegInst(LHS))
147 return BinaryOperator::create(Instruction::Sub, RHS, V);
150 if (Value *V = dyn_castNegInst(RHS))
151 return BinaryOperator::create(Instruction::Sub, LHS, V);
153 // Simplify add instructions with a constant RHS...
154 if (Constant *Op2 = dyn_cast<Constant>(RHS)) {
155 if (BinaryOperator *ILHS = dyn_cast<BinaryOperator>(LHS)) {
156 if (ILHS->getOpcode() == Instruction::Add &&
157 isa<Constant>(ILHS->getOperand(1))) {
159 // %Y = add int %X, 1
160 // %Z = add int %Y, 1
162 // %Z = add int %X, 2
164 if (Constant *Val = *Op2 + *cast<Constant>(ILHS->getOperand(1))) {
165 I.setOperand(0, ILHS->getOperand(0));
166 I.setOperand(1, Val);
173 return Changed ? &I : 0;
176 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
177 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
179 if (Op0 == Op1) // sub X, X -> 0
180 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
182 // If this is a subtract instruction with a constant RHS, convert it to an add
183 // instruction of a negative constant
185 if (Constant *Op2 = dyn_cast<Constant>(Op1))
186 if (Constant *RHS = *Constant::getNullValue(I.getType()) - *Op2) // 0 - RHS
187 return BinaryOperator::create(Instruction::Add, Op0, RHS, I.getName());
189 // If this is a 'B = x-(-A)', change to B = x+A...
190 if (Value *V = dyn_castNegInst(Op1))
191 return BinaryOperator::create(Instruction::Add, Op0, V);
193 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression is
194 // not used by anyone else...
196 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
197 if (Op1I->use_size() == 1 && Op1I->getOpcode() == Instruction::Sub) {
198 // Swap the two operands of the subexpr...
199 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
200 Op1I->setOperand(0, IIOp1);
201 Op1I->setOperand(1, IIOp0);
203 // Create the new top level add instruction...
204 return BinaryOperator::create(Instruction::Add, Op0, Op1);
209 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
210 bool Changed = SimplifyBinOp(I);
211 Value *Op1 = I.getOperand(0);
213 // Simplify mul instructions with a constant RHS...
214 if (Constant *Op2 = dyn_cast<Constant>(I.getOperand(1))) {
215 if (I.getType()->isIntegral() && cast<ConstantInt>(Op2)->equalsInt(1))
216 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul int %X, 1'
218 if (I.getType()->isIntegral() && cast<ConstantInt>(Op2)->equalsInt(2))
219 // Convert 'mul int %X, 2' to 'add int %X, %X'
220 return BinaryOperator::create(Instruction::Add, Op1, Op1, I.getName());
222 if (Op2->isNullValue())
223 return ReplaceInstUsesWith(I, Op2); // Eliminate 'mul int %X, 0'
226 return Changed ? &I : 0;
230 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
232 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1)))
233 if (RHS->equalsInt(1))
234 return ReplaceInstUsesWith(I, I.getOperand(0));
239 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
241 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1)))
242 if (RHS->equalsInt(1))
243 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
248 // isMaxValueMinusOne - return true if this is Max-1
249 static bool isMaxValueMinusOne(const ConstantInt *C) {
250 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
251 // Calculate -1 casted to the right type...
252 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
253 uint64_t Val = ~0ULL; // All ones
254 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
255 return CU->getValue() == Val-1;
258 const ConstantSInt *CS = cast<ConstantSInt>(C);
260 // Calculate 0111111111..11111
261 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
262 int64_t Val = INT64_MAX; // All ones
263 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
264 return CS->getValue() == Val-1;
267 // isMinValuePlusOne - return true if this is Min+1
268 static bool isMinValuePlusOne(const ConstantInt *C) {
269 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
270 return CU->getValue() == 1;
272 const ConstantSInt *CS = cast<ConstantSInt>(C);
274 // Calculate 1111111111000000000000
275 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
276 int64_t Val = -1; // All ones
277 Val <<= TypeBits-1; // Shift over to the right spot
278 return CS->getValue() == Val+1;
282 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
283 bool Changed = SimplifyBinOp(I);
284 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
286 // and X, X = X and X, 0 == 0
287 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
288 return ReplaceInstUsesWith(I, Op1);
291 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
292 if (RHS->isAllOnesValue())
293 return ReplaceInstUsesWith(I, Op0);
295 return Changed ? &I : 0;
300 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
301 bool Changed = SimplifyBinOp(I);
302 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
304 // or X, X = X or X, 0 == X
305 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
306 return ReplaceInstUsesWith(I, Op0);
309 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
310 if (RHS->isAllOnesValue())
311 return ReplaceInstUsesWith(I, Op1);
313 return Changed ? &I : 0;
318 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
319 bool Changed = SimplifyBinOp(I);
320 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
324 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
326 if (ConstantIntegral *Op1C = dyn_cast<ConstantIntegral>(Op1)) {
328 if (Op1C->isNullValue())
329 return ReplaceInstUsesWith(I, Op0);
331 // Is this a "NOT" instruction?
332 if (Op1C->isAllOnesValue()) {
333 // xor (xor X, -1), -1 = not (not X) = X
334 if (Value *X = dyn_castNotInst(Op0))
335 return ReplaceInstUsesWith(I, X);
337 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
338 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0))
339 if (SCI->use_size() == 1)
340 return new SetCondInst(SCI->getInverseCondition(),
341 SCI->getOperand(0), SCI->getOperand(1));
345 return Changed ? &I : 0;
348 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
349 static Constant *AddOne(ConstantInt *C) {
350 Constant *Result = *C + *ConstantInt::get(C->getType(), 1);
351 assert(Result && "Constant folding integer addition failed!");
354 static Constant *SubOne(ConstantInt *C) {
355 Constant *Result = *C - *ConstantInt::get(C->getType(), 1);
356 assert(Result && "Constant folding integer addition failed!");
360 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
361 // true when both operands are equal...
363 static bool isTrueWhenEqual(Instruction &I) {
364 return I.getOpcode() == Instruction::SetEQ ||
365 I.getOpcode() == Instruction::SetGE ||
366 I.getOpcode() == Instruction::SetLE;
369 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
370 bool Changed = SimplifyBinOp(I);
371 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
372 const Type *Ty = Op0->getType();
376 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
378 // setcc <global*>, 0 - Global value addresses are never null!
379 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
380 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
382 // setcc's with boolean values can always be turned into bitwise operations
383 if (Ty == Type::BoolTy) {
384 // If this is <, >, or !=, we can change this into a simple xor instruction
385 if (!isTrueWhenEqual(I))
386 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
388 // Otherwise we need to make a temporary intermediate instruction and insert
389 // it into the instruction stream. This is what we are after:
391 // seteq bool %A, %B -> ~(A^B)
392 // setle bool %A, %B -> ~A | B
393 // setge bool %A, %B -> A | ~B
395 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
396 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
398 InsertNewInstBefore(Xor, I);
399 return BinaryOperator::createNot(Xor, I.getName());
402 // Handle the setXe cases...
403 assert(I.getOpcode() == Instruction::SetGE ||
404 I.getOpcode() == Instruction::SetLE);
406 if (I.getOpcode() == Instruction::SetGE)
407 std::swap(Op0, Op1); // Change setge -> setle
409 // Now we just have the SetLE case.
410 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
411 InsertNewInstBefore(Not, I);
412 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
415 // Check to see if we are doing one of many comparisons against constant
416 // integers at the end of their ranges...
418 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
419 // Check to see if we are comparing against the minimum or maximum value...
420 if (CI->isMinValue()) {
421 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
422 return ReplaceInstUsesWith(I, ConstantBool::False);
423 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
424 return ReplaceInstUsesWith(I, ConstantBool::True);
425 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
426 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
427 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
428 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
430 } else if (CI->isMaxValue()) {
431 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
432 return ReplaceInstUsesWith(I, ConstantBool::False);
433 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
434 return ReplaceInstUsesWith(I, ConstantBool::True);
435 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
436 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
437 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
438 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
440 // Comparing against a value really close to min or max?
441 } else if (isMinValuePlusOne(CI)) {
442 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
443 return BinaryOperator::create(Instruction::SetEQ, Op0,
444 SubOne(CI), I.getName());
445 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
446 return BinaryOperator::create(Instruction::SetNE, Op0,
447 SubOne(CI), I.getName());
449 } else if (isMaxValueMinusOne(CI)) {
450 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
451 return BinaryOperator::create(Instruction::SetEQ, Op0,
452 AddOne(CI), I.getName());
453 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
454 return BinaryOperator::create(Instruction::SetNE, Op0,
455 AddOne(CI), I.getName());
459 return Changed ? &I : 0;
464 Instruction *InstCombiner::visitShiftInst(Instruction &I) {
465 assert(I.getOperand(1)->getType() == Type::UByteTy);
466 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
468 // shl X, 0 == X and shr X, 0 == X
469 // shl 0, X == 0 and shr 0, X == 0
470 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
471 Op0 == Constant::getNullValue(Op0->getType()))
472 return ReplaceInstUsesWith(I, Op0);
474 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr of
477 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
478 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
479 if (CUI->getValue() >= TypeBits &&
480 !(Op0->getType()->isSigned() && I.getOpcode() == Instruction::Shr))
481 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
487 // isCIntegral - For the purposes of casting, we allow conversion of sizes and
488 // stuff as long as the value type acts basically integral like.
490 static bool isCIntegral(const Type *Ty) {
491 return Ty->isIntegral() || Ty == Type::BoolTy;
494 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
497 static inline bool isEliminableCastOfCast(const CastInst &CI,
498 const CastInst *CSrc) {
499 assert(CI.getOperand(0) == CSrc);
500 const Type *SrcTy = CSrc->getOperand(0)->getType();
501 const Type *MidTy = CSrc->getType();
502 const Type *DstTy = CI.getType();
504 // It is legal to eliminate the instruction if casting A->B->A if the sizes
505 // are identical and the bits don't get reinterpreted (for example
506 // int->float->int would not be allowed)
507 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertableTo(MidTy))
510 // Allow free casting and conversion of sizes as long as the sign doesn't
512 if (isCIntegral(SrcTy) && isCIntegral(MidTy) && isCIntegral(DstTy)) {
513 unsigned SrcSize = SrcTy->getPrimitiveSize();
514 unsigned MidSize = MidTy->getPrimitiveSize();
515 unsigned DstSize = DstTy->getPrimitiveSize();
517 // Cases where we are monotonically decreasing the size of the type are
518 // always ok, regardless of what sign changes are going on.
520 if (SrcSize >= MidSize && MidSize >= DstSize)
523 // If we are monotonically growing, things are more complex.
525 if (SrcSize <= MidSize && MidSize <= DstSize) {
526 // We have eight combinations of signedness to worry about. Here's the
528 static const int SignTable[8] = {
529 // CODE, SrcSigned, MidSigned, DstSigned, Comment
530 1, // U U U Always ok
531 1, // U U S Always ok
532 3, // U S U Ok iff SrcSize != MidSize
533 3, // U S S Ok iff SrcSize != MidSize
535 2, // S U S Ok iff MidSize == DstSize
536 1, // S S U Always ok
537 1, // S S S Always ok
540 // Choose an action based on the current entry of the signtable that this
541 // cast of cast refers to...
542 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
543 switch (SignTable[Row]) {
544 case 0: return false; // Never ok
545 case 1: return true; // Always ok
546 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
547 case 3: // Ok iff SrcSize != MidSize
548 return SrcSize != MidSize || SrcTy == Type::BoolTy;
549 default: assert(0 && "Bad entry in sign table!");
554 // Otherwise, we cannot succeed. Specifically we do not want to allow things
555 // like: short -> ushort -> uint, because this can create wrong results if
556 // the input short is negative!
562 // CastInst simplification
564 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
565 // If the user is casting a value to the same type, eliminate this cast
567 if (CI.getType() == CI.getOperand(0)->getType())
568 return ReplaceInstUsesWith(CI, CI.getOperand(0));
570 // If casting the result of another cast instruction, try to eliminate this
573 if (CastInst *CSrc = dyn_cast<CastInst>(CI.getOperand(0))) {
574 if (isEliminableCastOfCast(CI, CSrc)) {
575 // This instruction now refers directly to the cast's src operand. This
576 // has a good chance of making CSrc dead.
577 CI.setOperand(0, CSrc->getOperand(0));
581 // If this is an A->B->A cast, and we are dealing with integral types, try
582 // to convert this into a logical 'and' instruction.
584 if (CSrc->getOperand(0)->getType() == CI.getType() &&
585 CI.getType()->isIntegral() && CSrc->getType()->isIntegral() &&
586 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
587 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
588 assert(CSrc->getType() != Type::ULongTy &&
589 "Cannot have type bigger than ulong!");
590 unsigned AndValue = (1U << CSrc->getType()->getPrimitiveSize()*8)-1;
591 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
592 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
601 // PHINode simplification
603 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
604 // If the PHI node only has one incoming value, eliminate the PHI node...
605 if (PN.getNumIncomingValues() == 0)
606 return ReplaceInstUsesWith(PN, Constant::getNullValue(PN.getType()));
607 if (PN.getNumIncomingValues() == 1)
608 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
610 // Otherwise if all of the incoming values are the same for the PHI, replace
611 // the PHI node with the incoming value.
614 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
615 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
616 if (InVal && PN.getIncomingValue(i) != InVal)
617 return 0; // Not the same, bail out.
619 InVal = PN.getIncomingValue(i);
621 // The only case that could cause InVal to be null is if we have a PHI node
622 // that only has entries for itself. In this case, there is no entry into the
623 // loop, so kill the PHI.
625 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
627 // All of the incoming values are the same, replace the PHI node now.
628 return ReplaceInstUsesWith(PN, InVal);
632 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
633 // Is it 'getelementptr %P, uint 0' or 'getelementptr %P'
634 // If so, eliminate the noop.
635 if ((GEP.getNumOperands() == 2 &&
636 GEP.getOperand(1) == Constant::getNullValue(Type::UIntTy)) ||
637 GEP.getNumOperands() == 1)
638 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
640 // Combine Indices - If the source pointer to this getelementptr instruction
641 // is a getelementptr instruction, combine the indices of the two
642 // getelementptr instructions into a single instruction.
644 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
645 std::vector<Value *> Indices;
647 // Can we combine the two pointer arithmetics offsets?
648 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
649 isa<Constant>(GEP.getOperand(1))) {
650 // Replace the index list on this GEP with the index on the getelementptr
651 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
652 Indices[0] = *cast<Constant>(Src->getOperand(1)) +
653 *cast<Constant>(GEP.getOperand(1));
654 assert(Indices[0] != 0 && "Constant folding of uint's failed!?");
656 } else if (*GEP.idx_begin() == ConstantUInt::get(Type::UIntTy, 0)) {
657 // Otherwise we can do the fold if the first index of the GEP is a zero
658 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
659 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
662 if (!Indices.empty())
663 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
665 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
666 // GEP of global variable. If all of the indices for this GEP are
667 // constants, we can promote this to a constexpr instead of an instruction.
669 // Scan for nonconstants...
670 std::vector<Constant*> Indices;
671 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
672 for (; I != E && isa<Constant>(*I); ++I)
673 Indices.push_back(cast<Constant>(*I));
675 if (I == E) { // If they are all constants...
677 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
679 // Replace all uses of the GEP with the new constexpr...
680 return ReplaceInstUsesWith(GEP, CE);
688 bool InstCombiner::runOnFunction(Function &F) {
689 bool Changed = false;
691 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
693 while (!WorkList.empty()) {
694 Instruction *I = WorkList.back(); // Get an instruction from the worklist
697 // Now that we have an instruction, try combining it to simplify it...
698 if (Instruction *Result = visit(*I)) {
700 // Should we replace the old instruction with a new one?
702 // Instructions can end up on the worklist more than once. Make sure
703 // we do not process an instruction that has been deleted.
704 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
707 ReplaceInstWithInst(I, Result);
709 BasicBlock::iterator II = I;
711 // If the instruction was modified, it's possible that it is now dead.
713 if (dceInstruction(II)) {
714 // Instructions may end up in the worklist more than once. Erase them
716 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
723 WorkList.push_back(Result);
724 AddUsesToWorkList(*Result);
733 Pass *createInstructionCombiningPass() {
734 return new InstCombiner();