update obsolete comment.
[oota-llvm.git] / lib / Transforms / InstCombine / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "InstCombine.h"
39 #include "llvm/IntrinsicInst.h"
40 #include "llvm/Analysis/ConstantFolding.h"
41 #include "llvm/Analysis/InstructionSimplify.h"
42 #include "llvm/Analysis/MemoryBuiltins.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CFG.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/PatternMatch.h"
49 #include "llvm/ADT/SmallPtrSet.h"
50 #include "llvm/ADT/Statistic.h"
51 #include "llvm-c/Initialization.h"
52 #include <algorithm>
53 #include <climits>
54 using namespace llvm;
55 using namespace llvm::PatternMatch;
56
57 STATISTIC(NumCombined , "Number of insts combined");
58 STATISTIC(NumConstProp, "Number of constant folds");
59 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
60 STATISTIC(NumSunkInst , "Number of instructions sunk");
61 STATISTIC(NumExpand,    "Number of expansions");
62 STATISTIC(NumFactor   , "Number of factorizations");
63 STATISTIC(NumReassoc  , "Number of reassociations");
64
65 // Initialization Routines
66 void llvm::initializeInstCombine(PassRegistry &Registry) {
67   initializeInstCombinerPass(Registry);
68 }
69
70 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
71   initializeInstCombine(*unwrap(R));
72 }
73
74 char InstCombiner::ID = 0;
75 INITIALIZE_PASS(InstCombiner, "instcombine",
76                 "Combine redundant instructions", false, false)
77
78 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
79   AU.addPreservedID(LCSSAID);
80   AU.setPreservesCFG();
81 }
82
83
84 /// ShouldChangeType - Return true if it is desirable to convert a computation
85 /// from 'From' to 'To'.  We don't want to convert from a legal to an illegal
86 /// type for example, or from a smaller to a larger illegal type.
87 bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
88   assert(From->isIntegerTy() && To->isIntegerTy());
89   
90   // If we don't have TD, we don't know if the source/dest are legal.
91   if (!TD) return false;
92   
93   unsigned FromWidth = From->getPrimitiveSizeInBits();
94   unsigned ToWidth = To->getPrimitiveSizeInBits();
95   bool FromLegal = TD->isLegalInteger(FromWidth);
96   bool ToLegal = TD->isLegalInteger(ToWidth);
97   
98   // If this is a legal integer from type, and the result would be an illegal
99   // type, don't do the transformation.
100   if (FromLegal && !ToLegal)
101     return false;
102   
103   // Otherwise, if both are illegal, do not increase the size of the result. We
104   // do allow things like i160 -> i64, but not i64 -> i160.
105   if (!FromLegal && !ToLegal && ToWidth > FromWidth)
106     return false;
107   
108   return true;
109 }
110
111
112 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
113 /// operators which are associative or commutative:
114 //
115 //  Commutative operators:
116 //
117 //  1. Order operands such that they are listed from right (least complex) to
118 //     left (most complex).  This puts constants before unary operators before
119 //     binary operators.
120 //
121 //  Associative operators:
122 //
123 //  2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
124 //  3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
125 //
126 //  Associative and commutative operators:
127 //
128 //  4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
129 //  5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
130 //  6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
131 //     if C1 and C2 are constants.
132 //
133 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
134   Instruction::BinaryOps Opcode = I.getOpcode();
135   bool Changed = false;
136
137   do {
138     // Order operands such that they are listed from right (least complex) to
139     // left (most complex).  This puts constants before unary operators before
140     // binary operators.
141     if (I.isCommutative() && getComplexity(I.getOperand(0)) <
142         getComplexity(I.getOperand(1)))
143       Changed = !I.swapOperands();
144
145     BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
146     BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
147
148     if (I.isAssociative()) {
149       // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
150       if (Op0 && Op0->getOpcode() == Opcode) {
151         Value *A = Op0->getOperand(0);
152         Value *B = Op0->getOperand(1);
153         Value *C = I.getOperand(1);
154
155         // Does "B op C" simplify?
156         if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) {
157           // It simplifies to V.  Form "A op V".
158           I.setOperand(0, A);
159           I.setOperand(1, V);
160           Changed = true;
161           ++NumReassoc;
162           continue;
163         }
164       }
165
166       // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
167       if (Op1 && Op1->getOpcode() == Opcode) {
168         Value *A = I.getOperand(0);
169         Value *B = Op1->getOperand(0);
170         Value *C = Op1->getOperand(1);
171
172         // Does "A op B" simplify?
173         if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) {
174           // It simplifies to V.  Form "V op C".
175           I.setOperand(0, V);
176           I.setOperand(1, C);
177           Changed = true;
178           ++NumReassoc;
179           continue;
180         }
181       }
182     }
183
184     if (I.isAssociative() && I.isCommutative()) {
185       // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
186       if (Op0 && Op0->getOpcode() == Opcode) {
187         Value *A = Op0->getOperand(0);
188         Value *B = Op0->getOperand(1);
189         Value *C = I.getOperand(1);
190
191         // Does "C op A" simplify?
192         if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
193           // It simplifies to V.  Form "V op B".
194           I.setOperand(0, V);
195           I.setOperand(1, B);
196           Changed = true;
197           ++NumReassoc;
198           continue;
199         }
200       }
201
202       // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
203       if (Op1 && Op1->getOpcode() == Opcode) {
204         Value *A = I.getOperand(0);
205         Value *B = Op1->getOperand(0);
206         Value *C = Op1->getOperand(1);
207
208         // Does "C op A" simplify?
209         if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
210           // It simplifies to V.  Form "B op V".
211           I.setOperand(0, B);
212           I.setOperand(1, V);
213           Changed = true;
214           ++NumReassoc;
215           continue;
216         }
217       }
218
219       // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
220       // if C1 and C2 are constants.
221       if (Op0 && Op1 &&
222           Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
223           isa<Constant>(Op0->getOperand(1)) &&
224           isa<Constant>(Op1->getOperand(1)) &&
225           Op0->hasOneUse() && Op1->hasOneUse()) {
226         Value *A = Op0->getOperand(0);
227         Constant *C1 = cast<Constant>(Op0->getOperand(1));
228         Value *B = Op1->getOperand(0);
229         Constant *C2 = cast<Constant>(Op1->getOperand(1));
230
231         Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
232         Instruction *New = BinaryOperator::Create(Opcode, A, B, Op1->getName(),
233                                                   &I);
234         Worklist.Add(New);
235         I.setOperand(0, New);
236         I.setOperand(1, Folded);
237         Changed = true;
238         continue;
239       }
240     }
241
242     // No further simplifications.
243     return Changed;
244   } while (1);
245 }
246
247 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
248 /// "(X LOp Y) ROp (X LOp Z)".
249 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
250                                      Instruction::BinaryOps ROp) {
251   switch (LOp) {
252   default:
253     return false;
254
255   case Instruction::And:
256     // And distributes over Or and Xor.
257     switch (ROp) {
258     default:
259       return false;
260     case Instruction::Or:
261     case Instruction::Xor:
262       return true;
263     }
264
265   case Instruction::Mul:
266     // Multiplication distributes over addition and subtraction.
267     switch (ROp) {
268     default:
269       return false;
270     case Instruction::Add:
271     case Instruction::Sub:
272       return true;
273     }
274
275   case Instruction::Or:
276     // Or distributes over And.
277     switch (ROp) {
278     default:
279       return false;
280     case Instruction::And:
281       return true;
282     }
283   }
284 }
285
286 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
287 /// "(X ROp Z) LOp (Y ROp Z)".
288 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
289                                      Instruction::BinaryOps ROp) {
290   if (Instruction::isCommutative(ROp))
291     return LeftDistributesOverRight(ROp, LOp);
292   // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
293   // but this requires knowing that the addition does not overflow and other
294   // such subtleties.
295   return false;
296 }
297
298 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
299 /// which some other binary operation distributes over either by factorizing
300 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
301 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
302 /// a win).  Returns the simplified value, or null if it didn't simplify.
303 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
304   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
305   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
306   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
307   Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); // op
308
309   // Factorization.
310   if (Op0 && Op1 && Op0->getOpcode() == Op1->getOpcode()) {
311     // The instruction has the form "(A op' B) op (C op' D)".  Try to factorize
312     // a common term.
313     Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
314     Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
315     Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
316
317     // Does "X op' Y" always equal "Y op' X"?
318     bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
319
320     // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
321     if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
322       // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
323       // commutative case, "(A op' B) op (C op' A)"?
324       if (A == C || (InnerCommutative && A == D)) {
325         if (A != C)
326           std::swap(C, D);
327         // Consider forming "A op' (B op D)".
328         // If "B op D" simplifies then it can be formed with no cost.
329         Value *V = SimplifyBinOp(TopLevelOpcode, B, D, TD);
330         // If "B op D" doesn't simplify then only go on if both of the existing
331         // operations "A op' B" and "C op' D" will be zapped as no longer used.
332         if (!V && Op0->hasOneUse() && Op1->hasOneUse())
333           V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName());
334         if (V) {
335           ++NumFactor;
336           V = Builder->CreateBinOp(InnerOpcode, A, V);
337           V->takeName(&I);
338           return V;
339         }
340       }
341
342     // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
343     if (RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
344       // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
345       // commutative case, "(A op' B) op (B op' D)"?
346       if (B == D || (InnerCommutative && B == C)) {
347         if (B != D)
348           std::swap(C, D);
349         // Consider forming "(A op C) op' B".
350         // If "A op C" simplifies then it can be formed with no cost.
351         Value *V = SimplifyBinOp(TopLevelOpcode, A, C, TD);
352         // If "A op C" doesn't simplify then only go on if both of the existing
353         // operations "A op' B" and "C op' D" will be zapped as no longer used.
354         if (!V && Op0->hasOneUse() && Op1->hasOneUse())
355           V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->getName());
356         if (V) {
357           ++NumFactor;
358           V = Builder->CreateBinOp(InnerOpcode, V, B);
359           V->takeName(&I);
360           return V;
361         }
362       }
363   }
364
365   // Expansion.
366   if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
367     // The instruction has the form "(A op' B) op C".  See if expanding it out
368     // to "(A op C) op' (B op C)" results in simplifications.
369     Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
370     Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
371
372     // Do "A op C" and "B op C" both simplify?
373     if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, TD))
374       if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, TD)) {
375         // They do! Return "L op' R".
376         ++NumExpand;
377         // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
378         if ((L == A && R == B) ||
379             (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
380           return Op0;
381         // Otherwise return "L op' R" if it simplifies.
382         if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
383           return V;
384         // Otherwise, create a new instruction.
385         C = Builder->CreateBinOp(InnerOpcode, L, R);
386         C->takeName(&I);
387         return C;
388       }
389   }
390
391   if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
392     // The instruction has the form "A op (B op' C)".  See if expanding it out
393     // to "(A op B) op' (A op C)" results in simplifications.
394     Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
395     Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
396
397     // Do "A op B" and "A op C" both simplify?
398     if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, TD))
399       if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, TD)) {
400         // They do! Return "L op' R".
401         ++NumExpand;
402         // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
403         if ((L == B && R == C) ||
404             (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
405           return Op1;
406         // Otherwise return "L op' R" if it simplifies.
407         if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
408           return V;
409         // Otherwise, create a new instruction.
410         A = Builder->CreateBinOp(InnerOpcode, L, R);
411         A->takeName(&I);
412         return A;
413       }
414   }
415
416   return 0;
417 }
418
419 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
420 // if the LHS is a constant zero (which is the 'negate' form).
421 //
422 Value *InstCombiner::dyn_castNegVal(Value *V) const {
423   if (BinaryOperator::isNeg(V))
424     return BinaryOperator::getNegArgument(V);
425
426   // Constants can be considered to be negated values if they can be folded.
427   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
428     return ConstantExpr::getNeg(C);
429
430   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
431     if (C->getType()->getElementType()->isIntegerTy())
432       return ConstantExpr::getNeg(C);
433
434   return 0;
435 }
436
437 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
438 // instruction if the LHS is a constant negative zero (which is the 'negate'
439 // form).
440 //
441 Value *InstCombiner::dyn_castFNegVal(Value *V) const {
442   if (BinaryOperator::isFNeg(V))
443     return BinaryOperator::getFNegArgument(V);
444
445   // Constants can be considered to be negated values if they can be folded.
446   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
447     return ConstantExpr::getFNeg(C);
448
449   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
450     if (C->getType()->getElementType()->isFloatingPointTy())
451       return ConstantExpr::getFNeg(C);
452
453   return 0;
454 }
455
456 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
457                                              InstCombiner *IC) {
458   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
459     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
460   }
461
462   // Figure out if the constant is the left or the right argument.
463   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
464   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
465
466   if (Constant *SOC = dyn_cast<Constant>(SO)) {
467     if (ConstIsRHS)
468       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
469     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
470   }
471
472   Value *Op0 = SO, *Op1 = ConstOperand;
473   if (!ConstIsRHS)
474     std::swap(Op0, Op1);
475   
476   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
477     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
478                                     SO->getName()+".op");
479   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
480     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
481                                    SO->getName()+".cmp");
482   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
483     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
484                                    SO->getName()+".cmp");
485   llvm_unreachable("Unknown binary instruction type!");
486 }
487
488 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
489 // constant as the other operand, try to fold the binary operator into the
490 // select arguments.  This also works for Cast instructions, which obviously do
491 // not have a second operand.
492 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
493   // Don't modify shared select instructions
494   if (!SI->hasOneUse()) return 0;
495   Value *TV = SI->getOperand(1);
496   Value *FV = SI->getOperand(2);
497
498   if (isa<Constant>(TV) || isa<Constant>(FV)) {
499     // Bool selects with constant operands can be folded to logical ops.
500     if (SI->getType()->isIntegerTy(1)) return 0;
501
502     // If it's a bitcast involving vectors, make sure it has the same number of
503     // elements on both sides.
504     if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
505       const VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
506       const VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
507
508       // Verify that either both or neither are vectors.
509       if ((SrcTy == NULL) != (DestTy == NULL)) return 0;
510       // If vectors, verify that they have the same number of elements.
511       if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
512         return 0;
513     }
514     
515     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
516     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
517
518     return SelectInst::Create(SI->getCondition(),
519                               SelectTrueVal, SelectFalseVal);
520   }
521   return 0;
522 }
523
524
525 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
526 /// has a PHI node as operand #0, see if we can fold the instruction into the
527 /// PHI (which is only possible if all operands to the PHI are constants).
528 ///
529 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
530   PHINode *PN = cast<PHINode>(I.getOperand(0));
531   unsigned NumPHIValues = PN->getNumIncomingValues();
532   if (NumPHIValues == 0)
533     return 0;
534   
535   // We normally only transform phis with a single use.  However, if a PHI has
536   // multiple uses and they are all the same operation, we can fold *all* of the
537   // uses into the PHI.
538   if (!PN->hasOneUse()) {
539     // Walk the use list for the instruction, comparing them to I.
540     for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
541          UI != E; ++UI)
542       if (!I.isIdenticalTo(cast<Instruction>(*UI))) 
543         return 0;
544     // Otherwise, we can replace *all* users with the new PHI we form.
545   }
546   
547   // Check to see if all of the operands of the PHI are simple constants
548   // (constantint/constantfp/undef).  If there is one non-constant value,
549   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
550   // bail out.  We don't do arbitrary constant expressions here because moving
551   // their computation can be expensive without a cost model.
552   BasicBlock *NonConstBB = 0;
553   for (unsigned i = 0; i != NumPHIValues; ++i) {
554     Value *InVal = PN->getIncomingValue(i);
555     if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
556       continue;
557
558     if (isa<PHINode>(InVal)) return 0;  // Itself a phi.
559     if (NonConstBB) return 0;  // More than one non-const value.
560     
561     NonConstBB = PN->getIncomingBlock(i);
562
563     // If the InVal is an invoke at the end of the pred block, then we can't
564     // insert a computation after it without breaking the edge.
565     if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
566       if (II->getParent() == NonConstBB)
567         return 0;
568   }
569   
570   // If there is exactly one non-constant value, we can insert a copy of the
571   // operation in that block.  However, if this is a critical edge, we would be
572   // inserting the computation one some other paths (e.g. inside a loop).  Only
573   // do this if the pred block is unconditionally branching into the phi block.
574   if (NonConstBB != 0) {
575     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
576     if (!BI || !BI->isUnconditional()) return 0;
577   }
578
579   // Okay, we can do the transformation: create the new PHI node.
580   PHINode *NewPN = PHINode::Create(I.getType(), "");
581   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
582   InsertNewInstBefore(NewPN, *PN);
583   NewPN->takeName(PN);
584   
585   // If we are going to have to insert a new computation, do so right before the
586   // predecessors terminator.
587   if (NonConstBB)
588     Builder->SetInsertPoint(NonConstBB->getTerminator());
589   
590   // Next, add all of the operands to the PHI.
591   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
592     // We only currently try to fold the condition of a select when it is a phi,
593     // not the true/false values.
594     Value *TrueV = SI->getTrueValue();
595     Value *FalseV = SI->getFalseValue();
596     BasicBlock *PhiTransBB = PN->getParent();
597     for (unsigned i = 0; i != NumPHIValues; ++i) {
598       BasicBlock *ThisBB = PN->getIncomingBlock(i);
599       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
600       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
601       Value *InV = 0;
602       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
603         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
604       else
605         InV = Builder->CreateSelect(PN->getIncomingValue(i),
606                                     TrueVInPred, FalseVInPred, "phitmp");
607       NewPN->addIncoming(InV, ThisBB);
608     }
609   } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
610     Constant *C = cast<Constant>(I.getOperand(1));
611     for (unsigned i = 0; i != NumPHIValues; ++i) {
612       Value *InV = 0;
613       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
614         InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
615       else if (isa<ICmpInst>(CI))
616         InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
617                                   C, "phitmp");
618       else
619         InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
620                                   C, "phitmp");
621       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
622     }
623   } else if (I.getNumOperands() == 2) {
624     Constant *C = cast<Constant>(I.getOperand(1));
625     for (unsigned i = 0; i != NumPHIValues; ++i) {
626       Value *InV = 0;
627       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
628         InV = ConstantExpr::get(I.getOpcode(), InC, C);
629       else
630         InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
631                                    PN->getIncomingValue(i), C, "phitmp");
632       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
633     }
634   } else { 
635     CastInst *CI = cast<CastInst>(&I);
636     const Type *RetTy = CI->getType();
637     for (unsigned i = 0; i != NumPHIValues; ++i) {
638       Value *InV;
639       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
640         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
641       else 
642         InV = Builder->CreateCast(CI->getOpcode(),
643                                 PN->getIncomingValue(i), I.getType(), "phitmp");
644       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
645     }
646   }
647   
648   for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
649        UI != E; ) {
650     Instruction *User = cast<Instruction>(*UI++);
651     if (User == &I) continue;
652     ReplaceInstUsesWith(*User, NewPN);
653     EraseInstFromFunction(*User);
654   }
655   return ReplaceInstUsesWith(I, NewPN);
656 }
657
658 /// FindElementAtOffset - Given a type and a constant offset, determine whether
659 /// or not there is a sequence of GEP indices into the type that will land us at
660 /// the specified offset.  If so, fill them into NewIndices and return the
661 /// resultant element type, otherwise return null.
662 const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset, 
663                                           SmallVectorImpl<Value*> &NewIndices) {
664   if (!TD) return 0;
665   if (!Ty->isSized()) return 0;
666   
667   // Start with the index over the outer type.  Note that the type size
668   // might be zero (even if the offset isn't zero) if the indexed type
669   // is something like [0 x {int, int}]
670   const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
671   int64_t FirstIdx = 0;
672   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
673     FirstIdx = Offset/TySize;
674     Offset -= FirstIdx*TySize;
675     
676     // Handle hosts where % returns negative instead of values [0..TySize).
677     if (Offset < 0) {
678       --FirstIdx;
679       Offset += TySize;
680       assert(Offset >= 0);
681     }
682     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
683   }
684   
685   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
686     
687   // Index into the types.  If we fail, set OrigBase to null.
688   while (Offset) {
689     // Indexing into tail padding between struct/array elements.
690     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
691       return 0;
692     
693     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
694       const StructLayout *SL = TD->getStructLayout(STy);
695       assert(Offset < (int64_t)SL->getSizeInBytes() &&
696              "Offset must stay within the indexed type");
697       
698       unsigned Elt = SL->getElementContainingOffset(Offset);
699       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
700                                             Elt));
701       
702       Offset -= SL->getElementOffset(Elt);
703       Ty = STy->getElementType(Elt);
704     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
705       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
706       assert(EltSize && "Cannot index into a zero-sized array");
707       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
708       Offset %= EltSize;
709       Ty = AT->getElementType();
710     } else {
711       // Otherwise, we can't index into the middle of this atomic type, bail.
712       return 0;
713     }
714   }
715   
716   return Ty;
717 }
718
719
720
721 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
722   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
723
724   if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
725     return ReplaceInstUsesWith(GEP, V);
726
727   Value *PtrOp = GEP.getOperand(0);
728
729   // Eliminate unneeded casts for indices, and replace indices which displace
730   // by multiples of a zero size type with zero.
731   if (TD) {
732     bool MadeChange = false;
733     const Type *IntPtrTy = TD->getIntPtrType(GEP.getContext());
734
735     gep_type_iterator GTI = gep_type_begin(GEP);
736     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
737          I != E; ++I, ++GTI) {
738       // Skip indices into struct types.
739       const SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
740       if (!SeqTy) continue;
741
742       // If the element type has zero size then any index over it is equivalent
743       // to an index of zero, so replace it with zero if it is not zero already.
744       if (SeqTy->getElementType()->isSized() &&
745           TD->getTypeAllocSize(SeqTy->getElementType()) == 0)
746         if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
747           *I = Constant::getNullValue(IntPtrTy);
748           MadeChange = true;
749         }
750
751       if ((*I)->getType() != IntPtrTy) {
752         // If we are using a wider index than needed for this platform, shrink
753         // it to what we need.  If narrower, sign-extend it to what we need.
754         // This explicit cast can make subsequent optimizations more obvious.
755         *I = Builder->CreateIntCast(*I, IntPtrTy, true);
756         MadeChange = true;
757       }
758     }
759     if (MadeChange) return &GEP;
760   }
761
762   // Combine Indices - If the source pointer to this getelementptr instruction
763   // is a getelementptr instruction, combine the indices of the two
764   // getelementptr instructions into a single instruction.
765   //
766   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
767     // Note that if our source is a gep chain itself that we wait for that
768     // chain to be resolved before we perform this transformation.  This
769     // avoids us creating a TON of code in some cases.
770     //
771     if (GetElementPtrInst *SrcGEP =
772           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
773       if (SrcGEP->getNumOperands() == 2)
774         return 0;   // Wait until our source is folded to completion.
775
776     SmallVector<Value*, 8> Indices;
777
778     // Find out whether the last index in the source GEP is a sequential idx.
779     bool EndsWithSequential = false;
780     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
781          I != E; ++I)
782       EndsWithSequential = !(*I)->isStructTy();
783
784     // Can we combine the two pointer arithmetics offsets?
785     if (EndsWithSequential) {
786       // Replace: gep (gep %P, long B), long A, ...
787       // With:    T = long A+B; gep %P, T, ...
788       //
789       Value *Sum;
790       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
791       Value *GO1 = GEP.getOperand(1);
792       if (SO1 == Constant::getNullValue(SO1->getType())) {
793         Sum = GO1;
794       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
795         Sum = SO1;
796       } else {
797         // If they aren't the same type, then the input hasn't been processed
798         // by the loop above yet (which canonicalizes sequential index types to
799         // intptr_t).  Just avoid transforming this until the input has been
800         // normalized.
801         if (SO1->getType() != GO1->getType())
802           return 0;
803         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
804       }
805
806       // Update the GEP in place if possible.
807       if (Src->getNumOperands() == 2) {
808         GEP.setOperand(0, Src->getOperand(0));
809         GEP.setOperand(1, Sum);
810         return &GEP;
811       }
812       Indices.append(Src->op_begin()+1, Src->op_end()-1);
813       Indices.push_back(Sum);
814       Indices.append(GEP.op_begin()+2, GEP.op_end());
815     } else if (isa<Constant>(*GEP.idx_begin()) &&
816                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
817                Src->getNumOperands() != 1) {
818       // Otherwise we can do the fold if the first index of the GEP is a zero
819       Indices.append(Src->op_begin()+1, Src->op_end());
820       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
821     }
822
823     if (!Indices.empty())
824       return (GEP.isInBounds() && Src->isInBounds()) ?
825         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
826                                           Indices.end(), GEP.getName()) :
827         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
828                                   Indices.end(), GEP.getName());
829   }
830   
831   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
832   Value *StrippedPtr = PtrOp->stripPointerCasts();
833   if (StrippedPtr != PtrOp) {
834     const PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType());
835
836     bool HasZeroPointerIndex = false;
837     if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
838       HasZeroPointerIndex = C->isZero();
839     
840     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
841     // into     : GEP [10 x i8]* X, i32 0, ...
842     //
843     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
844     //           into     : GEP i8* X, ...
845     // 
846     // This occurs when the program declares an array extern like "int X[];"
847     if (HasZeroPointerIndex) {
848       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
849       if (const ArrayType *CATy =
850           dyn_cast<ArrayType>(CPTy->getElementType())) {
851         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
852         if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
853           // -> GEP i8* X, ...
854           SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
855           GetElementPtrInst *Res =
856             GetElementPtrInst::Create(StrippedPtr, Idx.begin(),
857                                       Idx.end(), GEP.getName());
858           Res->setIsInBounds(GEP.isInBounds());
859           return Res;
860         }
861         
862         if (const ArrayType *XATy =
863               dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
864           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
865           if (CATy->getElementType() == XATy->getElementType()) {
866             // -> GEP [10 x i8]* X, i32 0, ...
867             // At this point, we know that the cast source type is a pointer
868             // to an array of the same type as the destination pointer
869             // array.  Because the array type is never stepped over (there
870             // is a leading zero) we can fold the cast into this GEP.
871             GEP.setOperand(0, StrippedPtr);
872             return &GEP;
873           }
874         }
875       }
876     } else if (GEP.getNumOperands() == 2) {
877       // Transform things like:
878       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
879       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
880       const Type *SrcElTy = StrippedPtrTy->getElementType();
881       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
882       if (TD && SrcElTy->isArrayTy() &&
883           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
884           TD->getTypeAllocSize(ResElTy)) {
885         Value *Idx[2];
886         Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
887         Idx[1] = GEP.getOperand(1);
888         Value *NewGEP = GEP.isInBounds() ?
889           Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()) :
890           Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
891         // V and GEP are both pointer types --> BitCast
892         return new BitCastInst(NewGEP, GEP.getType());
893       }
894       
895       // Transform things like:
896       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
897       //   (where tmp = 8*tmp2) into:
898       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
899       
900       if (TD && SrcElTy->isArrayTy() && ResElTy->isIntegerTy(8)) {
901         uint64_t ArrayEltSize =
902             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
903         
904         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
905         // allow either a mul, shift, or constant here.
906         Value *NewIdx = 0;
907         ConstantInt *Scale = 0;
908         if (ArrayEltSize == 1) {
909           NewIdx = GEP.getOperand(1);
910           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
911         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
912           NewIdx = ConstantInt::get(CI->getType(), 1);
913           Scale = CI;
914         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
915           if (Inst->getOpcode() == Instruction::Shl &&
916               isa<ConstantInt>(Inst->getOperand(1))) {
917             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
918             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
919             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
920                                      1ULL << ShAmtVal);
921             NewIdx = Inst->getOperand(0);
922           } else if (Inst->getOpcode() == Instruction::Mul &&
923                      isa<ConstantInt>(Inst->getOperand(1))) {
924             Scale = cast<ConstantInt>(Inst->getOperand(1));
925             NewIdx = Inst->getOperand(0);
926           }
927         }
928         
929         // If the index will be to exactly the right offset with the scale taken
930         // out, perform the transformation. Note, we don't know whether Scale is
931         // signed or not. We'll use unsigned version of division/modulo
932         // operation after making sure Scale doesn't have the sign bit set.
933         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
934             Scale->getZExtValue() % ArrayEltSize == 0) {
935           Scale = ConstantInt::get(Scale->getType(),
936                                    Scale->getZExtValue() / ArrayEltSize);
937           if (Scale->getZExtValue() != 1) {
938             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
939                                                        false /*ZExt*/);
940             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
941           }
942
943           // Insert the new GEP instruction.
944           Value *Idx[2];
945           Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
946           Idx[1] = NewIdx;
947           Value *NewGEP = GEP.isInBounds() ?
948             Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2,GEP.getName()):
949             Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
950           // The NewGEP must be pointer typed, so must the old one -> BitCast
951           return new BitCastInst(NewGEP, GEP.getType());
952         }
953       }
954     }
955   }
956   
957   /// See if we can simplify:
958   ///   X = bitcast A* to B*
959   ///   Y = gep X, <...constant indices...>
960   /// into a gep of the original struct.  This is important for SROA and alias
961   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
962   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
963     if (TD &&
964         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
965       // Determine how much the GEP moves the pointer.  We are guaranteed to get
966       // a constant back from EmitGEPOffset.
967       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
968       int64_t Offset = OffsetV->getSExtValue();
969       
970       // If this GEP instruction doesn't move the pointer, just replace the GEP
971       // with a bitcast of the real input to the dest type.
972       if (Offset == 0) {
973         // If the bitcast is of an allocation, and the allocation will be
974         // converted to match the type of the cast, don't touch this.
975         if (isa<AllocaInst>(BCI->getOperand(0)) ||
976             isMalloc(BCI->getOperand(0))) {
977           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
978           if (Instruction *I = visitBitCast(*BCI)) {
979             if (I != BCI) {
980               I->takeName(BCI);
981               BCI->getParent()->getInstList().insert(BCI, I);
982               ReplaceInstUsesWith(*BCI, I);
983             }
984             return &GEP;
985           }
986         }
987         return new BitCastInst(BCI->getOperand(0), GEP.getType());
988       }
989       
990       // Otherwise, if the offset is non-zero, we need to find out if there is a
991       // field at Offset in 'A's type.  If so, we can pull the cast through the
992       // GEP.
993       SmallVector<Value*, 8> NewIndices;
994       const Type *InTy =
995         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
996       if (FindElementAtOffset(InTy, Offset, NewIndices)) {
997         Value *NGEP = GEP.isInBounds() ?
998           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
999                                      NewIndices.end()) :
1000           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
1001                              NewIndices.end());
1002         
1003         if (NGEP->getType() == GEP.getType())
1004           return ReplaceInstUsesWith(GEP, NGEP);
1005         NGEP->takeName(&GEP);
1006         return new BitCastInst(NGEP, GEP.getType());
1007       }
1008     }
1009   }    
1010     
1011   return 0;
1012 }
1013
1014
1015
1016 static bool IsOnlyNullComparedAndFreed(const Value &V) {
1017   for (Value::const_use_iterator UI = V.use_begin(), UE = V.use_end();
1018        UI != UE; ++UI) {
1019     const User *U = *UI;
1020     if (isFreeCall(U))
1021       continue;
1022     if (const ICmpInst *ICI = dyn_cast<ICmpInst>(U))
1023       if (ICI->isEquality() && isa<ConstantPointerNull>(ICI->getOperand(1)))
1024         continue;
1025     return false;
1026   }
1027   return true;
1028 }
1029
1030 Instruction *InstCombiner::visitMalloc(Instruction &MI) {
1031   // If we have a malloc call which is only used in any amount of comparisons
1032   // to null and free calls, delete the calls and replace the comparisons with
1033   // true or false as appropriate.
1034   if (IsOnlyNullComparedAndFreed(MI)) {
1035     for (Value::use_iterator UI = MI.use_begin(), UE = MI.use_end();
1036          UI != UE;) {
1037       // We can assume that every remaining use is a free call or an icmp eq/ne
1038       // to null, so the cast is safe.
1039       Instruction *I = cast<Instruction>(*UI);
1040
1041       // Early increment here, as we're about to get rid of the user.
1042       ++UI;
1043
1044       if (isFreeCall(I)) {
1045         EraseInstFromFunction(*cast<CallInst>(I));
1046         continue;
1047       }
1048       // Again, the cast is safe.
1049       ICmpInst *C = cast<ICmpInst>(I);
1050       ReplaceInstUsesWith(*C, ConstantInt::get(Type::getInt1Ty(C->getContext()),
1051                                                C->isFalseWhenEqual()));
1052       EraseInstFromFunction(*C);
1053     }
1054     return EraseInstFromFunction(MI);
1055   }
1056   return 0;
1057 }
1058
1059
1060
1061 Instruction *InstCombiner::visitFree(CallInst &FI) {
1062   Value *Op = FI.getArgOperand(0);
1063
1064   // free undef -> unreachable.
1065   if (isa<UndefValue>(Op)) {
1066     // Insert a new store to null because we cannot modify the CFG here.
1067     new StoreInst(ConstantInt::getTrue(FI.getContext()),
1068            UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
1069     return EraseInstFromFunction(FI);
1070   }
1071   
1072   // If we have 'free null' delete the instruction.  This can happen in stl code
1073   // when lots of inlining happens.
1074   if (isa<ConstantPointerNull>(Op))
1075     return EraseInstFromFunction(FI);
1076
1077   return 0;
1078 }
1079
1080
1081
1082 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1083   // Change br (not X), label True, label False to: br X, label False, True
1084   Value *X = 0;
1085   BasicBlock *TrueDest;
1086   BasicBlock *FalseDest;
1087   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
1088       !isa<Constant>(X)) {
1089     // Swap Destinations and condition...
1090     BI.setCondition(X);
1091     BI.setSuccessor(0, FalseDest);
1092     BI.setSuccessor(1, TrueDest);
1093     return &BI;
1094   }
1095
1096   // Cannonicalize fcmp_one -> fcmp_oeq
1097   FCmpInst::Predicate FPred; Value *Y;
1098   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
1099                              TrueDest, FalseDest)) &&
1100       BI.getCondition()->hasOneUse())
1101     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
1102         FPred == FCmpInst::FCMP_OGE) {
1103       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
1104       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
1105       
1106       // Swap Destinations and condition.
1107       BI.setSuccessor(0, FalseDest);
1108       BI.setSuccessor(1, TrueDest);
1109       Worklist.Add(Cond);
1110       return &BI;
1111     }
1112
1113   // Cannonicalize icmp_ne -> icmp_eq
1114   ICmpInst::Predicate IPred;
1115   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
1116                       TrueDest, FalseDest)) &&
1117       BI.getCondition()->hasOneUse())
1118     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
1119         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
1120         IPred == ICmpInst::ICMP_SGE) {
1121       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
1122       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
1123       // Swap Destinations and condition.
1124       BI.setSuccessor(0, FalseDest);
1125       BI.setSuccessor(1, TrueDest);
1126       Worklist.Add(Cond);
1127       return &BI;
1128     }
1129
1130   return 0;
1131 }
1132
1133 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
1134   Value *Cond = SI.getCondition();
1135   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
1136     if (I->getOpcode() == Instruction::Add)
1137       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1138         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
1139         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
1140           SI.setOperand(i,
1141                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
1142                                                 AddRHS));
1143         SI.setOperand(0, I->getOperand(0));
1144         Worklist.Add(I);
1145         return &SI;
1146       }
1147   }
1148   return 0;
1149 }
1150
1151 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
1152   Value *Agg = EV.getAggregateOperand();
1153
1154   if (!EV.hasIndices())
1155     return ReplaceInstUsesWith(EV, Agg);
1156
1157   if (Constant *C = dyn_cast<Constant>(Agg)) {
1158     if (isa<UndefValue>(C))
1159       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
1160       
1161     if (isa<ConstantAggregateZero>(C))
1162       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
1163
1164     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
1165       // Extract the element indexed by the first index out of the constant
1166       Value *V = C->getOperand(*EV.idx_begin());
1167       if (EV.getNumIndices() > 1)
1168         // Extract the remaining indices out of the constant indexed by the
1169         // first index
1170         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
1171       else
1172         return ReplaceInstUsesWith(EV, V);
1173     }
1174     return 0; // Can't handle other constants
1175   } 
1176   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
1177     // We're extracting from an insertvalue instruction, compare the indices
1178     const unsigned *exti, *exte, *insi, *inse;
1179     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
1180          exte = EV.idx_end(), inse = IV->idx_end();
1181          exti != exte && insi != inse;
1182          ++exti, ++insi) {
1183       if (*insi != *exti)
1184         // The insert and extract both reference distinctly different elements.
1185         // This means the extract is not influenced by the insert, and we can
1186         // replace the aggregate operand of the extract with the aggregate
1187         // operand of the insert. i.e., replace
1188         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1189         // %E = extractvalue { i32, { i32 } } %I, 0
1190         // with
1191         // %E = extractvalue { i32, { i32 } } %A, 0
1192         return ExtractValueInst::Create(IV->getAggregateOperand(),
1193                                         EV.idx_begin(), EV.idx_end());
1194     }
1195     if (exti == exte && insi == inse)
1196       // Both iterators are at the end: Index lists are identical. Replace
1197       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1198       // %C = extractvalue { i32, { i32 } } %B, 1, 0
1199       // with "i32 42"
1200       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
1201     if (exti == exte) {
1202       // The extract list is a prefix of the insert list. i.e. replace
1203       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1204       // %E = extractvalue { i32, { i32 } } %I, 1
1205       // with
1206       // %X = extractvalue { i32, { i32 } } %A, 1
1207       // %E = insertvalue { i32 } %X, i32 42, 0
1208       // by switching the order of the insert and extract (though the
1209       // insertvalue should be left in, since it may have other uses).
1210       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
1211                                                  EV.idx_begin(), EV.idx_end());
1212       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
1213                                      insi, inse);
1214     }
1215     if (insi == inse)
1216       // The insert list is a prefix of the extract list
1217       // We can simply remove the common indices from the extract and make it
1218       // operate on the inserted value instead of the insertvalue result.
1219       // i.e., replace
1220       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1221       // %E = extractvalue { i32, { i32 } } %I, 1, 0
1222       // with
1223       // %E extractvalue { i32 } { i32 42 }, 0
1224       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
1225                                       exti, exte);
1226   }
1227   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
1228     // We're extracting from an intrinsic, see if we're the only user, which
1229     // allows us to simplify multiple result intrinsics to simpler things that
1230     // just get one value.
1231     if (II->hasOneUse()) {
1232       // Check if we're grabbing the overflow bit or the result of a 'with
1233       // overflow' intrinsic.  If it's the latter we can remove the intrinsic
1234       // and replace it with a traditional binary instruction.
1235       switch (II->getIntrinsicID()) {
1236       case Intrinsic::uadd_with_overflow:
1237       case Intrinsic::sadd_with_overflow:
1238         if (*EV.idx_begin() == 0) {  // Normal result.
1239           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1240           II->replaceAllUsesWith(UndefValue::get(II->getType()));
1241           EraseInstFromFunction(*II);
1242           return BinaryOperator::CreateAdd(LHS, RHS);
1243         }
1244           
1245         // If the normal result of the add is dead, and the RHS is a constant,
1246         // we can transform this into a range comparison.
1247         // overflow = uadd a, -4  -->  overflow = icmp ugt a, 3
1248         if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
1249           if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
1250             return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
1251                                 ConstantExpr::getNot(CI));
1252         break;
1253       case Intrinsic::usub_with_overflow:
1254       case Intrinsic::ssub_with_overflow:
1255         if (*EV.idx_begin() == 0) {  // Normal result.
1256           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1257           II->replaceAllUsesWith(UndefValue::get(II->getType()));
1258           EraseInstFromFunction(*II);
1259           return BinaryOperator::CreateSub(LHS, RHS);
1260         }
1261         break;
1262       case Intrinsic::umul_with_overflow:
1263       case Intrinsic::smul_with_overflow:
1264         if (*EV.idx_begin() == 0) {  // Normal result.
1265           Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1266           II->replaceAllUsesWith(UndefValue::get(II->getType()));
1267           EraseInstFromFunction(*II);
1268           return BinaryOperator::CreateMul(LHS, RHS);
1269         }
1270         break;
1271       default:
1272         break;
1273       }
1274     }
1275   }
1276   if (LoadInst *L = dyn_cast<LoadInst>(Agg))
1277     // If the (non-volatile) load only has one use, we can rewrite this to a
1278     // load from a GEP. This reduces the size of the load.
1279     // FIXME: If a load is used only by extractvalue instructions then this
1280     //        could be done regardless of having multiple uses.
1281     if (!L->isVolatile() && L->hasOneUse()) {
1282       // extractvalue has integer indices, getelementptr has Value*s. Convert.
1283       SmallVector<Value*, 4> Indices;
1284       // Prefix an i32 0 since we need the first element.
1285       Indices.push_back(Builder->getInt32(0));
1286       for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
1287             I != E; ++I)
1288         Indices.push_back(Builder->getInt32(*I));
1289
1290       // We need to insert these at the location of the old load, not at that of
1291       // the extractvalue.
1292       Builder->SetInsertPoint(L->getParent(), L);
1293       Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(),
1294                                               Indices.begin(), Indices.end());
1295       // Returning the load directly will cause the main loop to insert it in
1296       // the wrong spot, so use ReplaceInstUsesWith().
1297       return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
1298     }
1299   // We could simplify extracts from other values. Note that nested extracts may
1300   // already be simplified implicitly by the above: extract (extract (insert) )
1301   // will be translated into extract ( insert ( extract ) ) first and then just
1302   // the value inserted, if appropriate. Similarly for extracts from single-use
1303   // loads: extract (extract (load)) will be translated to extract (load (gep))
1304   // and if again single-use then via load (gep (gep)) to load (gep).
1305   // However, double extracts from e.g. function arguments or return values
1306   // aren't handled yet.
1307   return 0;
1308 }
1309
1310
1311
1312
1313 /// TryToSinkInstruction - Try to move the specified instruction from its
1314 /// current block into the beginning of DestBlock, which can only happen if it's
1315 /// safe to move the instruction past all of the instructions between it and the
1316 /// end of its block.
1317 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
1318   assert(I->hasOneUse() && "Invariants didn't hold!");
1319
1320   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1321   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
1322     return false;
1323
1324   // Do not sink alloca instructions out of the entry block.
1325   if (isa<AllocaInst>(I) && I->getParent() ==
1326         &DestBlock->getParent()->getEntryBlock())
1327     return false;
1328
1329   // We can only sink load instructions if there is nothing between the load and
1330   // the end of block that could change the value.
1331   if (I->mayReadFromMemory()) {
1332     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
1333          Scan != E; ++Scan)
1334       if (Scan->mayWriteToMemory())
1335         return false;
1336   }
1337
1338   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
1339
1340   I->moveBefore(InsertPos);
1341   ++NumSunkInst;
1342   return true;
1343 }
1344
1345
1346 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
1347 /// all reachable code to the worklist.
1348 ///
1349 /// This has a couple of tricks to make the code faster and more powerful.  In
1350 /// particular, we constant fold and DCE instructions as we go, to avoid adding
1351 /// them to the worklist (this significantly speeds up instcombine on code where
1352 /// many instructions are dead or constant).  Additionally, if we find a branch
1353 /// whose condition is a known constant, we only visit the reachable successors.
1354 ///
1355 static bool AddReachableCodeToWorklist(BasicBlock *BB, 
1356                                        SmallPtrSet<BasicBlock*, 64> &Visited,
1357                                        InstCombiner &IC,
1358                                        const TargetData *TD) {
1359   bool MadeIRChange = false;
1360   SmallVector<BasicBlock*, 256> Worklist;
1361   Worklist.push_back(BB);
1362
1363   SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
1364   SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
1365   
1366   do {
1367     BB = Worklist.pop_back_val();
1368     
1369     // We have now visited this block!  If we've already been here, ignore it.
1370     if (!Visited.insert(BB)) continue;
1371
1372     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
1373       Instruction *Inst = BBI++;
1374       
1375       // DCE instruction if trivially dead.
1376       if (isInstructionTriviallyDead(Inst)) {
1377         ++NumDeadInst;
1378         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
1379         Inst->eraseFromParent();
1380         continue;
1381       }
1382       
1383       // ConstantProp instruction if trivially constant.
1384       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
1385         if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
1386           DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
1387                        << *Inst << '\n');
1388           Inst->replaceAllUsesWith(C);
1389           ++NumConstProp;
1390           Inst->eraseFromParent();
1391           continue;
1392         }
1393       
1394       if (TD) {
1395         // See if we can constant fold its operands.
1396         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
1397              i != e; ++i) {
1398           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
1399           if (CE == 0) continue;
1400           
1401           // If we already folded this constant, don't try again.
1402           if (!FoldedConstants.insert(CE))
1403             continue;
1404           
1405           Constant *NewC = ConstantFoldConstantExpression(CE, TD);
1406           if (NewC && NewC != CE) {
1407             *i = NewC;
1408             MadeIRChange = true;
1409           }
1410         }
1411       }
1412
1413       InstrsForInstCombineWorklist.push_back(Inst);
1414     }
1415
1416     // Recursively visit successors.  If this is a branch or switch on a
1417     // constant, only visit the reachable successor.
1418     TerminatorInst *TI = BB->getTerminator();
1419     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1420       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
1421         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
1422         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
1423         Worklist.push_back(ReachableBB);
1424         continue;
1425       }
1426     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1427       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
1428         // See if this is an explicit destination.
1429         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
1430           if (SI->getCaseValue(i) == Cond) {
1431             BasicBlock *ReachableBB = SI->getSuccessor(i);
1432             Worklist.push_back(ReachableBB);
1433             continue;
1434           }
1435         
1436         // Otherwise it is the default destination.
1437         Worklist.push_back(SI->getSuccessor(0));
1438         continue;
1439       }
1440     }
1441     
1442     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1443       Worklist.push_back(TI->getSuccessor(i));
1444   } while (!Worklist.empty());
1445   
1446   // Once we've found all of the instructions to add to instcombine's worklist,
1447   // add them in reverse order.  This way instcombine will visit from the top
1448   // of the function down.  This jives well with the way that it adds all uses
1449   // of instructions to the worklist after doing a transformation, thus avoiding
1450   // some N^2 behavior in pathological cases.
1451   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
1452                               InstrsForInstCombineWorklist.size());
1453   
1454   return MadeIRChange;
1455 }
1456
1457 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
1458   MadeIRChange = false;
1459   
1460   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
1461         << F.getNameStr() << "\n");
1462
1463   {
1464     // Do a depth-first traversal of the function, populate the worklist with
1465     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
1466     // track of which blocks we visit.
1467     SmallPtrSet<BasicBlock*, 64> Visited;
1468     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
1469
1470     // Do a quick scan over the function.  If we find any blocks that are
1471     // unreachable, remove any instructions inside of them.  This prevents
1472     // the instcombine code from having to deal with some bad special cases.
1473     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1474       if (!Visited.count(BB)) {
1475         Instruction *Term = BB->getTerminator();
1476         while (Term != BB->begin()) {   // Remove instrs bottom-up
1477           BasicBlock::iterator I = Term; --I;
1478
1479           DEBUG(errs() << "IC: DCE: " << *I << '\n');
1480           // A debug intrinsic shouldn't force another iteration if we weren't
1481           // going to do one without it.
1482           if (!isa<DbgInfoIntrinsic>(I)) {
1483             ++NumDeadInst;
1484             MadeIRChange = true;
1485           }
1486
1487           // If I is not void type then replaceAllUsesWith undef.
1488           // This allows ValueHandlers and custom metadata to adjust itself.
1489           if (!I->getType()->isVoidTy())
1490             I->replaceAllUsesWith(UndefValue::get(I->getType()));
1491           I->eraseFromParent();
1492         }
1493       }
1494   }
1495
1496   while (!Worklist.isEmpty()) {
1497     Instruction *I = Worklist.RemoveOne();
1498     if (I == 0) continue;  // skip null values.
1499
1500     // Check to see if we can DCE the instruction.
1501     if (isInstructionTriviallyDead(I)) {
1502       DEBUG(errs() << "IC: DCE: " << *I << '\n');
1503       EraseInstFromFunction(*I);
1504       ++NumDeadInst;
1505       MadeIRChange = true;
1506       continue;
1507     }
1508
1509     // Instruction isn't dead, see if we can constant propagate it.
1510     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
1511       if (Constant *C = ConstantFoldInstruction(I, TD)) {
1512         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
1513
1514         // Add operands to the worklist.
1515         ReplaceInstUsesWith(*I, C);
1516         ++NumConstProp;
1517         EraseInstFromFunction(*I);
1518         MadeIRChange = true;
1519         continue;
1520       }
1521
1522     // See if we can trivially sink this instruction to a successor basic block.
1523     if (I->hasOneUse()) {
1524       BasicBlock *BB = I->getParent();
1525       Instruction *UserInst = cast<Instruction>(I->use_back());
1526       BasicBlock *UserParent;
1527       
1528       // Get the block the use occurs in.
1529       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
1530         UserParent = PN->getIncomingBlock(I->use_begin().getUse());
1531       else
1532         UserParent = UserInst->getParent();
1533       
1534       if (UserParent != BB) {
1535         bool UserIsSuccessor = false;
1536         // See if the user is one of our successors.
1537         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1538           if (*SI == UserParent) {
1539             UserIsSuccessor = true;
1540             break;
1541           }
1542
1543         // If the user is one of our immediate successors, and if that successor
1544         // only has us as a predecessors (we'd have to split the critical edge
1545         // otherwise), we can keep going.
1546         if (UserIsSuccessor && UserParent->getSinglePredecessor())
1547           // Okay, the CFG is simple enough, try to sink this instruction.
1548           MadeIRChange |= TryToSinkInstruction(I, UserParent);
1549       }
1550     }
1551
1552     // Now that we have an instruction, try combining it to simplify it.
1553     Builder->SetInsertPoint(I->getParent(), I);
1554     
1555 #ifndef NDEBUG
1556     std::string OrigI;
1557 #endif
1558     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
1559     DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
1560
1561     if (Instruction *Result = visit(*I)) {
1562       ++NumCombined;
1563       // Should we replace the old instruction with a new one?
1564       if (Result != I) {
1565         DEBUG(errs() << "IC: Old = " << *I << '\n'
1566                      << "    New = " << *Result << '\n');
1567
1568         // Everything uses the new instruction now.
1569         I->replaceAllUsesWith(Result);
1570
1571         // Push the new instruction and any users onto the worklist.
1572         Worklist.Add(Result);
1573         Worklist.AddUsersToWorkList(*Result);
1574
1575         // Move the name to the new instruction first.
1576         Result->takeName(I);
1577
1578         // Insert the new instruction into the basic block...
1579         BasicBlock *InstParent = I->getParent();
1580         BasicBlock::iterator InsertPos = I;
1581
1582         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
1583           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
1584             ++InsertPos;
1585
1586         InstParent->getInstList().insert(InsertPos, Result);
1587
1588         EraseInstFromFunction(*I);
1589       } else {
1590 #ifndef NDEBUG
1591         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
1592                      << "    New = " << *I << '\n');
1593 #endif
1594
1595         // If the instruction was modified, it's possible that it is now dead.
1596         // if so, remove it.
1597         if (isInstructionTriviallyDead(I)) {
1598           EraseInstFromFunction(*I);
1599         } else {
1600           Worklist.Add(I);
1601           Worklist.AddUsersToWorkList(*I);
1602         }
1603       }
1604       MadeIRChange = true;
1605     }
1606   }
1607
1608   Worklist.Zap();
1609   return MadeIRChange;
1610 }
1611
1612
1613 bool InstCombiner::runOnFunction(Function &F) {
1614   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1615   TD = getAnalysisIfAvailable<TargetData>();
1616
1617   
1618   /// Builder - This is an IRBuilder that automatically inserts new
1619   /// instructions into the worklist when they are created.
1620   IRBuilder<true, TargetFolder, InstCombineIRInserter> 
1621     TheBuilder(F.getContext(), TargetFolder(TD),
1622                InstCombineIRInserter(Worklist));
1623   Builder = &TheBuilder;
1624   
1625   bool EverMadeChange = false;
1626
1627   // Iterate while there is work to do.
1628   unsigned Iteration = 0;
1629   while (DoOneIteration(F, Iteration++))
1630     EverMadeChange = true;
1631   
1632   Builder = 0;
1633   return EverMadeChange;
1634 }
1635
1636 FunctionPass *llvm::createInstructionCombiningPass() {
1637   return new InstCombiner();
1638 }