Add support for elimination of load instruction from global constants
[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 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
295   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
296
297   if (Op0 == Op1)         // sub X, X  -> 0
298     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
299
300   // If this is a 'B = x-(-A)', change to B = x+A...
301   if (Value *V = dyn_castNegVal(Op1))
302     return BinaryOperator::create(Instruction::Add, Op0, V);
303
304   // Replace (-1 - A) with (~A)...
305   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
306     if (C->isAllOnesValue())
307       return BinaryOperator::createNot(Op1);
308
309   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
310     if (Op1I->use_size() == 1) {
311       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
312       // is not used by anyone else...
313       //
314       if (Op1I->getOpcode() == Instruction::Sub) {
315         // Swap the two operands of the subexpr...
316         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
317         Op1I->setOperand(0, IIOp1);
318         Op1I->setOperand(1, IIOp0);
319         
320         // Create the new top level add instruction...
321         return BinaryOperator::create(Instruction::Add, Op0, Op1);
322       }
323
324       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
325       //
326       if (Op1I->getOpcode() == Instruction::And &&
327           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
328         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
329
330         Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
331         return BinaryOperator::create(Instruction::And, Op0, NewNot);
332       }
333
334       // X - X*C --> X * (1-C)
335       if (dyn_castFoldableMul(Op1I) == Op0) {
336         Constant *CP1 =
337           ConstantExpr::get(Instruction::Sub,
338                             ConstantInt::get(I.getType(), 1),
339                          cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
340         assert(CP1 && "Couldn't constant fold 1-C?");
341         return BinaryOperator::create(Instruction::Mul, Op0, CP1);
342       }
343     }
344
345   // X*C - X --> X * (C-1)
346   if (dyn_castFoldableMul(Op0) == Op1) {
347     Constant *CP1 =
348       ConstantExpr::get(Instruction::Sub,
349                         cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
350                         ConstantInt::get(I.getType(), 1));
351     assert(CP1 && "Couldn't constant fold C - 1?");
352     return BinaryOperator::create(Instruction::Mul, Op1, CP1);
353   }
354
355   return 0;
356 }
357
358 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
359   bool Changed = SimplifyCommutative(I);
360   Value *Op0 = I.getOperand(0);
361
362   // Simplify mul instructions with a constant RHS...
363   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
364     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
365       const Type *Ty = CI->getType();
366       int64_t Val = Ty->isSigned() ?        cast<ConstantSInt>(CI)->getValue() :
367                                    (int64_t)cast<ConstantUInt>(CI)->getValue();
368       switch (Val) {
369       case -1:                               // X * -1 -> -X
370         return BinaryOperator::createNeg(Op0, I.getName());
371       case 0:
372         return ReplaceInstUsesWith(I, Op1);  // Eliminate 'mul double %X, 0'
373       case 1:
374         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul int %X, 1'
375       case 2:                     // Convert 'mul int %X, 2' to 'add int %X, %X'
376         return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
377       }
378
379       if (uint64_t C = Log2(Val))            // Replace X*(2^C) with X << C
380         return new ShiftInst(Instruction::Shl, Op0,
381                              ConstantUInt::get(Type::UByteTy, C));
382     } else {
383       ConstantFP *Op1F = cast<ConstantFP>(Op1);
384       if (Op1F->isNullValue())
385         return ReplaceInstUsesWith(I, Op1);
386
387       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
388       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
389       if (Op1F->getValue() == 1.0)
390         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
391     }
392   }
393
394   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
395     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
396       return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
397
398   return Changed ? &I : 0;
399 }
400
401 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
402   // div X, 1 == X
403   if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
404     if (RHS->equalsInt(1))
405       return ReplaceInstUsesWith(I, I.getOperand(0));
406
407     // Check to see if this is an unsigned division with an exact power of 2,
408     // if so, convert to a right shift.
409     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
410       if (uint64_t Val = C->getValue())    // Don't break X / 0
411         if (uint64_t C = Log2(Val))
412           return new ShiftInst(Instruction::Shr, I.getOperand(0),
413                                ConstantUInt::get(Type::UByteTy, C));
414   }
415
416   // 0 / X == 0, we don't need to preserve faults!
417   if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
418     if (LHS->equalsInt(0))
419       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
420
421   return 0;
422 }
423
424
425 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
426   if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
427     if (RHS->equalsInt(1))  // X % 1 == 0
428       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
429
430     // Check to see if this is an unsigned remainder with an exact power of 2,
431     // if so, convert to a bitwise and.
432     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
433       if (uint64_t Val = C->getValue())    // Don't break X % 0 (divide by zero)
434         if (Log2(Val))
435           return BinaryOperator::create(Instruction::And, I.getOperand(0),
436                                         ConstantUInt::get(I.getType(), Val-1));
437   }
438
439   // 0 % X == 0, we don't need to preserve faults!
440   if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
441     if (LHS->equalsInt(0))
442       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
443
444   return 0;
445 }
446
447 // isMaxValueMinusOne - return true if this is Max-1
448 static bool isMaxValueMinusOne(const ConstantInt *C) {
449   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
450     // Calculate -1 casted to the right type...
451     unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
452     uint64_t Val = ~0ULL;                // All ones
453     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
454     return CU->getValue() == Val-1;
455   }
456
457   const ConstantSInt *CS = cast<ConstantSInt>(C);
458   
459   // Calculate 0111111111..11111
460   unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
461   int64_t Val = INT64_MAX;             // All ones
462   Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
463   return CS->getValue() == Val-1;
464 }
465
466 // isMinValuePlusOne - return true if this is Min+1
467 static bool isMinValuePlusOne(const ConstantInt *C) {
468   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
469     return CU->getValue() == 1;
470
471   const ConstantSInt *CS = cast<ConstantSInt>(C);
472   
473   // Calculate 1111111111000000000000 
474   unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
475   int64_t Val = -1;                    // All ones
476   Val <<= TypeBits-1;                  // Shift over to the right spot
477   return CS->getValue() == Val+1;
478 }
479
480
481 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
482   bool Changed = SimplifyCommutative(I);
483   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
484
485   // and X, X = X   and X, 0 == 0
486   if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
487     return ReplaceInstUsesWith(I, Op1);
488
489   // and X, -1 == X
490   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
491     if (RHS->isAllOnesValue())
492       return ReplaceInstUsesWith(I, Op0);
493
494   Value *Op0NotVal = dyn_castNotVal(Op0);
495   Value *Op1NotVal = dyn_castNotVal(Op1);
496
497   // (~A & ~B) == (~(A | B)) - Demorgan's Law
498   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
499     Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
500                                              Op1NotVal,I.getName()+".demorgan",
501                                              &I);
502     WorkList.push_back(Or);
503     return BinaryOperator::createNot(Or);
504   }
505
506   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
507     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
508
509   return Changed ? &I : 0;
510 }
511
512
513
514 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
515   bool Changed = SimplifyCommutative(I);
516   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
517
518   // or X, X = X   or X, 0 == X
519   if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
520     return ReplaceInstUsesWith(I, Op0);
521
522   // or X, -1 == -1
523   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
524     if (RHS->isAllOnesValue())
525       return ReplaceInstUsesWith(I, Op1);
526
527   Value *Op0NotVal = dyn_castNotVal(Op0);
528   Value *Op1NotVal = dyn_castNotVal(Op1);
529
530   if (Op1 == Op0NotVal)   // ~A | A == -1
531     return ReplaceInstUsesWith(I, 
532                                ConstantIntegral::getAllOnesValue(I.getType()));
533
534   if (Op0 == Op1NotVal)   // A | ~A == -1
535     return ReplaceInstUsesWith(I, 
536                                ConstantIntegral::getAllOnesValue(I.getType()));
537
538   // (~A | ~B) == (~(A & B)) - Demorgan's Law
539   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
540     Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
541                                               Op1NotVal,I.getName()+".demorgan",
542                                               &I);
543     WorkList.push_back(And);
544     return BinaryOperator::createNot(And);
545   }
546
547   return Changed ? &I : 0;
548 }
549
550
551
552 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
553   bool Changed = SimplifyCommutative(I);
554   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
555
556   // xor X, X = 0
557   if (Op0 == Op1)
558     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
559
560   if (ConstantIntegral *Op1C = dyn_cast<ConstantIntegral>(Op1)) {
561     // xor X, 0 == X
562     if (Op1C->isNullValue())
563       return ReplaceInstUsesWith(I, Op0);
564
565     // Is this a "NOT" instruction?
566     if (Op1C->isAllOnesValue()) {
567       // xor (xor X, -1), -1 = not (not X) = X
568       if (Value *X = dyn_castNotVal(Op0))
569         return ReplaceInstUsesWith(I, X);
570
571       // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
572       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0))
573         if (SCI->use_size() == 1)
574           return new SetCondInst(SCI->getInverseCondition(),
575                                  SCI->getOperand(0), SCI->getOperand(1));
576     }
577   }
578
579   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
580     if (X == Op1)
581       return ReplaceInstUsesWith(I,
582                                 ConstantIntegral::getAllOnesValue(I.getType()));
583
584   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
585     if (X == Op0)
586       return ReplaceInstUsesWith(I,
587                                 ConstantIntegral::getAllOnesValue(I.getType()));
588
589   if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
590     if (Op1I->getOpcode() == Instruction::Or)
591       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
592         cast<BinaryOperator>(Op1I)->swapOperands();
593         I.swapOperands();
594         std::swap(Op0, Op1);
595       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
596         I.swapOperands();
597         std::swap(Op0, Op1);
598       }
599
600   if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
601     if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
602       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
603         cast<BinaryOperator>(Op0I)->swapOperands();
604       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
605         Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
606         WorkList.push_back(cast<Instruction>(NotB));
607         return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
608                                       NotB);
609       }
610     }
611
612   // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
613   if (Constant *C1 = dyn_castMaskingAnd(Op0))
614     if (Constant *C2 = dyn_castMaskingAnd(Op1))
615       if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
616         return BinaryOperator::create(Instruction::Or, Op0, Op1);
617
618   return Changed ? &I : 0;
619 }
620
621 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
622 static Constant *AddOne(ConstantInt *C) {
623   Constant *Result = ConstantExpr::get(Instruction::Add, C,
624                                        ConstantInt::get(C->getType(), 1));
625   assert(Result && "Constant folding integer addition failed!");
626   return Result;
627 }
628 static Constant *SubOne(ConstantInt *C) {
629   Constant *Result = ConstantExpr::get(Instruction::Sub, C,
630                                        ConstantInt::get(C->getType(), 1));
631   assert(Result && "Constant folding integer addition failed!");
632   return Result;
633 }
634
635 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
636 // true when both operands are equal...
637 //
638 static bool isTrueWhenEqual(Instruction &I) {
639   return I.getOpcode() == Instruction::SetEQ ||
640          I.getOpcode() == Instruction::SetGE ||
641          I.getOpcode() == Instruction::SetLE;
642 }
643
644 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
645   bool Changed = SimplifyCommutative(I);
646   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
647   const Type *Ty = Op0->getType();
648
649   // setcc X, X
650   if (Op0 == Op1)
651     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
652
653   // setcc <global*>, 0 - Global value addresses are never null!
654   if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
655     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
656
657   // setcc's with boolean values can always be turned into bitwise operations
658   if (Ty == Type::BoolTy) {
659     // If this is <, >, or !=, we can change this into a simple xor instruction
660     if (!isTrueWhenEqual(I))
661       return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
662
663     // Otherwise we need to make a temporary intermediate instruction and insert
664     // it into the instruction stream.  This is what we are after:
665     //
666     //  seteq bool %A, %B -> ~(A^B)
667     //  setle bool %A, %B -> ~A | B
668     //  setge bool %A, %B -> A | ~B
669     //
670     if (I.getOpcode() == Instruction::SetEQ) {  // seteq case
671       Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
672                                                 I.getName()+"tmp");
673       InsertNewInstBefore(Xor, I);
674       return BinaryOperator::createNot(Xor, I.getName());
675     }
676
677     // Handle the setXe cases...
678     assert(I.getOpcode() == Instruction::SetGE ||
679            I.getOpcode() == Instruction::SetLE);
680
681     if (I.getOpcode() == Instruction::SetGE)
682       std::swap(Op0, Op1);                   // Change setge -> setle
683
684     // Now we just have the SetLE case.
685     Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
686     InsertNewInstBefore(Not, I);
687     return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
688   }
689
690   // Check to see if we are doing one of many comparisons against constant
691   // integers at the end of their ranges...
692   //
693   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
694     if (CI->isNullValue()) {
695       if (I.getOpcode() == Instruction::SetNE)
696         return new CastInst(Op0, Type::BoolTy, I.getName());
697       else if (I.getOpcode() == Instruction::SetEQ) {
698         // seteq X, 0 -> not (cast X to bool)
699         Instruction *Val = new CastInst(Op0, Type::BoolTy, I.getName()+".not");
700         InsertNewInstBefore(Val, I);
701         return BinaryOperator::createNot(Val, I.getName());
702       }
703     }
704
705     // Check to see if we are comparing against the minimum or maximum value...
706     if (CI->isMinValue()) {
707       if (I.getOpcode() == Instruction::SetLT)       // A < MIN -> FALSE
708         return ReplaceInstUsesWith(I, ConstantBool::False);
709       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN -> TRUE
710         return ReplaceInstUsesWith(I, ConstantBool::True);
711       if (I.getOpcode() == Instruction::SetLE)       // A <= MIN -> A == MIN
712         return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
713       if (I.getOpcode() == Instruction::SetGT)       // A > MIN -> A != MIN
714         return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
715
716     } else if (CI->isMaxValue()) {
717       if (I.getOpcode() == Instruction::SetGT)       // A > MAX -> FALSE
718         return ReplaceInstUsesWith(I, ConstantBool::False);
719       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX -> TRUE
720         return ReplaceInstUsesWith(I, ConstantBool::True);
721       if (I.getOpcode() == Instruction::SetGE)       // A >= MAX -> A == MAX
722         return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
723       if (I.getOpcode() == Instruction::SetLT)       // A < MAX -> A != MAX
724         return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
725
726       // Comparing against a value really close to min or max?
727     } else if (isMinValuePlusOne(CI)) {
728       if (I.getOpcode() == Instruction::SetLT)       // A < MIN+1 -> A == MIN
729         return BinaryOperator::create(Instruction::SetEQ, Op0,
730                                       SubOne(CI), I.getName());
731       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN-1 -> A != MIN
732         return BinaryOperator::create(Instruction::SetNE, Op0,
733                                       SubOne(CI), I.getName());
734
735     } else if (isMaxValueMinusOne(CI)) {
736       if (I.getOpcode() == Instruction::SetGT)       // A > MAX-1 -> A == MAX
737         return BinaryOperator::create(Instruction::SetEQ, Op0,
738                                       AddOne(CI), I.getName());
739       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX-1 -> A != MAX
740         return BinaryOperator::create(Instruction::SetNE, Op0,
741                                       AddOne(CI), I.getName());
742     }
743   }
744
745   return Changed ? &I : 0;
746 }
747
748
749
750 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
751   assert(I.getOperand(1)->getType() == Type::UByteTy);
752   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
753
754   // shl X, 0 == X and shr X, 0 == X
755   // shl 0, X == 0 and shr 0, X == 0
756   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
757       Op0 == Constant::getNullValue(Op0->getType()))
758     return ReplaceInstUsesWith(I, Op0);
759
760   // If this is a shift of a shift, see if we can fold the two together...
761   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0)) {
762     if (isa<Constant>(Op1) && isa<Constant>(Op0SI->getOperand(1))) {
763       ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(Op0SI->getOperand(1));
764       unsigned ShiftAmt1 = ShiftAmt1C->getValue();
765       unsigned ShiftAmt2 = cast<ConstantUInt>(Op1)->getValue();
766
767       // Check for (A << c1) << c2   and   (A >> c1) >> c2
768       if (I.getOpcode() == Op0SI->getOpcode()) {
769         unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift...
770         return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
771                              ConstantUInt::get(Type::UByteTy, Amt));
772       }
773
774       if (I.getType()->isUnsigned()) { // Check for (A << c1) >> c2 or visaversa
775         // Calculate bitmask for what gets shifted off the edge...
776         Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
777         if (I.getOpcode() == Instruction::Shr)
778           C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
779         else
780           C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
781           
782         Instruction *Mask =
783           BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
784                                  C, Op0SI->getOperand(0)->getName()+".mask",&I);
785         WorkList.push_back(Mask);
786           
787         // Figure out what flavor of shift we should use...
788         if (ShiftAmt1 == ShiftAmt2)
789           return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
790         else if (ShiftAmt1 < ShiftAmt2) {
791           return new ShiftInst(I.getOpcode(), Mask,
792                          ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
793         } else {
794           return new ShiftInst(Op0SI->getOpcode(), Mask,
795                          ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
796         }
797       }
798     }
799   }
800
801   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr of
802   // a signed value.
803   //
804   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
805     unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
806     if (CUI->getValue() >= TypeBits &&
807         (!Op0->getType()->isSigned() || I.getOpcode() == Instruction::Shl))
808       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
809
810     // Check to see if we are shifting left by 1.  If so, turn it into an add
811     // instruction.
812     if (I.getOpcode() == Instruction::Shl && CUI->equalsInt(1))
813       // Convert 'shl int %X, 1' to 'add int %X, %X'
814       return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
815
816   }
817
818   // shr int -1, X = -1   (for any arithmetic shift rights of ~0)
819   if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
820     if (I.getOpcode() == Instruction::Shr && CSI->isAllOnesValue())
821       return ReplaceInstUsesWith(I, CSI);
822   
823   return 0;
824 }
825
826
827 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
828 // instruction.
829 //
830 static inline bool isEliminableCastOfCast(const CastInst &CI,
831                                           const CastInst *CSrc) {
832   assert(CI.getOperand(0) == CSrc);
833   const Type *SrcTy = CSrc->getOperand(0)->getType();
834   const Type *MidTy = CSrc->getType();
835   const Type *DstTy = CI.getType();
836
837   // It is legal to eliminate the instruction if casting A->B->A if the sizes
838   // are identical and the bits don't get reinterpreted (for example 
839   // int->float->int would not be allowed)
840   if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
841     return true;
842
843   // Allow free casting and conversion of sizes as long as the sign doesn't
844   // change...
845   if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
846     unsigned SrcSize = SrcTy->getPrimitiveSize();
847     unsigned MidSize = MidTy->getPrimitiveSize();
848     unsigned DstSize = DstTy->getPrimitiveSize();
849
850     // Cases where we are monotonically decreasing the size of the type are
851     // always ok, regardless of what sign changes are going on.
852     //
853     if (SrcSize >= MidSize && MidSize >= DstSize)
854       return true;
855
856     // Cases where the source and destination type are the same, but the middle
857     // type is bigger are noops.
858     //
859     if (SrcSize == DstSize && MidSize > SrcSize)
860       return true;
861
862     // If we are monotonically growing, things are more complex.
863     //
864     if (SrcSize <= MidSize && MidSize <= DstSize) {
865       // We have eight combinations of signedness to worry about. Here's the
866       // table:
867       static const int SignTable[8] = {
868         // CODE, SrcSigned, MidSigned, DstSigned, Comment
869         1,     //   U          U          U       Always ok
870         1,     //   U          U          S       Always ok
871         3,     //   U          S          U       Ok iff SrcSize != MidSize
872         3,     //   U          S          S       Ok iff SrcSize != MidSize
873         0,     //   S          U          U       Never ok
874         2,     //   S          U          S       Ok iff MidSize == DstSize
875         1,     //   S          S          U       Always ok
876         1,     //   S          S          S       Always ok
877       };
878
879       // Choose an action based on the current entry of the signtable that this
880       // cast of cast refers to...
881       unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
882       switch (SignTable[Row]) {
883       case 0: return false;              // Never ok
884       case 1: return true;               // Always ok
885       case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
886       case 3:                            // Ok iff SrcSize != MidSize
887         return SrcSize != MidSize || SrcTy == Type::BoolTy;
888       default: assert(0 && "Bad entry in sign table!");
889       }
890     }
891   }
892
893   // Otherwise, we cannot succeed.  Specifically we do not want to allow things
894   // like:  short -> ushort -> uint, because this can create wrong results if
895   // the input short is negative!
896   //
897   return false;
898 }
899
900
901 // CastInst simplification
902 //
903 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
904   Value *Src = CI.getOperand(0);
905
906   // If the user is casting a value to the same type, eliminate this cast
907   // instruction...
908   if (CI.getType() == Src->getType())
909     return ReplaceInstUsesWith(CI, Src);
910
911   // If casting the result of another cast instruction, try to eliminate this
912   // one!
913   //
914   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
915     if (isEliminableCastOfCast(CI, CSrc)) {
916       // This instruction now refers directly to the cast's src operand.  This
917       // has a good chance of making CSrc dead.
918       CI.setOperand(0, CSrc->getOperand(0));
919       return &CI;
920     }
921
922     // If this is an A->B->A cast, and we are dealing with integral types, try
923     // to convert this into a logical 'and' instruction.
924     //
925     if (CSrc->getOperand(0)->getType() == CI.getType() &&
926         CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
927         CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
928         CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
929       assert(CSrc->getType() != Type::ULongTy &&
930              "Cannot have type bigger than ulong!");
931       uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
932       Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
933       return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
934                                     AndOp);
935     }
936   }
937
938   // If casting the result of a getelementptr instruction with no offset, turn
939   // this into a cast of the original pointer!
940   //
941   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
942     bool AllZeroOperands = true;
943     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
944       if (!isa<Constant>(GEP->getOperand(i)) ||
945           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
946         AllZeroOperands = false;
947         break;
948       }
949     if (AllZeroOperands) {
950       CI.setOperand(0, GEP->getOperand(0));
951       return &CI;
952     }
953   }
954
955   // If this is a cast to bool (which is effectively a "!=0" test), then we can
956   // perform a few optimizations...
957   //
958   if (CI.getType() == Type::BoolTy) {
959     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Src)) {
960       Value *Op0 = BO->getOperand(0), *Op1 = BO->getOperand(1);
961
962       // Replace (cast (sub A, B) to bool) with (setne A, B)
963       if (BO->getOpcode() == Instruction::Sub)
964         return new SetCondInst(Instruction::SetNE, Op0, Op1);
965
966       // Replace (cast (add A, B) to bool) with (setne A, -B) if B is
967       // efficiently invertible, or if the add has just this one use.
968       if (BO->getOpcode() == Instruction::Add)
969         if (Value *NegVal = dyn_castNegVal(Op1))
970           return new SetCondInst(Instruction::SetNE, Op0, NegVal);
971         else if (Value *NegVal = dyn_castNegVal(Op0))
972           return new SetCondInst(Instruction::SetNE, NegVal, Op1);
973         else if (BO->use_size() == 1) {
974           Instruction *Neg = BinaryOperator::createNeg(Op1, BO->getName());
975           BO->setName("");
976           InsertNewInstBefore(Neg, CI);
977           return new SetCondInst(Instruction::SetNE, Op0, Neg);
978         }
979     }
980   }
981
982   return 0;
983 }
984
985 // CallInst simplification
986 //
987 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
988   if (transformConstExprCastCall(&CI)) return 0;
989   return 0;
990 }
991
992 // InvokeInst simplification
993 //
994 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
995   if (transformConstExprCastCall(&II)) return 0;
996   return 0;
997 }
998
999 // getPromotedType - Return the specified type promoted as it would be to pass
1000 // though a va_arg area...
1001 static const Type *getPromotedType(const Type *Ty) {
1002   switch (Ty->getPrimitiveID()) {
1003   case Type::SByteTyID:
1004   case Type::ShortTyID:  return Type::IntTy;
1005   case Type::UByteTyID:
1006   case Type::UShortTyID: return Type::UIntTy;
1007   case Type::FloatTyID:  return Type::DoubleTy;
1008   default:               return Ty;
1009   }
1010 }
1011
1012 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
1013 // attempt to move the cast to the arguments of the call/invoke.
1014 //
1015 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1016   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1017   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1018   if (CE->getOpcode() != Instruction::Cast ||
1019       !isa<ConstantPointerRef>(CE->getOperand(0)))
1020     return false;
1021   ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1022   if (!isa<Function>(CPR->getValue())) return false;
1023   Function *Callee = cast<Function>(CPR->getValue());
1024   Instruction *Caller = CS.getInstruction();
1025
1026   // Okay, this is a cast from a function to a different type.  Unless doing so
1027   // would cause a type conversion of one of our arguments, change this call to
1028   // be a direct call with arguments casted to the appropriate types.
1029   //
1030   const FunctionType *FT = Callee->getFunctionType();
1031   const Type *OldRetTy = Caller->getType();
1032
1033   if (Callee->isExternal() &&
1034       !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1035     return false;   // Cannot transform this return value...
1036
1037   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1038   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1039                                     
1040   CallSite::arg_iterator AI = CS.arg_begin();
1041   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1042     const Type *ParamTy = FT->getParamType(i);
1043     bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1044     if (Callee->isExternal() && !isConvertible) return false;    
1045   }
1046
1047   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1048       Callee->isExternal())
1049     return false;   // Do not delete arguments unless we have a function body...
1050
1051   // Okay, we decided that this is a safe thing to do: go ahead and start
1052   // inserting cast instructions as necessary...
1053   std::vector<Value*> Args;
1054   Args.reserve(NumActualArgs);
1055
1056   AI = CS.arg_begin();
1057   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1058     const Type *ParamTy = FT->getParamType(i);
1059     if ((*AI)->getType() == ParamTy) {
1060       Args.push_back(*AI);
1061     } else {
1062       Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1063       InsertNewInstBefore(Cast, *Caller);
1064       Args.push_back(Cast);
1065     }
1066   }
1067
1068   // If the function takes more arguments than the call was taking, add them
1069   // now...
1070   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1071     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1072
1073   // If we are removing arguments to the function, emit an obnoxious warning...
1074   if (FT->getNumParams() < NumActualArgs)
1075     if (!FT->isVarArg()) {
1076       std::cerr << "WARNING: While resolving call to function '"
1077                 << Callee->getName() << "' arguments were dropped!\n";
1078     } else {
1079       // Add all of the arguments in their promoted form to the arg list...
1080       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1081         const Type *PTy = getPromotedType((*AI)->getType());
1082         if (PTy != (*AI)->getType()) {
1083           // Must promote to pass through va_arg area!
1084           Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1085           InsertNewInstBefore(Cast, *Caller);
1086           Args.push_back(Cast);
1087         } else {
1088           Args.push_back(*AI);
1089         }
1090       }
1091     }
1092
1093   if (FT->getReturnType() == Type::VoidTy)
1094     Caller->setName("");   // Void type should not have a name...
1095
1096   Instruction *NC;
1097   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1098     NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1099                         Args, Caller->getName(), Caller);
1100   } else {
1101     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1102   }
1103
1104   // Insert a cast of the return type as necessary...
1105   Value *NV = NC;
1106   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1107     if (NV->getType() != Type::VoidTy) {
1108       NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1109       InsertNewInstBefore(NC, *Caller);
1110       AddUsesToWorkList(*Caller);
1111     } else {
1112       NV = Constant::getNullValue(Caller->getType());
1113     }
1114   }
1115
1116   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1117     Caller->replaceAllUsesWith(NV);
1118   Caller->getParent()->getInstList().erase(Caller);
1119   removeFromWorkList(Caller);
1120   return true;
1121 }
1122
1123
1124
1125 // PHINode simplification
1126 //
1127 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
1128   // If the PHI node only has one incoming value, eliminate the PHI node...
1129   if (PN.getNumIncomingValues() == 1)
1130     return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
1131   
1132   // Otherwise if all of the incoming values are the same for the PHI, replace
1133   // the PHI node with the incoming value.
1134   //
1135   Value *InVal = 0;
1136   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1137     if (PN.getIncomingValue(i) != &PN)  // Not the PHI node itself...
1138       if (InVal && PN.getIncomingValue(i) != InVal)
1139         return 0;  // Not the same, bail out.
1140       else
1141         InVal = PN.getIncomingValue(i);
1142
1143   // The only case that could cause InVal to be null is if we have a PHI node
1144   // that only has entries for itself.  In this case, there is no entry into the
1145   // loop, so kill the PHI.
1146   //
1147   if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
1148
1149   // All of the incoming values are the same, replace the PHI node now.
1150   return ReplaceInstUsesWith(PN, InVal);
1151 }
1152
1153
1154 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1155   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
1156   // If so, eliminate the noop.
1157   if ((GEP.getNumOperands() == 2 &&
1158        GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
1159       GEP.getNumOperands() == 1)
1160     return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
1161
1162   // Combine Indices - If the source pointer to this getelementptr instruction
1163   // is a getelementptr instruction, combine the indices of the two
1164   // getelementptr instructions into a single instruction.
1165   //
1166   if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
1167     std::vector<Value *> Indices;
1168   
1169     // Can we combine the two pointer arithmetics offsets?
1170     if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1171         isa<Constant>(GEP.getOperand(1))) {
1172       // Replace: gep (gep %P, long C1), long C2, ...
1173       // With:    gep %P, long (C1+C2), ...
1174       Value *Sum = ConstantExpr::get(Instruction::Add,
1175                                      cast<Constant>(Src->getOperand(1)),
1176                                      cast<Constant>(GEP.getOperand(1)));
1177       assert(Sum && "Constant folding of longs failed!?");
1178       GEP.setOperand(0, Src->getOperand(0));
1179       GEP.setOperand(1, Sum);
1180       AddUsesToWorkList(*Src);   // Reduce use count of Src
1181       return &GEP;
1182     } else if (Src->getNumOperands() == 2) {
1183       // Replace: gep (gep %P, long B), long A, ...
1184       // With:    T = long A+B; gep %P, T, ...
1185       //
1186       Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1187                                           GEP.getOperand(1),
1188                                           Src->getName()+".sum", &GEP);
1189       GEP.setOperand(0, Src->getOperand(0));
1190       GEP.setOperand(1, Sum);
1191       WorkList.push_back(cast<Instruction>(Sum));
1192       return &GEP;
1193     } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
1194                Src->getNumOperands() != 1) { 
1195       // Otherwise we can do the fold if the first index of the GEP is a zero
1196       Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1197       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
1198     } else if (Src->getOperand(Src->getNumOperands()-1) == 
1199                Constant::getNullValue(Type::LongTy)) {
1200       // If the src gep ends with a constant array index, merge this get into
1201       // it, even if we have a non-zero array index.
1202       Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1203       Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
1204     }
1205
1206     if (!Indices.empty())
1207       return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
1208
1209   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1210     // GEP of global variable.  If all of the indices for this GEP are
1211     // constants, we can promote this to a constexpr instead of an instruction.
1212
1213     // Scan for nonconstants...
1214     std::vector<Constant*> Indices;
1215     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1216     for (; I != E && isa<Constant>(*I); ++I)
1217       Indices.push_back(cast<Constant>(*I));
1218
1219     if (I == E) {  // If they are all constants...
1220       Constant *CE =
1221         ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1222
1223       // Replace all uses of the GEP with the new constexpr...
1224       return ReplaceInstUsesWith(GEP, CE);
1225     }
1226   }
1227
1228   return 0;
1229 }
1230
1231 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1232   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1233   if (AI.isArrayAllocation())    // Check C != 1
1234     if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1235       const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
1236       AllocationInst *New = 0;
1237
1238       // Create and insert the replacement instruction...
1239       if (isa<MallocInst>(AI))
1240         New = new MallocInst(NewTy, 0, AI.getName(), &AI);
1241       else {
1242         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
1243         New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
1244       }
1245       
1246       // Scan to the end of the allocation instructions, to skip over a block of
1247       // allocas if possible...
1248       //
1249       BasicBlock::iterator It = New;
1250       while (isa<AllocationInst>(*It)) ++It;
1251
1252       // Now that I is pointing to the first non-allocation-inst in the block,
1253       // insert our getelementptr instruction...
1254       //
1255       std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1256       Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1257
1258       // Now make everything use the getelementptr instead of the original
1259       // allocation.
1260       ReplaceInstUsesWith(AI, V);
1261       return &AI;
1262     }
1263   return 0;
1264 }
1265
1266 /// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1267 /// constantexpr, return the constant value being addressed by the constant
1268 /// expression, or null if something is funny.
1269 ///
1270 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1271   if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1272     return 0;  // Do not allow stepping over the value!
1273
1274   // Loop over all of the operands, tracking down which value we are
1275   // addressing...
1276   for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1277     if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1278       ConstantStruct *CS = cast<ConstantStruct>(C);
1279       if (CU->getValue() >= CS->getValues().size()) return 0;
1280       C = cast<Constant>(CS->getValues()[CU->getValue()]);
1281     } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1282       ConstantArray *CA = cast<ConstantArray>(C);
1283       if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1284       C = cast<Constant>(CA->getValues()[CS->getValue()]);
1285     } else 
1286       return 0;
1287   return C;
1288 }
1289
1290 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1291   Value *Op = LI.getOperand(0);
1292   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1293     Op = CPR->getValue();
1294
1295   // Instcombine load (constant global) into the value loaded...
1296   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
1297     if (GV->isConstant())
1298       return ReplaceInstUsesWith(LI, GV->getInitializer());
1299
1300   // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1301   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1302     if (CE->getOpcode() == Instruction::GetElementPtr)
1303       if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1304         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
1305           if (GV->isConstant())
1306             if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1307               return ReplaceInstUsesWith(LI, V);
1308   return 0;
1309 }
1310
1311
1312 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1313   // Change br (not X), label True, label False to: br X, label False, True
1314   if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
1315     if (Value *V = dyn_castNotVal(BI.getCondition())) {
1316       BasicBlock *TrueDest = BI.getSuccessor(0);
1317       BasicBlock *FalseDest = BI.getSuccessor(1);
1318       // Swap Destinations and condition...
1319       BI.setCondition(V);
1320       BI.setSuccessor(0, FalseDest);
1321       BI.setSuccessor(1, TrueDest);
1322       return &BI;
1323     }
1324   return 0;
1325 }
1326
1327
1328 void InstCombiner::removeFromWorkList(Instruction *I) {
1329   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1330                  WorkList.end());
1331 }
1332
1333 bool InstCombiner::runOnFunction(Function &F) {
1334   bool Changed = false;
1335
1336   WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
1337
1338   while (!WorkList.empty()) {
1339     Instruction *I = WorkList.back();  // Get an instruction from the worklist
1340     WorkList.pop_back();
1341
1342     // Check to see if we can DCE or ConstantPropagate the instruction...
1343     // Check to see if we can DIE the instruction...
1344     if (isInstructionTriviallyDead(I)) {
1345       // Add operands to the worklist...
1346       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1347         if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1348           WorkList.push_back(Op);
1349
1350       ++NumDeadInst;
1351       BasicBlock::iterator BBI = I;
1352       if (dceInstruction(BBI)) {
1353         removeFromWorkList(I);
1354         continue;
1355       }
1356     } 
1357
1358     // Instruction isn't dead, see if we can constant propagate it...
1359     if (Constant *C = ConstantFoldInstruction(I)) {
1360       // Add operands to the worklist...
1361       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1362         if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1363           WorkList.push_back(Op);
1364       ReplaceInstUsesWith(*I, C);
1365
1366       ++NumConstProp;
1367       BasicBlock::iterator BBI = I;
1368       if (dceInstruction(BBI)) {
1369         removeFromWorkList(I);
1370         continue;
1371       }
1372     }
1373     
1374     // Now that we have an instruction, try combining it to simplify it...
1375     if (Instruction *Result = visit(*I)) {
1376       ++NumCombined;
1377       // Should we replace the old instruction with a new one?
1378       if (Result != I) {
1379         // Instructions can end up on the worklist more than once.  Make sure
1380         // we do not process an instruction that has been deleted.
1381         removeFromWorkList(I);
1382         ReplaceInstWithInst(I, Result);
1383       } else {
1384         BasicBlock::iterator II = I;
1385
1386         // If the instruction was modified, it's possible that it is now dead.
1387         // if so, remove it.
1388         if (dceInstruction(II)) {
1389           // Instructions may end up in the worklist more than once.  Erase them
1390           // all.
1391           removeFromWorkList(I);
1392           Result = 0;
1393         }
1394       }
1395
1396       if (Result) {
1397         WorkList.push_back(Result);
1398         AddUsesToWorkList(*Result);
1399       }
1400       Changed = true;
1401     }
1402   }
1403
1404   return Changed;
1405 }
1406
1407 Pass *createInstructionCombiningPass() {
1408   return new InstCombiner();
1409 }