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