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