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