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