Generalize some of the add tests to allow for reassociation to take place
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 // InstructionCombining - Combine instructions to form fewer, simple
4 // instructions.  This pass does not modify the CFG This pass is where algebraic
5 // simplification happens.
6 //
7 // This pass combines things like:
8 //    %Y = add int 1, %X
9 //    %Z = add int 1, %Y
10 // into:
11 //    %Z = add int 2, %X
12 //
13 // This is a simple worklist driven algorithm.
14 //
15 // This pass guarantees that the following cannonicalizations are performed on
16 // the program:
17 //    1. If a binary operator has a constant operand, it is moved to the RHS
18 //    2. Bitwise operators with constant operands are always grouped so that
19 //       shifts are performed first, then or's, then and's, then xor's.
20 //    3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
21 //    4. All SetCC instructions on boolean values are replaced with logical ops
22 //    5. add X, X is represented as (X*2) => (X << 1)
23 //    6. Multiplies with a power-of-two constant argument are transformed into
24 //       shifts.
25 //    N. This list is incomplete
26 //
27 //===----------------------------------------------------------------------===//
28
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Constants.h"
35 #include "llvm/ConstantHandling.h"
36 #include "llvm/DerivedTypes.h"
37 #include "llvm/GlobalVariable.h"
38 #include "llvm/Support/InstIterator.h"
39 #include "llvm/Support/InstVisitor.h"
40 #include "llvm/Support/CallSite.h"
41 #include "Support/Statistic.h"
42 #include <algorithm>
43
44 namespace {
45   Statistic<> NumCombined ("instcombine", "Number of insts combined");
46   Statistic<> NumConstProp("instcombine", "Number of constant folds");
47   Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
48
49   class InstCombiner : public FunctionPass,
50                        public InstVisitor<InstCombiner, Instruction*> {
51     // Worklist of all of the instructions that need to be simplified.
52     std::vector<Instruction*> WorkList;
53
54     void AddUsesToWorkList(Instruction &I) {
55       // The instruction was simplified, add all users of the instruction to
56       // the work lists because they might get more simplified now...
57       //
58       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
59            UI != UE; ++UI)
60         WorkList.push_back(cast<Instruction>(*UI));
61     }
62
63     // removeFromWorkList - remove all instances of I from the worklist.
64     void removeFromWorkList(Instruction *I);
65   public:
66     virtual bool runOnFunction(Function &F);
67
68     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69       AU.setPreservesCFG();
70     }
71
72     // Visitation implementation - Implement instruction combining for different
73     // instruction types.  The semantics are as follows:
74     // Return Value:
75     //    null        - No change was made
76     //     I          - Change was made, I is still valid, I may be dead though
77     //   otherwise    - Change was made, replace I with returned instruction
78     //   
79     Instruction *visitAdd(BinaryOperator &I);
80     Instruction *visitSub(BinaryOperator &I);
81     Instruction *visitMul(BinaryOperator &I);
82     Instruction *visitDiv(BinaryOperator &I);
83     Instruction *visitRem(BinaryOperator &I);
84     Instruction *visitAnd(BinaryOperator &I);
85     Instruction *visitOr (BinaryOperator &I);
86     Instruction *visitXor(BinaryOperator &I);
87     Instruction *visitSetCondInst(BinaryOperator &I);
88     Instruction *visitShiftInst(ShiftInst &I);
89     Instruction *visitCastInst(CastInst &CI);
90     Instruction *visitCallInst(CallInst &CI);
91     Instruction *visitInvokeInst(InvokeInst &II);
92     Instruction *visitPHINode(PHINode &PN);
93     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
94     Instruction *visitAllocationInst(AllocationInst &AI);
95     Instruction *visitLoadInst(LoadInst &LI);
96     Instruction *visitBranchInst(BranchInst &BI);
97
98     // visitInstruction - Specify what to return for unhandled instructions...
99     Instruction *visitInstruction(Instruction &I) { return 0; }
100
101   private:
102     bool transformConstExprCastCall(CallSite CS);
103
104     // InsertNewInstBefore - insert an instruction New before instruction Old
105     // in the program.  Add the new instruction to the worklist.
106     //
107     void InsertNewInstBefore(Instruction *New, Instruction &Old) {
108       assert(New && New->getParent() == 0 &&
109              "New instruction already inserted into a basic block!");
110       BasicBlock *BB = Old.getParent();
111       BB->getInstList().insert(&Old, New);  // Insert inst
112       WorkList.push_back(New);              // Add to worklist
113     }
114
115     // ReplaceInstUsesWith - This method is to be used when an instruction is
116     // found to be dead, replacable with another preexisting expression.  Here
117     // we add all uses of I to the worklist, replace all uses of I with the new
118     // value, then return I, so that the inst combiner will know that I was
119     // modified.
120     //
121     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
122       AddUsesToWorkList(I);         // Add all modified instrs to worklist
123       I.replaceAllUsesWith(V);
124       return &I;
125     }
126
127     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
128     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
129     /// casts that are known to not do anything...
130     ///
131     Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
132                                    Instruction *InsertBefore);
133
134     // SimplifyCommutative - This performs a few simplifications for commutative
135     // operators...
136     bool SimplifyCommutative(BinaryOperator &I);
137   };
138
139   RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
140 }
141
142 // getComplexity:  Assign a complexity or rank value to LLVM Values...
143 //   0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
144 static unsigned getComplexity(Value *V) {
145   if (isa<Instruction>(V)) {
146     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
147       return 2;
148     return 3;
149   }
150   if (isa<Argument>(V)) return 2;
151   return isa<Constant>(V) ? 0 : 1;
152 }
153
154 // isOnlyUse - Return true if this instruction will be deleted if we stop using
155 // it.
156 static bool isOnlyUse(Value *V) {
157   return V->use_size() == 1 || isa<Constant>(V);
158 }
159
160 // SimplifyCommutative - This performs a few simplifications for commutative
161 // operators:
162 //
163 //  1. Order operands such that they are listed from right (least complex) to
164 //     left (most complex).  This puts constants before unary operators before
165 //     binary operators.
166 //
167 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
168 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
169 //
170 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
171   bool Changed = false;
172   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
173     Changed = !I.swapOperands();
174   
175   if (!I.isAssociative()) return Changed;
176   Instruction::BinaryOps Opcode = I.getOpcode();
177   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
178     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
179       if (isa<Constant>(I.getOperand(1))) {
180         Constant *Folded = ConstantExpr::get(I.getOpcode(),
181                                              cast<Constant>(I.getOperand(1)),
182                                              cast<Constant>(Op->getOperand(1)));
183         I.setOperand(0, Op->getOperand(0));
184         I.setOperand(1, Folded);
185         return true;
186       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
187         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
188             isOnlyUse(Op) && isOnlyUse(Op1)) {
189           Constant *C1 = cast<Constant>(Op->getOperand(1));
190           Constant *C2 = cast<Constant>(Op1->getOperand(1));
191
192           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
193           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
194           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
195                                                     Op1->getOperand(0),
196                                                     Op1->getName(), &I);
197           WorkList.push_back(New);
198           I.setOperand(0, New);
199           I.setOperand(1, Folded);
200           return true;
201         }      
202     }
203   return Changed;
204 }
205
206 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
207 // if the LHS is a constant zero (which is the 'negate' form).
208 //
209 static inline Value *dyn_castNegVal(Value *V) {
210   if (BinaryOperator::isNeg(V))
211     return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
212
213   // Constants can be considered to be negated values if they can be folded...
214   if (Constant *C = dyn_cast<Constant>(V))
215     return ConstantExpr::get(Instruction::Sub,
216                              Constant::getNullValue(V->getType()), C);
217   return 0;
218 }
219
220 static inline Value *dyn_castNotVal(Value *V) {
221   if (BinaryOperator::isNot(V))
222     return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
223
224   // Constants can be considered to be not'ed values...
225   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
226     return ConstantExpr::get(Instruction::Xor,
227                              ConstantIntegral::getAllOnesValue(C->getType()),C);
228   return 0;
229 }
230
231 // dyn_castFoldableMul - If this value is a multiply that can be folded into
232 // other computations (because it has a constant operand), return the
233 // non-constant operand of the multiply.
234 //
235 static inline Value *dyn_castFoldableMul(Value *V) {
236   if (V->use_size() == 1 && V->getType()->isInteger())
237     if (Instruction *I = dyn_cast<Instruction>(V))
238       if (I->getOpcode() == Instruction::Mul)
239         if (isa<Constant>(I->getOperand(1)))
240           return I->getOperand(0);
241   return 0;
242 }
243
244 // dyn_castMaskingAnd - If this value is an And instruction masking a value with
245 // a constant, return the constant being anded with.
246 //
247 template<class ValueType>
248 static inline Constant *dyn_castMaskingAnd(ValueType *V) {
249   if (Instruction *I = dyn_cast<Instruction>(V))
250     if (I->getOpcode() == Instruction::And)
251       return dyn_cast<Constant>(I->getOperand(1));
252
253   // If this is a constant, it acts just like we were masking with it.
254   return dyn_cast<Constant>(V);
255 }
256
257 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
258 // power of 2.
259 static unsigned Log2(uint64_t Val) {
260   assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
261   unsigned Count = 0;
262   while (Val != 1) {
263     if (Val & 1) return 0;    // Multiple bits set?
264     Val >>= 1;
265     ++Count;
266   }
267   return Count;
268 }
269
270
271 /// AssociativeOpt - Perform an optimization on an associative operator.  This
272 /// function is designed to check a chain of associative operators for a
273 /// potential to apply a certain optimization.  Since the optimization may be
274 /// applicable if the expression was reassociated, this checks the chain, then
275 /// reassociates the expression as necessary to expose the optimization
276 /// opportunity.  This makes use of a special Functor, which must define
277 /// 'shouldApply' and 'apply' methods.
278 ///
279 template<typename Functor>
280 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
281   unsigned Opcode = Root.getOpcode();
282   Value *LHS = Root.getOperand(0);
283
284   // Quick check, see if the immediate LHS matches...
285   if (F.shouldApply(LHS))
286     return F.apply(Root);
287
288   // Otherwise, if the LHS is not of the same opcode as the root, return.
289   Instruction *LHSI = dyn_cast<Instruction>(LHS);
290   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->use_size() == 1) {
291     // Should we apply this transform to the RHS?
292     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
293
294     // If not to the RHS, check to see if we should apply to the LHS...
295     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
296       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
297       ShouldApply = true;
298     }
299
300     // If the functor wants to apply the optimization to the RHS of LHSI,
301     // reassociate the expression from ((? op A) op B) to (? op (A op B))
302     if (ShouldApply) {
303       BasicBlock *BB = Root.getParent();
304       // All of the instructions have a single use and have no side-effects,
305       // because of this, we can pull them all into the current basic block.
306       if (LHSI->getParent() != BB) {
307         // Move all of the instructions from root to LHSI into the current
308         // block.
309         Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
310         Instruction *LastUse = &Root;
311         while (TmpLHSI->getParent() == BB) {
312           LastUse = TmpLHSI;
313           TmpLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
314         }
315         
316         // Loop over all of the instructions in other blocks, moving them into
317         // the current one.
318         Value *TmpLHS = TmpLHSI;
319         do {
320           TmpLHSI = cast<Instruction>(TmpLHS);
321           // Remove from current block...
322           TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
323           // Insert before the last instruction...
324           BB->getInstList().insert(LastUse, TmpLHSI);
325           TmpLHS = TmpLHSI->getOperand(0);
326         } while (TmpLHSI != LHSI);
327       }
328       
329       // Now all of the instructions are in the current basic block, go ahead
330       // and perform the reassociation.
331       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
332
333       // First move the selected RHS to the LHS of the root...
334       Root.setOperand(0, LHSI->getOperand(1));
335
336       // Make what used to be the LHS of the root be the user of the root...
337       Value *ExtraOperand = TmpLHSI->getOperand(1);
338       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
339       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
340       BB->getInstList().remove(&Root);           // Remove root from the BB
341       BB->getInstList().insert(TmpLHSI, &Root);  // Insert root before TmpLHSI
342
343       // Now propagate the ExtraOperand down the chain of instructions until we
344       // get to LHSI.
345       while (TmpLHSI != LHSI) {
346         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
347         Value *NextOp = NextLHSI->getOperand(1);
348         NextLHSI->setOperand(1, ExtraOperand);
349         TmpLHSI = NextLHSI;
350         ExtraOperand = NextOp;
351       }
352       
353       // Now that the instructions are reassociated, have the functor perform
354       // the transformation...
355       return F.apply(Root);
356     }
357     
358     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
359   }
360   return 0;
361 }
362
363
364 // AddRHS - Implements: X + X --> X << 1
365 struct AddRHS {
366   Value *RHS;
367   AddRHS(Value *rhs) : RHS(rhs) {}
368   bool shouldApply(Value *LHS) const { return LHS == RHS; }
369   Instruction *apply(BinaryOperator &Add) const {
370     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
371                          ConstantInt::get(Type::UByteTy, 1));
372   }
373 };
374
375 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
376 //                 iff C1&C2 == 0
377 struct AddMaskingAnd {
378   Constant *C2;
379   AddMaskingAnd(Constant *c) : C2(c) {}
380   bool shouldApply(Value *LHS) const {
381     if (Constant *C1 = dyn_castMaskingAnd(LHS))
382       return ConstantExpr::get(Instruction::And, C1, C2)->isNullValue();
383     return false;
384   }
385   Instruction *apply(BinaryOperator &Add) const {
386     return BinaryOperator::create(Instruction::Or, Add.getOperand(0),
387                                   Add.getOperand(1));
388   }
389 };
390
391
392
393 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
394   bool Changed = SimplifyCommutative(I);
395   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
396
397   // X + 0 --> X
398   if (RHS == Constant::getNullValue(I.getType()))
399     return ReplaceInstUsesWith(I, LHS);
400
401   // X + X --> X << 1
402   if (I.getType()->isInteger())
403     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
404
405   // -A + B  -->  B - A
406   if (Value *V = dyn_castNegVal(LHS))
407     return BinaryOperator::create(Instruction::Sub, RHS, V);
408
409   // A + -B  -->  A - B
410   if (!isa<Constant>(RHS))
411     if (Value *V = dyn_castNegVal(RHS))
412       return BinaryOperator::create(Instruction::Sub, LHS, V);
413
414   // X*C + X --> X * (C+1)
415   if (dyn_castFoldableMul(LHS) == RHS) {
416     Constant *CP1 =
417       ConstantExpr::get(Instruction::Add, 
418                         cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
419                         ConstantInt::get(I.getType(), 1));
420     return BinaryOperator::create(Instruction::Mul, RHS, CP1);
421   }
422
423   // X + X*C --> X * (C+1)
424   if (dyn_castFoldableMul(RHS) == LHS) {
425     Constant *CP1 =
426       ConstantExpr::get(Instruction::Add,
427                         cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
428                         ConstantInt::get(I.getType(), 1));
429     return BinaryOperator::create(Instruction::Mul, LHS, CP1);
430   }
431
432   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
433   if (Constant *C2 = dyn_castMaskingAnd(RHS))
434     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
435
436   return Changed ? &I : 0;
437 }
438
439 // isSignBit - Return true if the value represented by the constant only has the
440 // highest order bit set.
441 static bool isSignBit(ConstantInt *CI) {
442   unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
443   return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
444 }
445
446 static unsigned getTypeSizeInBits(const Type *Ty) {
447   return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
448 }
449
450 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
451   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
452
453   if (Op0 == Op1)         // sub X, X  -> 0
454     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
455
456   // If this is a 'B = x-(-A)', change to B = x+A...
457   if (Value *V = dyn_castNegVal(Op1))
458     return BinaryOperator::create(Instruction::Add, Op0, V);
459
460   // Replace (-1 - A) with (~A)...
461   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
462     if (C->isAllOnesValue())
463       return BinaryOperator::createNot(Op1);
464
465   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
466     if (Op1I->use_size() == 1) {
467       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
468       // is not used by anyone else...
469       //
470       if (Op1I->getOpcode() == Instruction::Sub) {
471         // Swap the two operands of the subexpr...
472         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
473         Op1I->setOperand(0, IIOp1);
474         Op1I->setOperand(1, IIOp0);
475         
476         // Create the new top level add instruction...
477         return BinaryOperator::create(Instruction::Add, Op0, Op1);
478       }
479
480       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
481       //
482       if (Op1I->getOpcode() == Instruction::And &&
483           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
484         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
485
486         Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
487         return BinaryOperator::create(Instruction::And, Op0, NewNot);
488       }
489
490       // X - X*C --> X * (1-C)
491       if (dyn_castFoldableMul(Op1I) == Op0) {
492         Constant *CP1 =
493           ConstantExpr::get(Instruction::Sub,
494                             ConstantInt::get(I.getType(), 1),
495                          cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
496         assert(CP1 && "Couldn't constant fold 1-C?");
497         return BinaryOperator::create(Instruction::Mul, Op0, CP1);
498       }
499     }
500
501   // X*C - X --> X * (C-1)
502   if (dyn_castFoldableMul(Op0) == Op1) {
503     Constant *CP1 =
504       ConstantExpr::get(Instruction::Sub,
505                         cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
506                         ConstantInt::get(I.getType(), 1));
507     assert(CP1 && "Couldn't constant fold C - 1?");
508     return BinaryOperator::create(Instruction::Mul, Op1, CP1);
509   }
510
511   return 0;
512 }
513
514 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
515   bool Changed = SimplifyCommutative(I);
516   Value *Op0 = I.getOperand(0);
517
518   // Simplify mul instructions with a constant RHS...
519   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
520     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
521
522       // ((X << C1)*C2) == (X * (C2 << C1))
523       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
524         if (SI->getOpcode() == Instruction::Shl)
525           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
526             return BinaryOperator::create(Instruction::Mul, SI->getOperand(0),
527                                           *CI << *ShOp);
528
529       const Type *Ty = CI->getType();
530       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
531       switch (Val) {
532       case -1:                               // X * -1 -> -X
533         return BinaryOperator::createNeg(Op0, I.getName());
534       case 0:
535         return ReplaceInstUsesWith(I, Op1);  // Eliminate 'mul double %X, 0'
536       case 1:
537         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul int %X, 1'
538       }
539
540       if (uint64_t C = Log2(Val))            // Replace X*(2^C) with X << C
541         return new ShiftInst(Instruction::Shl, Op0,
542                              ConstantUInt::get(Type::UByteTy, C));
543     } else {
544       ConstantFP *Op1F = cast<ConstantFP>(Op1);
545       if (Op1F->isNullValue())
546         return ReplaceInstUsesWith(I, Op1);
547
548       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
549       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
550       if (Op1F->getValue() == 1.0)
551         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
552     }
553   }
554
555   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
556     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
557       return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
558
559   return Changed ? &I : 0;
560 }
561
562 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
563   // div X, 1 == X
564   if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
565     if (RHS->equalsInt(1))
566       return ReplaceInstUsesWith(I, I.getOperand(0));
567
568     // Check to see if this is an unsigned division with an exact power of 2,
569     // if so, convert to a right shift.
570     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
571       if (uint64_t Val = C->getValue())    // Don't break X / 0
572         if (uint64_t C = Log2(Val))
573           return new ShiftInst(Instruction::Shr, I.getOperand(0),
574                                ConstantUInt::get(Type::UByteTy, C));
575   }
576
577   // 0 / X == 0, we don't need to preserve faults!
578   if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
579     if (LHS->equalsInt(0))
580       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
581
582   return 0;
583 }
584
585
586 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
587   if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
588     if (RHS->equalsInt(1))  // X % 1 == 0
589       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
590
591     // Check to see if this is an unsigned remainder with an exact power of 2,
592     // if so, convert to a bitwise and.
593     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
594       if (uint64_t Val = C->getValue())    // Don't break X % 0 (divide by zero)
595         if (Log2(Val))
596           return BinaryOperator::create(Instruction::And, I.getOperand(0),
597                                         ConstantUInt::get(I.getType(), Val-1));
598   }
599
600   // 0 % X == 0, we don't need to preserve faults!
601   if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
602     if (LHS->equalsInt(0))
603       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
604
605   return 0;
606 }
607
608 // isMaxValueMinusOne - return true if this is Max-1
609 static bool isMaxValueMinusOne(const ConstantInt *C) {
610   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
611     // Calculate -1 casted to the right type...
612     unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
613     uint64_t Val = ~0ULL;                // All ones
614     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
615     return CU->getValue() == Val-1;
616   }
617
618   const ConstantSInt *CS = cast<ConstantSInt>(C);
619   
620   // Calculate 0111111111..11111
621   unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
622   int64_t Val = INT64_MAX;             // All ones
623   Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
624   return CS->getValue() == Val-1;
625 }
626
627 // isMinValuePlusOne - return true if this is Min+1
628 static bool isMinValuePlusOne(const ConstantInt *C) {
629   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
630     return CU->getValue() == 1;
631
632   const ConstantSInt *CS = cast<ConstantSInt>(C);
633   
634   // Calculate 1111111111000000000000 
635   unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
636   int64_t Val = -1;                    // All ones
637   Val <<= TypeBits-1;                  // Shift over to the right spot
638   return CS->getValue() == Val+1;
639 }
640
641
642 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
643   bool Changed = SimplifyCommutative(I);
644   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
645
646   // and X, X = X   and X, 0 == 0
647   if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
648     return ReplaceInstUsesWith(I, Op1);
649
650   // and X, -1 == X
651   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
652     if (RHS->isAllOnesValue())
653       return ReplaceInstUsesWith(I, Op0);
654
655     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
656       Value *X = Op0I->getOperand(0);
657       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
658         if (Op0I->getOpcode() == Instruction::Xor) {
659           if ((*RHS & *Op0CI)->isNullValue()) {
660             // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
661             return BinaryOperator::create(Instruction::And, X, RHS);
662           } else if (isOnlyUse(Op0)) {
663             // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
664             std::string Op0Name = Op0I->getName(); Op0I->setName("");
665             Instruction *And = BinaryOperator::create(Instruction::And,
666                                                       X, RHS, Op0Name);
667             InsertNewInstBefore(And, I);
668             return BinaryOperator::create(Instruction::Xor, And, *RHS & *Op0CI);
669           }
670         } else if (Op0I->getOpcode() == Instruction::Or) {
671           // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
672           if ((*RHS & *Op0CI)->isNullValue())
673             return BinaryOperator::create(Instruction::And, X, RHS);
674
675           Constant *Together = *RHS & *Op0CI;
676           if (Together == RHS) // (X | C) & C --> C
677             return ReplaceInstUsesWith(I, RHS);
678
679           if (isOnlyUse(Op0)) {
680             if (Together != Op0CI) {
681               // (X | C1) & C2 --> (X | (C1&C2)) & C2
682               std::string Op0Name = Op0I->getName(); Op0I->setName("");
683               Instruction *Or = BinaryOperator::create(Instruction::Or, X,
684                                                        Together, Op0Name);
685               InsertNewInstBefore(Or, I);
686               return BinaryOperator::create(Instruction::And, Or, RHS);
687             }
688           }
689         }
690     }
691   }
692
693   Value *Op0NotVal = dyn_castNotVal(Op0);
694   Value *Op1NotVal = dyn_castNotVal(Op1);
695
696   // (~A & ~B) == (~(A | B)) - Demorgan's Law
697   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
698     Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
699                                              Op1NotVal,I.getName()+".demorgan");
700     InsertNewInstBefore(Or, I);
701     return BinaryOperator::createNot(Or);
702   }
703
704   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
705     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
706
707   return Changed ? &I : 0;
708 }
709
710
711
712 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
713   bool Changed = SimplifyCommutative(I);
714   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
715
716   // or X, X = X   or X, 0 == X
717   if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
718     return ReplaceInstUsesWith(I, Op0);
719
720   // or X, -1 == -1
721   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
722     if (RHS->isAllOnesValue())
723       return ReplaceInstUsesWith(I, Op1);
724
725     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
726       // (X & C1) | C2 --> (X | C2) & (C1|C2)
727       if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
728         if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
729           std::string Op0Name = Op0I->getName(); Op0I->setName("");
730           Instruction *Or = BinaryOperator::create(Instruction::Or,
731                                                    Op0I->getOperand(0), RHS,
732                                                    Op0Name);
733           InsertNewInstBefore(Or, I);
734           return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
735         }
736
737       // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
738       if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
739         if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
740           std::string Op0Name = Op0I->getName(); Op0I->setName("");
741           Instruction *Or = BinaryOperator::create(Instruction::Or,
742                                                    Op0I->getOperand(0), RHS,
743                                                    Op0Name);
744           InsertNewInstBefore(Or, I);
745           return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
746         }
747     }
748   }
749
750   // (A & C1)|(A & C2) == A & (C1|C2)
751   if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
752     if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
753       if (LHS->getOperand(0) == RHS->getOperand(0))
754         if (Constant *C0 = dyn_castMaskingAnd(LHS))
755           if (Constant *C1 = dyn_castMaskingAnd(RHS))
756             return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
757                                           *C0 | *C1);            
758
759   Value *Op0NotVal = dyn_castNotVal(Op0);
760   Value *Op1NotVal = dyn_castNotVal(Op1);
761
762   if (Op1 == Op0NotVal)   // ~A | A == -1
763     return ReplaceInstUsesWith(I, 
764                                ConstantIntegral::getAllOnesValue(I.getType()));
765
766   if (Op0 == Op1NotVal)   // A | ~A == -1
767     return ReplaceInstUsesWith(I, 
768                                ConstantIntegral::getAllOnesValue(I.getType()));
769
770   // (~A | ~B) == (~(A & B)) - Demorgan's Law
771   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
772     Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
773                                               Op1NotVal,I.getName()+".demorgan",
774                                               &I);
775     WorkList.push_back(And);
776     return BinaryOperator::createNot(And);
777   }
778
779   return Changed ? &I : 0;
780 }
781
782
783
784 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
785   bool Changed = SimplifyCommutative(I);
786   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
787
788   // xor X, X = 0
789   if (Op0 == Op1)
790     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
791
792   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
793     // xor X, 0 == X
794     if (RHS->isNullValue())
795       return ReplaceInstUsesWith(I, Op0);
796
797     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
798       // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
799       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
800         if (RHS == ConstantBool::True && SCI->use_size() == 1)
801           return new SetCondInst(SCI->getInverseCondition(),
802                                  SCI->getOperand(0), SCI->getOperand(1));
803           
804       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
805         if (Op0I->getOpcode() == Instruction::And) {
806           // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
807           if ((*RHS & *Op0CI)->isNullValue())
808             return BinaryOperator::create(Instruction::Or, Op0, RHS);
809         } else if (Op0I->getOpcode() == Instruction::Or) {
810           // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
811           if ((*RHS & *Op0CI) == RHS)
812             return BinaryOperator::create(Instruction::And, Op0, ~*RHS);
813         }
814     }
815   }
816
817   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
818     if (X == Op1)
819       return ReplaceInstUsesWith(I,
820                                 ConstantIntegral::getAllOnesValue(I.getType()));
821
822   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
823     if (X == Op0)
824       return ReplaceInstUsesWith(I,
825                                 ConstantIntegral::getAllOnesValue(I.getType()));
826
827   if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
828     if (Op1I->getOpcode() == Instruction::Or)
829       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
830         cast<BinaryOperator>(Op1I)->swapOperands();
831         I.swapOperands();
832         std::swap(Op0, Op1);
833       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
834         I.swapOperands();
835         std::swap(Op0, Op1);
836       }
837
838   if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
839     if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
840       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
841         cast<BinaryOperator>(Op0I)->swapOperands();
842       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
843         Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
844         WorkList.push_back(cast<Instruction>(NotB));
845         return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
846                                       NotB);
847       }
848     }
849
850   // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
851   if (Constant *C1 = dyn_castMaskingAnd(Op0))
852     if (Constant *C2 = dyn_castMaskingAnd(Op1))
853       if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
854         return BinaryOperator::create(Instruction::Or, Op0, Op1);
855
856   return Changed ? &I : 0;
857 }
858
859 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
860 static Constant *AddOne(ConstantInt *C) {
861   Constant *Result = ConstantExpr::get(Instruction::Add, C,
862                                        ConstantInt::get(C->getType(), 1));
863   assert(Result && "Constant folding integer addition failed!");
864   return Result;
865 }
866 static Constant *SubOne(ConstantInt *C) {
867   Constant *Result = ConstantExpr::get(Instruction::Sub, C,
868                                        ConstantInt::get(C->getType(), 1));
869   assert(Result && "Constant folding integer addition failed!");
870   return Result;
871 }
872
873 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
874 // true when both operands are equal...
875 //
876 static bool isTrueWhenEqual(Instruction &I) {
877   return I.getOpcode() == Instruction::SetEQ ||
878          I.getOpcode() == Instruction::SetGE ||
879          I.getOpcode() == Instruction::SetLE;
880 }
881
882 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
883   bool Changed = SimplifyCommutative(I);
884   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
885   const Type *Ty = Op0->getType();
886
887   // setcc X, X
888   if (Op0 == Op1)
889     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
890
891   // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
892   if (isa<ConstantPointerNull>(Op1) && 
893       (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
894     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
895
896
897   // setcc's with boolean values can always be turned into bitwise operations
898   if (Ty == Type::BoolTy) {
899     // If this is <, >, or !=, we can change this into a simple xor instruction
900     if (!isTrueWhenEqual(I))
901       return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
902
903     // Otherwise we need to make a temporary intermediate instruction and insert
904     // it into the instruction stream.  This is what we are after:
905     //
906     //  seteq bool %A, %B -> ~(A^B)
907     //  setle bool %A, %B -> ~A | B
908     //  setge bool %A, %B -> A | ~B
909     //
910     if (I.getOpcode() == Instruction::SetEQ) {  // seteq case
911       Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
912                                                 I.getName()+"tmp");
913       InsertNewInstBefore(Xor, I);
914       return BinaryOperator::createNot(Xor, I.getName());
915     }
916
917     // Handle the setXe cases...
918     assert(I.getOpcode() == Instruction::SetGE ||
919            I.getOpcode() == Instruction::SetLE);
920
921     if (I.getOpcode() == Instruction::SetGE)
922       std::swap(Op0, Op1);                   // Change setge -> setle
923
924     // Now we just have the SetLE case.
925     Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
926     InsertNewInstBefore(Not, I);
927     return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
928   }
929
930   // Check to see if we are doing one of many comparisons against constant
931   // integers at the end of their ranges...
932   //
933   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
934     // Simplify seteq and setne instructions...
935     if (I.getOpcode() == Instruction::SetEQ ||
936         I.getOpcode() == Instruction::SetNE) {
937       bool isSetNE = I.getOpcode() == Instruction::SetNE;
938
939       // If the first operand is (and|or|xor) with a constant, and the second
940       // operand is a constant, simplify a bit.
941       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
942         switch (BO->getOpcode()) {
943         case Instruction::Add:
944           if (CI->isNullValue()) {
945             // Replace ((add A, B) != 0) with (A != -B) if A or B is
946             // efficiently invertible, or if the add has just this one use.
947             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
948             if (Value *NegVal = dyn_castNegVal(BOp1))
949               return new SetCondInst(I.getOpcode(), BOp0, NegVal);
950             else if (Value *NegVal = dyn_castNegVal(BOp0))
951               return new SetCondInst(I.getOpcode(), NegVal, BOp1);
952             else if (BO->use_size() == 1) {
953               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
954               BO->setName("");
955               InsertNewInstBefore(Neg, I);
956               return new SetCondInst(I.getOpcode(), BOp0, Neg);
957             }
958           }
959           break;
960         case Instruction::Xor:
961           // For the xor case, we can xor two constants together, eliminating
962           // the explicit xor.
963           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
964             return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
965                                           *CI ^ *BOC);
966
967           // FALLTHROUGH
968         case Instruction::Sub:
969           // Replace (([sub|xor] A, B) != 0) with (A != B)
970           if (CI->isNullValue())
971             return new SetCondInst(I.getOpcode(), BO->getOperand(0),
972                                    BO->getOperand(1));
973           break;
974
975         case Instruction::Or:
976           // If bits are being or'd in that are not present in the constant we
977           // are comparing against, then the comparison could never succeed!
978           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
979             if (!(*BOC & *~*CI)->isNullValue())
980               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
981           break;
982
983         case Instruction::And:
984           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
985             // If bits are being compared against that are and'd out, then the
986             // comparison can never succeed!
987             if (!(*CI & *~*BOC)->isNullValue())
988               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
989
990             // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
991             // to be a signed value as appropriate.
992             if (isSignBit(BOC)) {
993               Value *X = BO->getOperand(0);
994               // If 'X' is not signed, insert a cast now...
995               if (!BOC->getType()->isSigned()) {
996                 const Type *DestTy;
997                 switch (BOC->getType()->getPrimitiveID()) {
998                 case Type::UByteTyID:  DestTy = Type::SByteTy; break;
999                 case Type::UShortTyID: DestTy = Type::ShortTy; break;
1000                 case Type::UIntTyID:   DestTy = Type::IntTy;   break;
1001                 case Type::ULongTyID:  DestTy = Type::LongTy;  break;
1002                 default: assert(0 && "Invalid unsigned integer type!"); abort();
1003                 }
1004                 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1005                 InsertNewInstBefore(NewCI, I);
1006                 X = NewCI;
1007               }
1008               return new SetCondInst(isSetNE ? Instruction::SetLT :
1009                                          Instruction::SetGE, X,
1010                                      Constant::getNullValue(X->getType()));
1011             }
1012           }
1013         default: break;
1014         }
1015       }
1016     }
1017
1018     // Check to see if we are comparing against the minimum or maximum value...
1019     if (CI->isMinValue()) {
1020       if (I.getOpcode() == Instruction::SetLT)       // A < MIN -> FALSE
1021         return ReplaceInstUsesWith(I, ConstantBool::False);
1022       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN -> TRUE
1023         return ReplaceInstUsesWith(I, ConstantBool::True);
1024       if (I.getOpcode() == Instruction::SetLE)       // A <= MIN -> A == MIN
1025         return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1026       if (I.getOpcode() == Instruction::SetGT)       // A > MIN -> A != MIN
1027         return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1028
1029     } else if (CI->isMaxValue()) {
1030       if (I.getOpcode() == Instruction::SetGT)       // A > MAX -> FALSE
1031         return ReplaceInstUsesWith(I, ConstantBool::False);
1032       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX -> TRUE
1033         return ReplaceInstUsesWith(I, ConstantBool::True);
1034       if (I.getOpcode() == Instruction::SetGE)       // A >= MAX -> A == MAX
1035         return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1036       if (I.getOpcode() == Instruction::SetLT)       // A < MAX -> A != MAX
1037         return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1038
1039       // Comparing against a value really close to min or max?
1040     } else if (isMinValuePlusOne(CI)) {
1041       if (I.getOpcode() == Instruction::SetLT)       // A < MIN+1 -> A == MIN
1042         return BinaryOperator::create(Instruction::SetEQ, Op0,
1043                                       SubOne(CI), I.getName());
1044       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN-1 -> A != MIN
1045         return BinaryOperator::create(Instruction::SetNE, Op0,
1046                                       SubOne(CI), I.getName());
1047
1048     } else if (isMaxValueMinusOne(CI)) {
1049       if (I.getOpcode() == Instruction::SetGT)       // A > MAX-1 -> A == MAX
1050         return BinaryOperator::create(Instruction::SetEQ, Op0,
1051                                       AddOne(CI), I.getName());
1052       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX-1 -> A != MAX
1053         return BinaryOperator::create(Instruction::SetNE, Op0,
1054                                       AddOne(CI), I.getName());
1055     }
1056   }
1057
1058   return Changed ? &I : 0;
1059 }
1060
1061
1062
1063 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
1064   assert(I.getOperand(1)->getType() == Type::UByteTy);
1065   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1066   bool isLeftShift = I.getOpcode() == Instruction::Shl;
1067
1068   // shl X, 0 == X and shr X, 0 == X
1069   // shl 0, X == 0 and shr 0, X == 0
1070   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
1071       Op0 == Constant::getNullValue(Op0->getType()))
1072     return ReplaceInstUsesWith(I, Op0);
1073
1074   // shr int -1, X = -1   (for any arithmetic shift rights of ~0)
1075   if (!isLeftShift)
1076     if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1077       if (CSI->isAllOnesValue())
1078         return ReplaceInstUsesWith(I, CSI);
1079
1080   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
1081     // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1082     // of a signed value.
1083     //
1084     unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
1085     if (CUI->getValue() >= TypeBits &&
1086         (!Op0->getType()->isSigned() || isLeftShift))
1087       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1088
1089     // ((X*C1) << C2) == (X * (C1 << C2))
1090     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1091       if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1092         if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
1093           return BinaryOperator::create(Instruction::Mul, BO->getOperand(0),
1094                                         *BOOp << *CUI);
1095     
1096
1097     // If the operand is an bitwise operator with a constant RHS, and the
1098     // shift is the only use, we can pull it out of the shift.
1099     if (Op0->use_size() == 1)
1100       if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1101         if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1102           bool isValid = true;     // Valid only for And, Or, Xor
1103           bool highBitSet = false; // Transform if high bit of constant set?
1104
1105           switch (Op0BO->getOpcode()) {
1106           default: isValid = false; break;   // Do not perform transform!
1107           case Instruction::Or:
1108           case Instruction::Xor:
1109             highBitSet = false;
1110             break;
1111           case Instruction::And:
1112             highBitSet = true;
1113             break;
1114           }
1115
1116           // If this is a signed shift right, and the high bit is modified
1117           // by the logical operation, do not perform the transformation.
1118           // The highBitSet boolean indicates the value of the high bit of
1119           // the constant which would cause it to be modified for this
1120           // operation.
1121           //
1122           if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1123             uint64_t Val = Op0C->getRawValue();
1124             isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1125           }
1126
1127           if (isValid) {
1128             Constant *NewRHS =
1129               ConstantFoldShiftInstruction(I.getOpcode(), Op0C, CUI);
1130
1131             Instruction *NewShift =
1132               new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1133                             Op0BO->getName());
1134             Op0BO->setName("");
1135             InsertNewInstBefore(NewShift, I);
1136
1137             return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1138                                           NewRHS);
1139           }
1140         }
1141
1142     // If this is a shift of a shift, see if we can fold the two together...
1143     if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
1144       if (ConstantUInt *ShiftAmt1C =
1145                                  dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
1146         unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1147         unsigned ShiftAmt2 = CUI->getValue();
1148         
1149         // Check for (A << c1) << c2   and   (A >> c1) >> c2
1150         if (I.getOpcode() == Op0SI->getOpcode()) {
1151           unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift...
1152           return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1153                                ConstantUInt::get(Type::UByteTy, Amt));
1154         }
1155         
1156         // Check for (A << c1) >> c2 or visaversa.  If we are dealing with
1157         // signed types, we can only support the (A >> c1) << c2 configuration,
1158         // because it can not turn an arbitrary bit of A into a sign bit.
1159         if (I.getType()->isUnsigned() || isLeftShift) {
1160           // Calculate bitmask for what gets shifted off the edge...
1161           Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
1162           if (isLeftShift)
1163             C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
1164           else
1165             C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
1166           
1167           Instruction *Mask =
1168             BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
1169                                    C, Op0SI->getOperand(0)->getName()+".mask");
1170           InsertNewInstBefore(Mask, I);
1171           
1172           // Figure out what flavor of shift we should use...
1173           if (ShiftAmt1 == ShiftAmt2)
1174             return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
1175           else if (ShiftAmt1 < ShiftAmt2) {
1176             return new ShiftInst(I.getOpcode(), Mask,
1177                          ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1178           } else {
1179             return new ShiftInst(Op0SI->getOpcode(), Mask,
1180                          ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1181           }
1182         }
1183       }
1184   }
1185
1186   return 0;
1187 }
1188
1189
1190 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1191 // instruction.
1192 //
1193 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1194                                           const Type *DstTy) {
1195
1196   // It is legal to eliminate the instruction if casting A->B->A if the sizes
1197   // are identical and the bits don't get reinterpreted (for example 
1198   // int->float->int would not be allowed)
1199   if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
1200     return true;
1201
1202   // Allow free casting and conversion of sizes as long as the sign doesn't
1203   // change...
1204   if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
1205     unsigned SrcSize = SrcTy->getPrimitiveSize();
1206     unsigned MidSize = MidTy->getPrimitiveSize();
1207     unsigned DstSize = DstTy->getPrimitiveSize();
1208
1209     // Cases where we are monotonically decreasing the size of the type are
1210     // always ok, regardless of what sign changes are going on.
1211     //
1212     if (SrcSize >= MidSize && MidSize >= DstSize)
1213       return true;
1214
1215     // Cases where the source and destination type are the same, but the middle
1216     // type is bigger are noops.
1217     //
1218     if (SrcSize == DstSize && MidSize > SrcSize)
1219       return true;
1220
1221     // If we are monotonically growing, things are more complex.
1222     //
1223     if (SrcSize <= MidSize && MidSize <= DstSize) {
1224       // We have eight combinations of signedness to worry about. Here's the
1225       // table:
1226       static const int SignTable[8] = {
1227         // CODE, SrcSigned, MidSigned, DstSigned, Comment
1228         1,     //   U          U          U       Always ok
1229         1,     //   U          U          S       Always ok
1230         3,     //   U          S          U       Ok iff SrcSize != MidSize
1231         3,     //   U          S          S       Ok iff SrcSize != MidSize
1232         0,     //   S          U          U       Never ok
1233         2,     //   S          U          S       Ok iff MidSize == DstSize
1234         1,     //   S          S          U       Always ok
1235         1,     //   S          S          S       Always ok
1236       };
1237
1238       // Choose an action based on the current entry of the signtable that this
1239       // cast of cast refers to...
1240       unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1241       switch (SignTable[Row]) {
1242       case 0: return false;              // Never ok
1243       case 1: return true;               // Always ok
1244       case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1245       case 3:                            // Ok iff SrcSize != MidSize
1246         return SrcSize != MidSize || SrcTy == Type::BoolTy;
1247       default: assert(0 && "Bad entry in sign table!");
1248       }
1249     }
1250   }
1251
1252   // Otherwise, we cannot succeed.  Specifically we do not want to allow things
1253   // like:  short -> ushort -> uint, because this can create wrong results if
1254   // the input short is negative!
1255   //
1256   return false;
1257 }
1258
1259 static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1260   if (V->getType() == Ty || isa<Constant>(V)) return false;
1261   if (const CastInst *CI = dyn_cast<CastInst>(V))
1262     if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1263       return false;
1264   return true;
1265 }
1266
1267 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1268 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
1269 /// casts that are known to not do anything...
1270 ///
1271 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1272                                              Instruction *InsertBefore) {
1273   if (V->getType() == DestTy) return V;
1274   if (Constant *C = dyn_cast<Constant>(V))
1275     return ConstantExpr::getCast(C, DestTy);
1276
1277   CastInst *CI = new CastInst(V, DestTy, V->getName());
1278   InsertNewInstBefore(CI, *InsertBefore);
1279   return CI;
1280 }
1281
1282 // CastInst simplification
1283 //
1284 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
1285   Value *Src = CI.getOperand(0);
1286
1287   // If the user is casting a value to the same type, eliminate this cast
1288   // instruction...
1289   if (CI.getType() == Src->getType())
1290     return ReplaceInstUsesWith(CI, Src);
1291
1292   // If casting the result of another cast instruction, try to eliminate this
1293   // one!
1294   //
1295   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
1296     if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1297                                CSrc->getType(), CI.getType())) {
1298       // This instruction now refers directly to the cast's src operand.  This
1299       // has a good chance of making CSrc dead.
1300       CI.setOperand(0, CSrc->getOperand(0));
1301       return &CI;
1302     }
1303
1304     // If this is an A->B->A cast, and we are dealing with integral types, try
1305     // to convert this into a logical 'and' instruction.
1306     //
1307     if (CSrc->getOperand(0)->getType() == CI.getType() &&
1308         CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
1309         CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1310         CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1311       assert(CSrc->getType() != Type::ULongTy &&
1312              "Cannot have type bigger than ulong!");
1313       uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
1314       Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1315       return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1316                                     AndOp);
1317     }
1318   }
1319
1320   // If casting the result of a getelementptr instruction with no offset, turn
1321   // this into a cast of the original pointer!
1322   //
1323   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1324     bool AllZeroOperands = true;
1325     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1326       if (!isa<Constant>(GEP->getOperand(i)) ||
1327           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1328         AllZeroOperands = false;
1329         break;
1330       }
1331     if (AllZeroOperands) {
1332       CI.setOperand(0, GEP->getOperand(0));
1333       return &CI;
1334     }
1335   }
1336
1337   // If the source value is an instruction with only this use, we can attempt to
1338   // propagate the cast into the instruction.  Also, only handle integral types
1339   // for now.
1340   if (Instruction *SrcI = dyn_cast<Instruction>(Src))
1341     if (SrcI->use_size() == 1 && Src->getType()->isIntegral() &&
1342         CI.getType()->isInteger()) {  // Don't mess with casts to bool here
1343       const Type *DestTy = CI.getType();
1344       unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1345       unsigned DestBitSize = getTypeSizeInBits(DestTy);
1346
1347       Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1348       Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1349
1350       switch (SrcI->getOpcode()) {
1351       case Instruction::Add:
1352       case Instruction::Mul:
1353       case Instruction::And:
1354       case Instruction::Or:
1355       case Instruction::Xor:
1356         // If we are discarding information, or just changing the sign, rewrite.
1357         if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1358           // Don't insert two casts if they cannot be eliminated.  We allow two
1359           // casts to be inserted if the sizes are the same.  This could only be
1360           // converting signedness, which is a noop.
1361           if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1362               !ValueRequiresCast(Op0, DestTy)) {
1363             Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1364             Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1365             return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1366                              ->getOpcode(), Op0c, Op1c);
1367           }
1368         }
1369         break;
1370       case Instruction::Shl:
1371         // Allow changing the sign of the source operand.  Do not allow changing
1372         // the size of the shift, UNLESS the shift amount is a constant.  We
1373         // mush not change variable sized shifts to a smaller size, because it
1374         // is undefined to shift more bits out than exist in the value.
1375         if (DestBitSize == SrcBitSize ||
1376             (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1377           Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1378           return new ShiftInst(Instruction::Shl, Op0c, Op1);
1379         }
1380         break;
1381       }
1382     }
1383   
1384   return 0;
1385 }
1386
1387 // CallInst simplification
1388 //
1389 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1390   if (transformConstExprCastCall(&CI)) return 0;
1391   return 0;
1392 }
1393
1394 // InvokeInst simplification
1395 //
1396 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1397   if (transformConstExprCastCall(&II)) return 0;
1398   return 0;
1399 }
1400
1401 // getPromotedType - Return the specified type promoted as it would be to pass
1402 // though a va_arg area...
1403 static const Type *getPromotedType(const Type *Ty) {
1404   switch (Ty->getPrimitiveID()) {
1405   case Type::SByteTyID:
1406   case Type::ShortTyID:  return Type::IntTy;
1407   case Type::UByteTyID:
1408   case Type::UShortTyID: return Type::UIntTy;
1409   case Type::FloatTyID:  return Type::DoubleTy;
1410   default:               return Ty;
1411   }
1412 }
1413
1414 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
1415 // attempt to move the cast to the arguments of the call/invoke.
1416 //
1417 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1418   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1419   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1420   if (CE->getOpcode() != Instruction::Cast ||
1421       !isa<ConstantPointerRef>(CE->getOperand(0)))
1422     return false;
1423   ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1424   if (!isa<Function>(CPR->getValue())) return false;
1425   Function *Callee = cast<Function>(CPR->getValue());
1426   Instruction *Caller = CS.getInstruction();
1427
1428   // Okay, this is a cast from a function to a different type.  Unless doing so
1429   // would cause a type conversion of one of our arguments, change this call to
1430   // be a direct call with arguments casted to the appropriate types.
1431   //
1432   const FunctionType *FT = Callee->getFunctionType();
1433   const Type *OldRetTy = Caller->getType();
1434
1435   if (Callee->isExternal() &&
1436       !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1437     return false;   // Cannot transform this return value...
1438
1439   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1440   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1441                                     
1442   CallSite::arg_iterator AI = CS.arg_begin();
1443   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1444     const Type *ParamTy = FT->getParamType(i);
1445     bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1446     if (Callee->isExternal() && !isConvertible) return false;    
1447   }
1448
1449   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1450       Callee->isExternal())
1451     return false;   // Do not delete arguments unless we have a function body...
1452
1453   // Okay, we decided that this is a safe thing to do: go ahead and start
1454   // inserting cast instructions as necessary...
1455   std::vector<Value*> Args;
1456   Args.reserve(NumActualArgs);
1457
1458   AI = CS.arg_begin();
1459   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1460     const Type *ParamTy = FT->getParamType(i);
1461     if ((*AI)->getType() == ParamTy) {
1462       Args.push_back(*AI);
1463     } else {
1464       Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1465       InsertNewInstBefore(Cast, *Caller);
1466       Args.push_back(Cast);
1467     }
1468   }
1469
1470   // If the function takes more arguments than the call was taking, add them
1471   // now...
1472   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1473     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1474
1475   // If we are removing arguments to the function, emit an obnoxious warning...
1476   if (FT->getNumParams() < NumActualArgs)
1477     if (!FT->isVarArg()) {
1478       std::cerr << "WARNING: While resolving call to function '"
1479                 << Callee->getName() << "' arguments were dropped!\n";
1480     } else {
1481       // Add all of the arguments in their promoted form to the arg list...
1482       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1483         const Type *PTy = getPromotedType((*AI)->getType());
1484         if (PTy != (*AI)->getType()) {
1485           // Must promote to pass through va_arg area!
1486           Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1487           InsertNewInstBefore(Cast, *Caller);
1488           Args.push_back(Cast);
1489         } else {
1490           Args.push_back(*AI);
1491         }
1492       }
1493     }
1494
1495   if (FT->getReturnType() == Type::VoidTy)
1496     Caller->setName("");   // Void type should not have a name...
1497
1498   Instruction *NC;
1499   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1500     NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1501                         Args, Caller->getName(), Caller);
1502   } else {
1503     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1504   }
1505
1506   // Insert a cast of the return type as necessary...
1507   Value *NV = NC;
1508   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1509     if (NV->getType() != Type::VoidTy) {
1510       NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1511       InsertNewInstBefore(NC, *Caller);
1512       AddUsesToWorkList(*Caller);
1513     } else {
1514       NV = Constant::getNullValue(Caller->getType());
1515     }
1516   }
1517
1518   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1519     Caller->replaceAllUsesWith(NV);
1520   Caller->getParent()->getInstList().erase(Caller);
1521   removeFromWorkList(Caller);
1522   return true;
1523 }
1524
1525
1526
1527 // PHINode simplification
1528 //
1529 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
1530   // If the PHI node only has one incoming value, eliminate the PHI node...
1531   if (PN.getNumIncomingValues() == 1)
1532     return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
1533   
1534   // Otherwise if all of the incoming values are the same for the PHI, replace
1535   // the PHI node with the incoming value.
1536   //
1537   Value *InVal = 0;
1538   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1539     if (PN.getIncomingValue(i) != &PN)  // Not the PHI node itself...
1540       if (InVal && PN.getIncomingValue(i) != InVal)
1541         return 0;  // Not the same, bail out.
1542       else
1543         InVal = PN.getIncomingValue(i);
1544
1545   // The only case that could cause InVal to be null is if we have a PHI node
1546   // that only has entries for itself.  In this case, there is no entry into the
1547   // loop, so kill the PHI.
1548   //
1549   if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
1550
1551   // All of the incoming values are the same, replace the PHI node now.
1552   return ReplaceInstUsesWith(PN, InVal);
1553 }
1554
1555
1556 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1557   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
1558   // If so, eliminate the noop.
1559   if ((GEP.getNumOperands() == 2 &&
1560        GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
1561       GEP.getNumOperands() == 1)
1562     return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
1563
1564   // Combine Indices - If the source pointer to this getelementptr instruction
1565   // is a getelementptr instruction, combine the indices of the two
1566   // getelementptr instructions into a single instruction.
1567   //
1568   if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
1569     std::vector<Value *> Indices;
1570   
1571     // Can we combine the two pointer arithmetics offsets?
1572     if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1573         isa<Constant>(GEP.getOperand(1))) {
1574       // Replace: gep (gep %P, long C1), long C2, ...
1575       // With:    gep %P, long (C1+C2), ...
1576       Value *Sum = ConstantExpr::get(Instruction::Add,
1577                                      cast<Constant>(Src->getOperand(1)),
1578                                      cast<Constant>(GEP.getOperand(1)));
1579       assert(Sum && "Constant folding of longs failed!?");
1580       GEP.setOperand(0, Src->getOperand(0));
1581       GEP.setOperand(1, Sum);
1582       AddUsesToWorkList(*Src);   // Reduce use count of Src
1583       return &GEP;
1584     } else if (Src->getNumOperands() == 2) {
1585       // Replace: gep (gep %P, long B), long A, ...
1586       // With:    T = long A+B; gep %P, T, ...
1587       //
1588       Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1589                                           GEP.getOperand(1),
1590                                           Src->getName()+".sum", &GEP);
1591       GEP.setOperand(0, Src->getOperand(0));
1592       GEP.setOperand(1, Sum);
1593       WorkList.push_back(cast<Instruction>(Sum));
1594       return &GEP;
1595     } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
1596                Src->getNumOperands() != 1) { 
1597       // Otherwise we can do the fold if the first index of the GEP is a zero
1598       Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1599       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
1600     } else if (Src->getOperand(Src->getNumOperands()-1) == 
1601                Constant::getNullValue(Type::LongTy)) {
1602       // If the src gep ends with a constant array index, merge this get into
1603       // it, even if we have a non-zero array index.
1604       Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1605       Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
1606     }
1607
1608     if (!Indices.empty())
1609       return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
1610
1611   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1612     // GEP of global variable.  If all of the indices for this GEP are
1613     // constants, we can promote this to a constexpr instead of an instruction.
1614
1615     // Scan for nonconstants...
1616     std::vector<Constant*> Indices;
1617     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1618     for (; I != E && isa<Constant>(*I); ++I)
1619       Indices.push_back(cast<Constant>(*I));
1620
1621     if (I == E) {  // If they are all constants...
1622       Constant *CE =
1623         ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1624
1625       // Replace all uses of the GEP with the new constexpr...
1626       return ReplaceInstUsesWith(GEP, CE);
1627     }
1628   }
1629
1630   return 0;
1631 }
1632
1633 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1634   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1635   if (AI.isArrayAllocation())    // Check C != 1
1636     if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1637       const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
1638       AllocationInst *New = 0;
1639
1640       // Create and insert the replacement instruction...
1641       if (isa<MallocInst>(AI))
1642         New = new MallocInst(NewTy, 0, AI.getName(), &AI);
1643       else {
1644         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
1645         New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
1646       }
1647       
1648       // Scan to the end of the allocation instructions, to skip over a block of
1649       // allocas if possible...
1650       //
1651       BasicBlock::iterator It = New;
1652       while (isa<AllocationInst>(*It)) ++It;
1653
1654       // Now that I is pointing to the first non-allocation-inst in the block,
1655       // insert our getelementptr instruction...
1656       //
1657       std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1658       Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1659
1660       // Now make everything use the getelementptr instead of the original
1661       // allocation.
1662       ReplaceInstUsesWith(AI, V);
1663       return &AI;
1664     }
1665   return 0;
1666 }
1667
1668 /// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1669 /// constantexpr, return the constant value being addressed by the constant
1670 /// expression, or null if something is funny.
1671 ///
1672 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1673   if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1674     return 0;  // Do not allow stepping over the value!
1675
1676   // Loop over all of the operands, tracking down which value we are
1677   // addressing...
1678   for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1679     if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1680       ConstantStruct *CS = cast<ConstantStruct>(C);
1681       if (CU->getValue() >= CS->getValues().size()) return 0;
1682       C = cast<Constant>(CS->getValues()[CU->getValue()]);
1683     } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1684       ConstantArray *CA = cast<ConstantArray>(C);
1685       if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1686       C = cast<Constant>(CA->getValues()[CS->getValue()]);
1687     } else 
1688       return 0;
1689   return C;
1690 }
1691
1692 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1693   Value *Op = LI.getOperand(0);
1694   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1695     Op = CPR->getValue();
1696
1697   // Instcombine load (constant global) into the value loaded...
1698   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
1699     if (GV->isConstant() && !GV->isExternal())
1700       return ReplaceInstUsesWith(LI, GV->getInitializer());
1701
1702   // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1703   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1704     if (CE->getOpcode() == Instruction::GetElementPtr)
1705       if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1706         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
1707           if (GV->isConstant() && !GV->isExternal())
1708             if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1709               return ReplaceInstUsesWith(LI, V);
1710   return 0;
1711 }
1712
1713
1714 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1715   // Change br (not X), label True, label False to: br X, label False, True
1716   if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
1717     if (Value *V = dyn_castNotVal(BI.getCondition())) {
1718       BasicBlock *TrueDest = BI.getSuccessor(0);
1719       BasicBlock *FalseDest = BI.getSuccessor(1);
1720       // Swap Destinations and condition...
1721       BI.setCondition(V);
1722       BI.setSuccessor(0, FalseDest);
1723       BI.setSuccessor(1, TrueDest);
1724       return &BI;
1725     }
1726   return 0;
1727 }
1728
1729
1730 void InstCombiner::removeFromWorkList(Instruction *I) {
1731   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1732                  WorkList.end());
1733 }
1734
1735 bool InstCombiner::runOnFunction(Function &F) {
1736   bool Changed = false;
1737
1738   WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
1739
1740   while (!WorkList.empty()) {
1741     Instruction *I = WorkList.back();  // Get an instruction from the worklist
1742     WorkList.pop_back();
1743
1744     // Check to see if we can DCE or ConstantPropagate the instruction...
1745     // Check to see if we can DIE the instruction...
1746     if (isInstructionTriviallyDead(I)) {
1747       // Add operands to the worklist...
1748       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1749         if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1750           WorkList.push_back(Op);
1751
1752       ++NumDeadInst;
1753       BasicBlock::iterator BBI = I;
1754       if (dceInstruction(BBI)) {
1755         removeFromWorkList(I);
1756         continue;
1757       }
1758     } 
1759
1760     // Instruction isn't dead, see if we can constant propagate it...
1761     if (Constant *C = ConstantFoldInstruction(I)) {
1762       // Add operands to the worklist...
1763       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1764         if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1765           WorkList.push_back(Op);
1766       ReplaceInstUsesWith(*I, C);
1767
1768       ++NumConstProp;
1769       BasicBlock::iterator BBI = I;
1770       if (dceInstruction(BBI)) {
1771         removeFromWorkList(I);
1772         continue;
1773       }
1774     }
1775     
1776     // Now that we have an instruction, try combining it to simplify it...
1777     if (Instruction *Result = visit(*I)) {
1778       ++NumCombined;
1779       // Should we replace the old instruction with a new one?
1780       if (Result != I) {
1781         // Instructions can end up on the worklist more than once.  Make sure
1782         // we do not process an instruction that has been deleted.
1783         removeFromWorkList(I);
1784         ReplaceInstWithInst(I, Result);
1785       } else {
1786         BasicBlock::iterator II = I;
1787
1788         // If the instruction was modified, it's possible that it is now dead.
1789         // if so, remove it.
1790         if (dceInstruction(II)) {
1791           // Instructions may end up in the worklist more than once.  Erase them
1792           // all.
1793           removeFromWorkList(I);
1794           Result = 0;
1795         }
1796       }
1797
1798       if (Result) {
1799         WorkList.push_back(Result);
1800         AddUsesToWorkList(*Result);
1801       }
1802       Changed = true;
1803     }
1804   }
1805
1806   return Changed;
1807 }
1808
1809 Pass *createInstructionCombiningPass() {
1810   return new InstCombiner();
1811 }