Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG This pass is where algebraic
12 // simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add int %X, 1
16 //    %Z = add int %Y, 1
17 // into:
18 //    %Z = add int %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All SetCC instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/ADT/DepthFirstIterator.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include <algorithm>
55 #include <iostream>
56 using namespace llvm;
57 using namespace llvm::PatternMatch;
58
59 namespace {
60   Statistic<> NumCombined ("instcombine", "Number of insts combined");
61   Statistic<> NumConstProp("instcombine", "Number of constant folds");
62   Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
63   Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
64
65   class InstCombiner : public FunctionPass,
66                        public InstVisitor<InstCombiner, Instruction*> {
67     // Worklist of all of the instructions that need to be simplified.
68     std::vector<Instruction*> WorkList;
69     TargetData *TD;
70
71     /// AddUsersToWorkList - When an instruction is simplified, add all users of
72     /// the instruction to the work lists because they might get more simplified
73     /// now.
74     ///
75     void AddUsersToWorkList(Instruction &I) {
76       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
77            UI != UE; ++UI)
78         WorkList.push_back(cast<Instruction>(*UI));
79     }
80
81     /// AddUsesToWorkList - When an instruction is simplified, add operands to
82     /// the work lists because they might get more simplified now.
83     ///
84     void AddUsesToWorkList(Instruction &I) {
85       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
86         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
87           WorkList.push_back(Op);
88     }
89
90     // removeFromWorkList - remove all instances of I from the worklist.
91     void removeFromWorkList(Instruction *I);
92   public:
93     virtual bool runOnFunction(Function &F);
94
95     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
96       AU.addRequired<TargetData>();
97       AU.setPreservesCFG();
98     }
99
100     TargetData &getTargetData() const { return *TD; }
101
102     // Visitation implementation - Implement instruction combining for different
103     // instruction types.  The semantics are as follows:
104     // Return Value:
105     //    null        - No change was made
106     //     I          - Change was made, I is still valid, I may be dead though
107     //   otherwise    - Change was made, replace I with returned instruction
108     //
109     Instruction *visitAdd(BinaryOperator &I);
110     Instruction *visitSub(BinaryOperator &I);
111     Instruction *visitMul(BinaryOperator &I);
112     Instruction *visitDiv(BinaryOperator &I);
113     Instruction *visitRem(BinaryOperator &I);
114     Instruction *visitAnd(BinaryOperator &I);
115     Instruction *visitOr (BinaryOperator &I);
116     Instruction *visitXor(BinaryOperator &I);
117     Instruction *visitSetCondInst(SetCondInst &I);
118     Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
119
120     Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
121                               Instruction::BinaryOps Cond, Instruction &I);
122     Instruction *visitShiftInst(ShiftInst &I);
123     Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
124                                      ShiftInst &I);
125     Instruction *visitCastInst(CastInst &CI);
126     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
127                                 Instruction *FI);
128     Instruction *visitSelectInst(SelectInst &CI);
129     Instruction *visitCallInst(CallInst &CI);
130     Instruction *visitInvokeInst(InvokeInst &II);
131     Instruction *visitPHINode(PHINode &PN);
132     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
133     Instruction *visitAllocationInst(AllocationInst &AI);
134     Instruction *visitFreeInst(FreeInst &FI);
135     Instruction *visitLoadInst(LoadInst &LI);
136     Instruction *visitStoreInst(StoreInst &SI);
137     Instruction *visitBranchInst(BranchInst &BI);
138     Instruction *visitSwitchInst(SwitchInst &SI);
139     Instruction *visitExtractElementInst(ExtractElementInst &EI);
140
141     // visitInstruction - Specify what to return for unhandled instructions...
142     Instruction *visitInstruction(Instruction &I) { return 0; }
143
144   private:
145     Instruction *visitCallSite(CallSite CS);
146     bool transformConstExprCastCall(CallSite CS);
147
148   public:
149     // InsertNewInstBefore - insert an instruction New before instruction Old
150     // in the program.  Add the new instruction to the worklist.
151     //
152     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
153       assert(New && New->getParent() == 0 &&
154              "New instruction already inserted into a basic block!");
155       BasicBlock *BB = Old.getParent();
156       BB->getInstList().insert(&Old, New);  // Insert inst
157       WorkList.push_back(New);              // Add to worklist
158       return New;
159     }
160
161     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
162     /// This also adds the cast to the worklist.  Finally, this returns the
163     /// cast.
164     Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
165       if (V->getType() == Ty) return V;
166
167       Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
168       WorkList.push_back(C);
169       return C;
170     }
171
172     // ReplaceInstUsesWith - This method is to be used when an instruction is
173     // found to be dead, replacable with another preexisting expression.  Here
174     // we add all uses of I to the worklist, replace all uses of I with the new
175     // value, then return I, so that the inst combiner will know that I was
176     // modified.
177     //
178     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
179       AddUsersToWorkList(I);         // Add all modified instrs to worklist
180       if (&I != V) {
181         I.replaceAllUsesWith(V);
182         return &I;
183       } else {
184         // If we are replacing the instruction with itself, this must be in a
185         // segment of unreachable code, so just clobber the instruction.
186         I.replaceAllUsesWith(UndefValue::get(I.getType()));
187         return &I;
188       }
189     }
190
191     // EraseInstFromFunction - When dealing with an instruction that has side
192     // effects or produces a void value, we can't rely on DCE to delete the
193     // instruction.  Instead, visit methods should return the value returned by
194     // this function.
195     Instruction *EraseInstFromFunction(Instruction &I) {
196       assert(I.use_empty() && "Cannot erase instruction that is used!");
197       AddUsesToWorkList(I);
198       removeFromWorkList(&I);
199       I.eraseFromParent();
200       return 0;  // Don't do anything with FI
201     }
202
203
204   private:
205     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
206     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
207     /// casts that are known to not do anything...
208     ///
209     Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
210                                    Instruction *InsertBefore);
211
212     // SimplifyCommutative - This performs a few simplifications for commutative
213     // operators.
214     bool SimplifyCommutative(BinaryOperator &I);
215
216
217     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
218     // PHI node as operand #0, see if we can fold the instruction into the PHI
219     // (which is only possible if all operands to the PHI are constants).
220     Instruction *FoldOpIntoPhi(Instruction &I);
221
222     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
223     // operator and they all are only used by the PHI, PHI together their
224     // inputs, and do the operation once, to the result of the PHI.
225     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
226
227     Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
228                           ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
229     
230     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
231                               bool isSub, Instruction &I);
232     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
233                                  bool Inside, Instruction &IB);
234     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
235   };
236
237   RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
238 }
239
240 // getComplexity:  Assign a complexity or rank value to LLVM Values...
241 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
242 static unsigned getComplexity(Value *V) {
243   if (isa<Instruction>(V)) {
244     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
245       return 3;
246     return 4;
247   }
248   if (isa<Argument>(V)) return 3;
249   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
250 }
251
252 // isOnlyUse - Return true if this instruction will be deleted if we stop using
253 // it.
254 static bool isOnlyUse(Value *V) {
255   return V->hasOneUse() || isa<Constant>(V);
256 }
257
258 // getPromotedType - Return the specified type promoted as it would be to pass
259 // though a va_arg area...
260 static const Type *getPromotedType(const Type *Ty) {
261   switch (Ty->getTypeID()) {
262   case Type::SByteTyID:
263   case Type::ShortTyID:  return Type::IntTy;
264   case Type::UByteTyID:
265   case Type::UShortTyID: return Type::UIntTy;
266   case Type::FloatTyID:  return Type::DoubleTy;
267   default:               return Ty;
268   }
269 }
270
271 /// isCast - If the specified operand is a CastInst or a constant expr cast,
272 /// return the operand value, otherwise return null.
273 static Value *isCast(Value *V) {
274   if (CastInst *I = dyn_cast<CastInst>(V))
275     return I->getOperand(0);
276   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
277     if (CE->getOpcode() == Instruction::Cast)
278       return CE->getOperand(0);
279   return 0;
280 }
281
282 // SimplifyCommutative - This performs a few simplifications for commutative
283 // operators:
284 //
285 //  1. Order operands such that they are listed from right (least complex) to
286 //     left (most complex).  This puts constants before unary operators before
287 //     binary operators.
288 //
289 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
290 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
291 //
292 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
293   bool Changed = false;
294   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
295     Changed = !I.swapOperands();
296
297   if (!I.isAssociative()) return Changed;
298   Instruction::BinaryOps Opcode = I.getOpcode();
299   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
300     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
301       if (isa<Constant>(I.getOperand(1))) {
302         Constant *Folded = ConstantExpr::get(I.getOpcode(),
303                                              cast<Constant>(I.getOperand(1)),
304                                              cast<Constant>(Op->getOperand(1)));
305         I.setOperand(0, Op->getOperand(0));
306         I.setOperand(1, Folded);
307         return true;
308       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
309         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
310             isOnlyUse(Op) && isOnlyUse(Op1)) {
311           Constant *C1 = cast<Constant>(Op->getOperand(1));
312           Constant *C2 = cast<Constant>(Op1->getOperand(1));
313
314           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
315           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
316           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
317                                                     Op1->getOperand(0),
318                                                     Op1->getName(), &I);
319           WorkList.push_back(New);
320           I.setOperand(0, New);
321           I.setOperand(1, Folded);
322           return true;
323         }
324     }
325   return Changed;
326 }
327
328 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
329 // if the LHS is a constant zero (which is the 'negate' form).
330 //
331 static inline Value *dyn_castNegVal(Value *V) {
332   if (BinaryOperator::isNeg(V))
333     return BinaryOperator::getNegArgument(V);
334
335   // Constants can be considered to be negated values if they can be folded.
336   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
337     return ConstantExpr::getNeg(C);
338   return 0;
339 }
340
341 static inline Value *dyn_castNotVal(Value *V) {
342   if (BinaryOperator::isNot(V))
343     return BinaryOperator::getNotArgument(V);
344
345   // Constants can be considered to be not'ed values...
346   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
347     return ConstantExpr::getNot(C);
348   return 0;
349 }
350
351 // dyn_castFoldableMul - If this value is a multiply that can be folded into
352 // other computations (because it has a constant operand), return the
353 // non-constant operand of the multiply, and set CST to point to the multiplier.
354 // Otherwise, return null.
355 //
356 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
357   if (V->hasOneUse() && V->getType()->isInteger())
358     if (Instruction *I = dyn_cast<Instruction>(V)) {
359       if (I->getOpcode() == Instruction::Mul)
360         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
361           return I->getOperand(0);
362       if (I->getOpcode() == Instruction::Shl)
363         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
364           // The multiplier is really 1 << CST.
365           Constant *One = ConstantInt::get(V->getType(), 1);
366           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
367           return I->getOperand(0);
368         }
369     }
370   return 0;
371 }
372
373 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
374 /// expression, return it.
375 static User *dyn_castGetElementPtr(Value *V) {
376   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
377   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
378     if (CE->getOpcode() == Instruction::GetElementPtr)
379       return cast<User>(V);
380   return false;
381 }
382
383 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
384 static ConstantInt *AddOne(ConstantInt *C) {
385   return cast<ConstantInt>(ConstantExpr::getAdd(C,
386                                          ConstantInt::get(C->getType(), 1)));
387 }
388 static ConstantInt *SubOne(ConstantInt *C) {
389   return cast<ConstantInt>(ConstantExpr::getSub(C,
390                                          ConstantInt::get(C->getType(), 1)));
391 }
392
393 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
394 /// this predicate to simplify operations downstream.  V and Mask are known to
395 /// be the same type.
396 static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask, 
397                               unsigned Depth = 0) {
398   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
399   // we cannot optimize based on the assumption that it is zero without changing
400   // to to an explicit zero.  If we don't change it to zero, other code could
401   // optimized based on the contradictory assumption that it is non-zero.
402   // Because instcombine aggressively folds operations with undef args anyway,
403   // this won't lose us code quality.
404   if (Mask->isNullValue())
405     return true;
406   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
407     return ConstantExpr::getAnd(CI, Mask)->isNullValue();
408
409   if (Depth == 6) return false;  // Limit search depth.
410   
411   if (Instruction *I = dyn_cast<Instruction>(V)) {
412     switch (I->getOpcode()) {
413     case Instruction::And:
414       // (X & C1) & C2 == 0   iff   C1 & C2 == 0.
415       if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1))) {
416         ConstantIntegral *C1C2 = 
417           cast<ConstantIntegral>(ConstantExpr::getAnd(CI, Mask));
418         if (MaskedValueIsZero(I->getOperand(0), C1C2, Depth+1))
419           return true;
420       }
421       // If either the LHS or the RHS are MaskedValueIsZero, the result is zero.
422       return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) ||
423              MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
424     case Instruction::Or:
425     case Instruction::Xor:
426       // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
427       return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) &&
428              MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
429     case Instruction::Select:
430       // If the T and F values are MaskedValueIsZero, the result is also zero.
431       return MaskedValueIsZero(I->getOperand(2), Mask, Depth+1) &&
432              MaskedValueIsZero(I->getOperand(1), Mask, Depth+1);
433     case Instruction::Cast: {
434       const Type *SrcTy = I->getOperand(0)->getType();
435       if (SrcTy == Type::BoolTy)
436         return (Mask->getRawValue() & 1) == 0;
437       
438       if (SrcTy->isInteger()) {
439         // (cast <ty> X to int) & C2 == 0  iff <ty> could not have contained C2.
440         if (SrcTy->isUnsigned() &&                      // Only handle zero ext.
441             ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
442           return true;
443         
444         // If this is a noop cast, recurse.
445         if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
446             SrcTy->getSignedVersion() == I->getType()) {
447           Constant *NewMask =
448           ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
449           return MaskedValueIsZero(I->getOperand(0),
450                                    cast<ConstantIntegral>(NewMask), Depth+1);
451         }
452       }
453       break;
454     }
455     case Instruction::Shl:
456       // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
457       if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
458         return MaskedValueIsZero(I->getOperand(0),
459                     cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)), 
460                                  Depth+1);
461       break;
462     case Instruction::Shr:
463       // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
464       if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
465         if (I->getType()->isUnsigned()) {
466           Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
467           C1 = ConstantExpr::getShr(C1, SA);
468           C1 = ConstantExpr::getAnd(C1, Mask);
469           if (C1->isNullValue())
470             return true;
471         }
472       break;
473     }
474   }
475   
476   return false;
477 }
478
479 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
480 // true when both operands are equal...
481 //
482 static bool isTrueWhenEqual(Instruction &I) {
483   return I.getOpcode() == Instruction::SetEQ ||
484          I.getOpcode() == Instruction::SetGE ||
485          I.getOpcode() == Instruction::SetLE;
486 }
487
488 /// AssociativeOpt - Perform an optimization on an associative operator.  This
489 /// function is designed to check a chain of associative operators for a
490 /// potential to apply a certain optimization.  Since the optimization may be
491 /// applicable if the expression was reassociated, this checks the chain, then
492 /// reassociates the expression as necessary to expose the optimization
493 /// opportunity.  This makes use of a special Functor, which must define
494 /// 'shouldApply' and 'apply' methods.
495 ///
496 template<typename Functor>
497 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
498   unsigned Opcode = Root.getOpcode();
499   Value *LHS = Root.getOperand(0);
500
501   // Quick check, see if the immediate LHS matches...
502   if (F.shouldApply(LHS))
503     return F.apply(Root);
504
505   // Otherwise, if the LHS is not of the same opcode as the root, return.
506   Instruction *LHSI = dyn_cast<Instruction>(LHS);
507   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
508     // Should we apply this transform to the RHS?
509     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
510
511     // If not to the RHS, check to see if we should apply to the LHS...
512     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
513       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
514       ShouldApply = true;
515     }
516
517     // If the functor wants to apply the optimization to the RHS of LHSI,
518     // reassociate the expression from ((? op A) op B) to (? op (A op B))
519     if (ShouldApply) {
520       BasicBlock *BB = Root.getParent();
521
522       // Now all of the instructions are in the current basic block, go ahead
523       // and perform the reassociation.
524       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
525
526       // First move the selected RHS to the LHS of the root...
527       Root.setOperand(0, LHSI->getOperand(1));
528
529       // Make what used to be the LHS of the root be the user of the root...
530       Value *ExtraOperand = TmpLHSI->getOperand(1);
531       if (&Root == TmpLHSI) {
532         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
533         return 0;
534       }
535       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
536       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
537       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
538       BasicBlock::iterator ARI = &Root; ++ARI;
539       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
540       ARI = Root;
541
542       // Now propagate the ExtraOperand down the chain of instructions until we
543       // get to LHSI.
544       while (TmpLHSI != LHSI) {
545         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
546         // Move the instruction to immediately before the chain we are
547         // constructing to avoid breaking dominance properties.
548         NextLHSI->getParent()->getInstList().remove(NextLHSI);
549         BB->getInstList().insert(ARI, NextLHSI);
550         ARI = NextLHSI;
551
552         Value *NextOp = NextLHSI->getOperand(1);
553         NextLHSI->setOperand(1, ExtraOperand);
554         TmpLHSI = NextLHSI;
555         ExtraOperand = NextOp;
556       }
557
558       // Now that the instructions are reassociated, have the functor perform
559       // the transformation...
560       return F.apply(Root);
561     }
562
563     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
564   }
565   return 0;
566 }
567
568
569 // AddRHS - Implements: X + X --> X << 1
570 struct AddRHS {
571   Value *RHS;
572   AddRHS(Value *rhs) : RHS(rhs) {}
573   bool shouldApply(Value *LHS) const { return LHS == RHS; }
574   Instruction *apply(BinaryOperator &Add) const {
575     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
576                          ConstantInt::get(Type::UByteTy, 1));
577   }
578 };
579
580 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
581 //                 iff C1&C2 == 0
582 struct AddMaskingAnd {
583   Constant *C2;
584   AddMaskingAnd(Constant *c) : C2(c) {}
585   bool shouldApply(Value *LHS) const {
586     ConstantInt *C1;
587     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
588            ConstantExpr::getAnd(C1, C2)->isNullValue();
589   }
590   Instruction *apply(BinaryOperator &Add) const {
591     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
592   }
593 };
594
595 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
596                                              InstCombiner *IC) {
597   if (isa<CastInst>(I)) {
598     if (Constant *SOC = dyn_cast<Constant>(SO))
599       return ConstantExpr::getCast(SOC, I.getType());
600
601     return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
602                                                 SO->getName() + ".cast"), I);
603   }
604
605   // Figure out if the constant is the left or the right argument.
606   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
607   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
608
609   if (Constant *SOC = dyn_cast<Constant>(SO)) {
610     if (ConstIsRHS)
611       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
612     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
613   }
614
615   Value *Op0 = SO, *Op1 = ConstOperand;
616   if (!ConstIsRHS)
617     std::swap(Op0, Op1);
618   Instruction *New;
619   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
620     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
621   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
622     New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
623   else {
624     assert(0 && "Unknown binary instruction type!");
625     abort();
626   }
627   return IC->InsertNewInstBefore(New, I);
628 }
629
630 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
631 // constant as the other operand, try to fold the binary operator into the
632 // select arguments.  This also works for Cast instructions, which obviously do
633 // not have a second operand.
634 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
635                                      InstCombiner *IC) {
636   // Don't modify shared select instructions
637   if (!SI->hasOneUse()) return 0;
638   Value *TV = SI->getOperand(1);
639   Value *FV = SI->getOperand(2);
640
641   if (isa<Constant>(TV) || isa<Constant>(FV)) {
642     // Bool selects with constant operands can be folded to logical ops.
643     if (SI->getType() == Type::BoolTy) return 0;
644
645     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
646     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
647
648     return new SelectInst(SI->getCondition(), SelectTrueVal,
649                           SelectFalseVal);
650   }
651   return 0;
652 }
653
654
655 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
656 /// node as operand #0, see if we can fold the instruction into the PHI (which
657 /// is only possible if all operands to the PHI are constants).
658 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
659   PHINode *PN = cast<PHINode>(I.getOperand(0));
660   unsigned NumPHIValues = PN->getNumIncomingValues();
661   if (!PN->hasOneUse() || NumPHIValues == 0 ||
662       !isa<Constant>(PN->getIncomingValue(0))) return 0;
663
664   // Check to see if all of the operands of the PHI are constants.  If not, we
665   // cannot do the transformation.
666   for (unsigned i = 1; i != NumPHIValues; ++i)
667     if (!isa<Constant>(PN->getIncomingValue(i)))
668       return 0;
669
670   // Okay, we can do the transformation: create the new PHI node.
671   PHINode *NewPN = new PHINode(I.getType(), I.getName());
672   I.setName("");
673   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
674   InsertNewInstBefore(NewPN, *PN);
675
676   // Next, add all of the operands to the PHI.
677   if (I.getNumOperands() == 2) {
678     Constant *C = cast<Constant>(I.getOperand(1));
679     for (unsigned i = 0; i != NumPHIValues; ++i) {
680       Constant *InV = cast<Constant>(PN->getIncomingValue(i));
681       NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
682                          PN->getIncomingBlock(i));
683     }
684   } else {
685     assert(isa<CastInst>(I) && "Unary op should be a cast!");
686     const Type *RetTy = I.getType();
687     for (unsigned i = 0; i != NumPHIValues; ++i) {
688       Constant *InV = cast<Constant>(PN->getIncomingValue(i));
689       NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
690                          PN->getIncomingBlock(i));
691     }
692   }
693   return ReplaceInstUsesWith(I, NewPN);
694 }
695
696 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
697   bool Changed = SimplifyCommutative(I);
698   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
699
700   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
701     // X + undef -> undef
702     if (isa<UndefValue>(RHS))
703       return ReplaceInstUsesWith(I, RHS);
704
705     // X + 0 --> X
706     if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
707       if (RHSC->isNullValue())
708         return ReplaceInstUsesWith(I, LHS);
709     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
710       if (CFP->isExactlyValue(-0.0))
711         return ReplaceInstUsesWith(I, LHS);
712     }
713
714     // X + (signbit) --> X ^ signbit
715     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
716       unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
717       uint64_t Val = CI->getRawValue() & (~0ULL >> (64- NumBits));
718       if (Val == (1ULL << (NumBits-1)))
719         return BinaryOperator::createXor(LHS, RHS);
720     }
721
722     if (isa<PHINode>(LHS))
723       if (Instruction *NV = FoldOpIntoPhi(I))
724         return NV;
725     
726     ConstantInt *XorRHS = 0;
727     Value *XorLHS = 0;
728     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
729       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
730       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
731       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
732       
733       uint64_t C0080Val = 1ULL << 31;
734       int64_t CFF80Val = -C0080Val;
735       unsigned Size = 32;
736       do {
737         if (TySizeBits > Size) {
738           bool Found = false;
739           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
740           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
741           if (RHSSExt == CFF80Val) {
742             if (XorRHS->getZExtValue() == C0080Val)
743               Found = true;
744           } else if (RHSZExt == C0080Val) {
745             if (XorRHS->getSExtValue() == CFF80Val)
746               Found = true;
747           }
748           if (Found) {
749             // This is a sign extend if the top bits are known zero.
750             Constant *Mask = ConstantInt::getAllOnesValue(XorLHS->getType());
751             Mask = ConstantExpr::getShl(Mask, 
752                          ConstantInt::get(Type::UByteTy, 64-(TySizeBits-Size)));
753             if (!MaskedValueIsZero(XorLHS, cast<ConstantInt>(Mask)))
754               Size = 0;  // Not a sign ext, but can't be any others either.
755             goto FoundSExt;
756           }
757         }
758         Size >>= 1;
759         C0080Val >>= Size;
760         CFF80Val >>= Size;
761       } while (Size >= 8);
762       
763 FoundSExt:
764       const Type *MiddleType = 0;
765       switch (Size) {
766       default: break;
767       case 32: MiddleType = Type::IntTy; break;
768       case 16: MiddleType = Type::ShortTy; break;
769       case 8:  MiddleType = Type::SByteTy; break;
770       }
771       if (MiddleType) {
772         Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
773         InsertNewInstBefore(NewTrunc, I);
774         return new CastInst(NewTrunc, I.getType());
775       }
776     }
777   }
778
779   // X + X --> X << 1
780   if (I.getType()->isInteger()) {
781     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
782
783     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
784       if (RHSI->getOpcode() == Instruction::Sub)
785         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
786           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
787     }
788     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
789       if (LHSI->getOpcode() == Instruction::Sub)
790         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
791           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
792     }
793   }
794
795   // -A + B  -->  B - A
796   if (Value *V = dyn_castNegVal(LHS))
797     return BinaryOperator::createSub(RHS, V);
798
799   // A + -B  -->  A - B
800   if (!isa<Constant>(RHS))
801     if (Value *V = dyn_castNegVal(RHS))
802       return BinaryOperator::createSub(LHS, V);
803
804
805   ConstantInt *C2;
806   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
807     if (X == RHS)   // X*C + X --> X * (C+1)
808       return BinaryOperator::createMul(RHS, AddOne(C2));
809
810     // X*C1 + X*C2 --> X * (C1+C2)
811     ConstantInt *C1;
812     if (X == dyn_castFoldableMul(RHS, C1))
813       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
814   }
815
816   // X + X*C --> X * (C+1)
817   if (dyn_castFoldableMul(RHS, C2) == LHS)
818     return BinaryOperator::createMul(LHS, AddOne(C2));
819
820
821   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
822   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
823     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
824
825   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
826     Value *X = 0;
827     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
828       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
829       return BinaryOperator::createSub(C, X);
830     }
831
832     // (X & FF00) + xx00  -> (X+xx00) & FF00
833     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
834       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
835       if (Anded == CRHS) {
836         // See if all bits from the first bit set in the Add RHS up are included
837         // in the mask.  First, get the rightmost bit.
838         uint64_t AddRHSV = CRHS->getRawValue();
839
840         // Form a mask of all bits from the lowest bit added through the top.
841         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
842         AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
843
844         // See if the and mask includes all of these bits.
845         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
846
847         if (AddRHSHighBits == AddRHSHighBitsAnd) {
848           // Okay, the xform is safe.  Insert the new add pronto.
849           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
850                                                             LHS->getName()), I);
851           return BinaryOperator::createAnd(NewAdd, C2);
852         }
853       }
854     }
855
856     // Try to fold constant add into select arguments.
857     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
858       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
859         return R;
860   }
861
862   return Changed ? &I : 0;
863 }
864
865 // isSignBit - Return true if the value represented by the constant only has the
866 // highest order bit set.
867 static bool isSignBit(ConstantInt *CI) {
868   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
869   return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
870 }
871
872 /// RemoveNoopCast - Strip off nonconverting casts from the value.
873 ///
874 static Value *RemoveNoopCast(Value *V) {
875   if (CastInst *CI = dyn_cast<CastInst>(V)) {
876     const Type *CTy = CI->getType();
877     const Type *OpTy = CI->getOperand(0)->getType();
878     if (CTy->isInteger() && OpTy->isInteger()) {
879       if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
880         return RemoveNoopCast(CI->getOperand(0));
881     } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
882       return RemoveNoopCast(CI->getOperand(0));
883   }
884   return V;
885 }
886
887 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
888   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
889
890   if (Op0 == Op1)         // sub X, X  -> 0
891     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
892
893   // If this is a 'B = x-(-A)', change to B = x+A...
894   if (Value *V = dyn_castNegVal(Op1))
895     return BinaryOperator::createAdd(Op0, V);
896
897   if (isa<UndefValue>(Op0))
898     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
899   if (isa<UndefValue>(Op1))
900     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
901
902   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
903     // Replace (-1 - A) with (~A)...
904     if (C->isAllOnesValue())
905       return BinaryOperator::createNot(Op1);
906
907     // C - ~X == X + (1+C)
908     Value *X = 0;
909     if (match(Op1, m_Not(m_Value(X))))
910       return BinaryOperator::createAdd(X,
911                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
912     // -((uint)X >> 31) -> ((int)X >> 31)
913     // -((int)X >> 31) -> ((uint)X >> 31)
914     if (C->isNullValue()) {
915       Value *NoopCastedRHS = RemoveNoopCast(Op1);
916       if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
917         if (SI->getOpcode() == Instruction::Shr)
918           if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
919             const Type *NewTy;
920             if (SI->getType()->isSigned())
921               NewTy = SI->getType()->getUnsignedVersion();
922             else
923               NewTy = SI->getType()->getSignedVersion();
924             // Check to see if we are shifting out everything but the sign bit.
925             if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
926               // Ok, the transformation is safe.  Insert a cast of the incoming
927               // value, then the new shift, then the new cast.
928               Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
929                                                  SI->getOperand(0)->getName());
930               Value *InV = InsertNewInstBefore(FirstCast, I);
931               Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
932                                                     CU, SI->getName());
933               if (NewShift->getType() == I.getType())
934                 return NewShift;
935               else {
936                 InV = InsertNewInstBefore(NewShift, I);
937                 return new CastInst(NewShift, I.getType());
938               }
939             }
940           }
941     }
942
943     // Try to fold constant sub into select arguments.
944     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
945       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
946         return R;
947
948     if (isa<PHINode>(Op0))
949       if (Instruction *NV = FoldOpIntoPhi(I))
950         return NV;
951   }
952
953   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
954     if (Op1I->getOpcode() == Instruction::Add &&
955         !Op0->getType()->isFloatingPoint()) {
956       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
957         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
958       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
959         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
960       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
961         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
962           // C1-(X+C2) --> (C1-C2)-X
963           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
964                                            Op1I->getOperand(0));
965       }
966     }
967
968     if (Op1I->hasOneUse()) {
969       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
970       // is not used by anyone else...
971       //
972       if (Op1I->getOpcode() == Instruction::Sub &&
973           !Op1I->getType()->isFloatingPoint()) {
974         // Swap the two operands of the subexpr...
975         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
976         Op1I->setOperand(0, IIOp1);
977         Op1I->setOperand(1, IIOp0);
978
979         // Create the new top level add instruction...
980         return BinaryOperator::createAdd(Op0, Op1);
981       }
982
983       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
984       //
985       if (Op1I->getOpcode() == Instruction::And &&
986           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
987         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
988
989         Value *NewNot =
990           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
991         return BinaryOperator::createAnd(Op0, NewNot);
992       }
993
994       // -(X sdiv C)  -> (X sdiv -C)
995       if (Op1I->getOpcode() == Instruction::Div)
996         if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
997           if (CSI->isNullValue())
998             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
999               return BinaryOperator::createDiv(Op1I->getOperand(0),
1000                                                ConstantExpr::getNeg(DivRHS));
1001
1002       // X - X*C --> X * (1-C)
1003       ConstantInt *C2 = 0;
1004       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
1005         Constant *CP1 =
1006           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
1007         return BinaryOperator::createMul(Op0, CP1);
1008       }
1009     }
1010   }
1011
1012   if (!Op0->getType()->isFloatingPoint())
1013     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1014       if (Op0I->getOpcode() == Instruction::Add) {
1015         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
1016           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1017         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
1018           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1019       } else if (Op0I->getOpcode() == Instruction::Sub) {
1020         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
1021           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
1022       }
1023
1024   ConstantInt *C1;
1025   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1026     if (X == Op1) { // X*C - X --> X * (C-1)
1027       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1028       return BinaryOperator::createMul(Op1, CP1);
1029     }
1030
1031     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
1032     if (X == dyn_castFoldableMul(Op1, C2))
1033       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1034   }
1035   return 0;
1036 }
1037
1038 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1039 /// really just returns true if the most significant (sign) bit is set.
1040 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1041   if (RHS->getType()->isSigned()) {
1042     // True if source is LHS < 0 or LHS <= -1
1043     return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1044            Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1045   } else {
1046     ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1047     // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1048     // the size of the integer type.
1049     if (Opcode == Instruction::SetGE)
1050       return RHSC->getValue() ==
1051         1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
1052     if (Opcode == Instruction::SetGT)
1053       return RHSC->getValue() ==
1054         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
1055   }
1056   return false;
1057 }
1058
1059 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
1060   bool Changed = SimplifyCommutative(I);
1061   Value *Op0 = I.getOperand(0);
1062
1063   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
1064     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1065
1066   // Simplify mul instructions with a constant RHS...
1067   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1068     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1069
1070       // ((X << C1)*C2) == (X * (C2 << C1))
1071       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1072         if (SI->getOpcode() == Instruction::Shl)
1073           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
1074             return BinaryOperator::createMul(SI->getOperand(0),
1075                                              ConstantExpr::getShl(CI, ShOp));
1076
1077       if (CI->isNullValue())
1078         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
1079       if (CI->equalsInt(1))                  // X * 1  == X
1080         return ReplaceInstUsesWith(I, Op0);
1081       if (CI->isAllOnesValue())              // X * -1 == 0 - X
1082         return BinaryOperator::createNeg(Op0, I.getName());
1083
1084       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
1085       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
1086         uint64_t C = Log2_64(Val);
1087         return new ShiftInst(Instruction::Shl, Op0,
1088                              ConstantUInt::get(Type::UByteTy, C));
1089       }
1090     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
1091       if (Op1F->isNullValue())
1092         return ReplaceInstUsesWith(I, Op1);
1093
1094       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
1095       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1096       if (Op1F->getValue() == 1.0)
1097         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
1098     }
1099
1100     // Try to fold constant mul into select arguments.
1101     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1102       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1103         return R;
1104
1105     if (isa<PHINode>(Op0))
1106       if (Instruction *NV = FoldOpIntoPhi(I))
1107         return NV;
1108   }
1109
1110   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
1111     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
1112       return BinaryOperator::createMul(Op0v, Op1v);
1113
1114   // If one of the operands of the multiply is a cast from a boolean value, then
1115   // we know the bool is either zero or one, so this is a 'masking' multiply.
1116   // See if we can simplify things based on how the boolean was originally
1117   // formed.
1118   CastInst *BoolCast = 0;
1119   if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1120     if (CI->getOperand(0)->getType() == Type::BoolTy)
1121       BoolCast = CI;
1122   if (!BoolCast)
1123     if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1124       if (CI->getOperand(0)->getType() == Type::BoolTy)
1125         BoolCast = CI;
1126   if (BoolCast) {
1127     if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1128       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1129       const Type *SCOpTy = SCIOp0->getType();
1130
1131       // If the setcc is true iff the sign bit of X is set, then convert this
1132       // multiply into a shift/and combination.
1133       if (isa<ConstantInt>(SCIOp1) &&
1134           isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
1135         // Shift the X value right to turn it into "all signbits".
1136         Constant *Amt = ConstantUInt::get(Type::UByteTy,
1137                                           SCOpTy->getPrimitiveSizeInBits()-1);
1138         if (SCIOp0->getType()->isUnsigned()) {
1139           const Type *NewTy = SCIOp0->getType()->getSignedVersion();
1140           SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1141                                                     SCIOp0->getName()), I);
1142         }
1143
1144         Value *V =
1145           InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1146                                             BoolCast->getOperand(0)->getName()+
1147                                             ".mask"), I);
1148
1149         // If the multiply type is not the same as the source type, sign extend
1150         // or truncate to the multiply type.
1151         if (I.getType() != V->getType())
1152           V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
1153
1154         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
1155         return BinaryOperator::createAnd(V, OtherOp);
1156       }
1157     }
1158   }
1159
1160   return Changed ? &I : 0;
1161 }
1162
1163 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
1164   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1165
1166   if (isa<UndefValue>(Op0))              // undef / X -> 0
1167     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1168   if (isa<UndefValue>(Op1))
1169     return ReplaceInstUsesWith(I, Op1);  // X / undef -> undef
1170
1171   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1172     // div X, 1 == X
1173     if (RHS->equalsInt(1))
1174       return ReplaceInstUsesWith(I, Op0);
1175
1176     // div X, -1 == -X
1177     if (RHS->isAllOnesValue())
1178       return BinaryOperator::createNeg(Op0);
1179
1180     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1181       if (LHS->getOpcode() == Instruction::Div)
1182         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
1183           // (X / C1) / C2  -> X / (C1*C2)
1184           return BinaryOperator::createDiv(LHS->getOperand(0),
1185                                            ConstantExpr::getMul(RHS, LHSRHS));
1186         }
1187
1188     // Check to see if this is an unsigned division with an exact power of 2,
1189     // if so, convert to a right shift.
1190     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1191       if (uint64_t Val = C->getValue())    // Don't break X / 0
1192         if (isPowerOf2_64(Val)) {
1193           uint64_t C = Log2_64(Val);
1194           return new ShiftInst(Instruction::Shr, Op0,
1195                                ConstantUInt::get(Type::UByteTy, C));
1196         }
1197
1198     // -X/C -> X/-C
1199     if (RHS->getType()->isSigned())
1200       if (Value *LHSNeg = dyn_castNegVal(Op0))
1201         return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1202
1203     if (!RHS->isNullValue()) {
1204       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1205         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1206           return R;
1207       if (isa<PHINode>(Op0))
1208         if (Instruction *NV = FoldOpIntoPhi(I))
1209           return NV;
1210     }
1211   }
1212
1213   // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1214   // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1215   if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1216     if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1217       if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1218         if (STO->getValue() == 0) { // Couldn't be this argument.
1219           I.setOperand(1, SFO);
1220           return &I;
1221         } else if (SFO->getValue() == 0) {
1222           I.setOperand(1, STO);
1223           return &I;
1224         }
1225
1226         uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
1227         if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1228           unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
1229           Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1230           Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1231                                            TC, SI->getName()+".t");
1232           TSI = InsertNewInstBefore(TSI, I);
1233
1234           Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1235           Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1236                                            FC, SI->getName()+".f");
1237           FSI = InsertNewInstBefore(FSI, I);
1238           return new SelectInst(SI->getOperand(0), TSI, FSI);
1239         }
1240       }
1241
1242   // 0 / X == 0, we don't need to preserve faults!
1243   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1244     if (LHS->equalsInt(0))
1245       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1246
1247   if (I.getType()->isSigned()) {
1248     // If the top bits of both operands are zero (i.e. we can prove they are
1249     // unsigned inputs), turn this into a udiv.
1250     ConstantIntegral *MaskV = ConstantSInt::getMinValue(I.getType());
1251     if (MaskedValueIsZero(Op1, MaskV) && MaskedValueIsZero(Op0, MaskV)) {
1252       const Type *NTy = Op0->getType()->getUnsignedVersion();
1253       Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1254       InsertNewInstBefore(LHS, I);
1255       Value *RHS;
1256       if (Constant *R = dyn_cast<Constant>(Op1))
1257         RHS = ConstantExpr::getCast(R, NTy);
1258       else
1259         RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1260       Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1261       InsertNewInstBefore(Div, I);
1262       return new CastInst(Div, I.getType());
1263     }      
1264   } else {
1265     // Known to be an unsigned division.
1266     if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1267       // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1268       if (RHSI->getOpcode() == Instruction::Shl &&
1269           isa<ConstantUInt>(RHSI->getOperand(0))) {
1270         unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1271         if (isPowerOf2_64(C1)) {
1272           unsigned C2 = Log2_64(C1);
1273           Value *Add = RHSI->getOperand(1);
1274           if (C2) {
1275             Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1276             Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1277                                                                 "tmp"), I);
1278           }
1279           return new ShiftInst(Instruction::Shr, Op0, Add);
1280         }
1281       }
1282     }
1283   }
1284   
1285   return 0;
1286 }
1287
1288
1289 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
1290   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1291   if (I.getType()->isSigned()) {
1292     if (Value *RHSNeg = dyn_castNegVal(Op1))
1293       if (!isa<ConstantSInt>(RHSNeg) ||
1294           cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
1295         // X % -Y -> X % Y
1296         AddUsesToWorkList(I);
1297         I.setOperand(1, RHSNeg);
1298         return &I;
1299       }
1300    
1301     // If the top bits of both operands are zero (i.e. we can prove they are
1302     // unsigned inputs), turn this into a urem.
1303     ConstantIntegral *MaskV = ConstantSInt::getMinValue(I.getType());
1304     if (MaskedValueIsZero(Op1, MaskV) && MaskedValueIsZero(Op0, MaskV)) {
1305       const Type *NTy = Op0->getType()->getUnsignedVersion();
1306       Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1307       InsertNewInstBefore(LHS, I);
1308       Value *RHS;
1309       if (Constant *R = dyn_cast<Constant>(Op1))
1310         RHS = ConstantExpr::getCast(R, NTy);
1311       else
1312         RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1313       Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1314       InsertNewInstBefore(Rem, I);
1315       return new CastInst(Rem, I.getType());
1316     }
1317   }
1318
1319   if (isa<UndefValue>(Op0))              // undef % X -> 0
1320     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1321   if (isa<UndefValue>(Op1))
1322     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
1323
1324   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1325     if (RHS->equalsInt(1))  // X % 1 == 0
1326       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1327
1328     // Check to see if this is an unsigned remainder with an exact power of 2,
1329     // if so, convert to a bitwise and.
1330     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1331       if (uint64_t Val = C->getValue())    // Don't break X % 0 (divide by zero)
1332         if (!(Val & (Val-1)))              // Power of 2
1333           return BinaryOperator::createAnd(Op0,
1334                                          ConstantUInt::get(I.getType(), Val-1));
1335
1336     if (!RHS->isNullValue()) {
1337       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1338         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1339           return R;
1340       if (isa<PHINode>(Op0))
1341         if (Instruction *NV = FoldOpIntoPhi(I))
1342           return NV;
1343     }
1344   }
1345
1346   // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1347   // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1348   if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1349     if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1350       if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1351         if (STO->getValue() == 0) { // Couldn't be this argument.
1352           I.setOperand(1, SFO);
1353           return &I;
1354         } else if (SFO->getValue() == 0) {
1355           I.setOperand(1, STO);
1356           return &I;
1357         }
1358
1359         if (!(STO->getValue() & (STO->getValue()-1)) &&
1360             !(SFO->getValue() & (SFO->getValue()-1))) {
1361           Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1362                                          SubOne(STO), SI->getName()+".t"), I);
1363           Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1364                                          SubOne(SFO), SI->getName()+".f"), I);
1365           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1366         }
1367       }
1368
1369   // 0 % X == 0, we don't need to preserve faults!
1370   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1371     if (LHS->equalsInt(0))
1372       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1373
1374   
1375   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1376     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1377     if (I.getType()->isUnsigned() && 
1378         RHSI->getOpcode() == Instruction::Shl &&
1379         isa<ConstantUInt>(RHSI->getOperand(0))) {
1380       unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1381       if (isPowerOf2_64(C1)) {
1382         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1383         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1384                                                                    "tmp"), I);
1385         return BinaryOperator::createAnd(Op0, Add);
1386       }
1387     }
1388   }
1389   
1390   return 0;
1391 }
1392
1393 // isMaxValueMinusOne - return true if this is Max-1
1394 static bool isMaxValueMinusOne(const ConstantInt *C) {
1395   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1396     // Calculate -1 casted to the right type...
1397     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1398     uint64_t Val = ~0ULL;                // All ones
1399     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
1400     return CU->getValue() == Val-1;
1401   }
1402
1403   const ConstantSInt *CS = cast<ConstantSInt>(C);
1404
1405   // Calculate 0111111111..11111
1406   unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1407   int64_t Val = INT64_MAX;             // All ones
1408   Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
1409   return CS->getValue() == Val-1;
1410 }
1411
1412 // isMinValuePlusOne - return true if this is Min+1
1413 static bool isMinValuePlusOne(const ConstantInt *C) {
1414   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1415     return CU->getValue() == 1;
1416
1417   const ConstantSInt *CS = cast<ConstantSInt>(C);
1418
1419   // Calculate 1111111111000000000000
1420   unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1421   int64_t Val = -1;                    // All ones
1422   Val <<= TypeBits-1;                  // Shift over to the right spot
1423   return CS->getValue() == Val+1;
1424 }
1425
1426 // isOneBitSet - Return true if there is exactly one bit set in the specified
1427 // constant.
1428 static bool isOneBitSet(const ConstantInt *CI) {
1429   uint64_t V = CI->getRawValue();
1430   return V && (V & (V-1)) == 0;
1431 }
1432
1433 #if 0   // Currently unused
1434 // isLowOnes - Return true if the constant is of the form 0+1+.
1435 static bool isLowOnes(const ConstantInt *CI) {
1436   uint64_t V = CI->getRawValue();
1437
1438   // There won't be bits set in parts that the type doesn't contain.
1439   V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1440
1441   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
1442   return U && V && (U & V) == 0;
1443 }
1444 #endif
1445
1446 // isHighOnes - Return true if the constant is of the form 1+0+.
1447 // This is the same as lowones(~X).
1448 static bool isHighOnes(const ConstantInt *CI) {
1449   uint64_t V = ~CI->getRawValue();
1450   if (~V == 0) return false;  // 0's does not match "1+"
1451
1452   // There won't be bits set in parts that the type doesn't contain.
1453   V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1454
1455   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
1456   return U && V && (U & V) == 0;
1457 }
1458
1459
1460 /// getSetCondCode - Encode a setcc opcode into a three bit mask.  These bits
1461 /// are carefully arranged to allow folding of expressions such as:
1462 ///
1463 ///      (A < B) | (A > B) --> (A != B)
1464 ///
1465 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1466 /// represents that the comparison is true if A == B, and bit value '1' is true
1467 /// if A < B.
1468 ///
1469 static unsigned getSetCondCode(const SetCondInst *SCI) {
1470   switch (SCI->getOpcode()) {
1471     // False -> 0
1472   case Instruction::SetGT: return 1;
1473   case Instruction::SetEQ: return 2;
1474   case Instruction::SetGE: return 3;
1475   case Instruction::SetLT: return 4;
1476   case Instruction::SetNE: return 5;
1477   case Instruction::SetLE: return 6;
1478     // True -> 7
1479   default:
1480     assert(0 && "Invalid SetCC opcode!");
1481     return 0;
1482   }
1483 }
1484
1485 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
1486 /// opcode and two operands into either a constant true or false, or a brand new
1487 /// SetCC instruction.
1488 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1489   switch (Opcode) {
1490   case 0: return ConstantBool::False;
1491   case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1492   case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1493   case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1494   case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1495   case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1496   case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1497   case 7: return ConstantBool::True;
1498   default: assert(0 && "Illegal SetCCCode!"); return 0;
1499   }
1500 }
1501
1502 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1503 struct FoldSetCCLogical {
1504   InstCombiner &IC;
1505   Value *LHS, *RHS;
1506   FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1507     : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1508   bool shouldApply(Value *V) const {
1509     if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1510       return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1511               SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1512     return false;
1513   }
1514   Instruction *apply(BinaryOperator &Log) const {
1515     SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1516     if (SCI->getOperand(0) != LHS) {
1517       assert(SCI->getOperand(1) == LHS);
1518       SCI->swapOperands();  // Swap the LHS and RHS of the SetCC
1519     }
1520
1521     unsigned LHSCode = getSetCondCode(SCI);
1522     unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1523     unsigned Code;
1524     switch (Log.getOpcode()) {
1525     case Instruction::And: Code = LHSCode & RHSCode; break;
1526     case Instruction::Or:  Code = LHSCode | RHSCode; break;
1527     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
1528     default: assert(0 && "Illegal logical opcode!"); return 0;
1529     }
1530
1531     Value *RV = getSetCCValue(Code, LHS, RHS);
1532     if (Instruction *I = dyn_cast<Instruction>(RV))
1533       return I;
1534     // Otherwise, it's a constant boolean value...
1535     return IC.ReplaceInstUsesWith(Log, RV);
1536   }
1537 };
1538
1539 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
1540 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
1541 // guaranteed to be either a shift instruction or a binary operator.
1542 Instruction *InstCombiner::OptAndOp(Instruction *Op,
1543                                     ConstantIntegral *OpRHS,
1544                                     ConstantIntegral *AndRHS,
1545                                     BinaryOperator &TheAnd) {
1546   Value *X = Op->getOperand(0);
1547   Constant *Together = 0;
1548   if (!isa<ShiftInst>(Op))
1549     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
1550
1551   switch (Op->getOpcode()) {
1552   case Instruction::Xor:
1553     if (Op->hasOneUse()) {
1554       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1555       std::string OpName = Op->getName(); Op->setName("");
1556       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
1557       InsertNewInstBefore(And, TheAnd);
1558       return BinaryOperator::createXor(And, Together);
1559     }
1560     break;
1561   case Instruction::Or:
1562     if (Together == AndRHS) // (X | C) & C --> C
1563       return ReplaceInstUsesWith(TheAnd, AndRHS);
1564
1565     if (Op->hasOneUse() && Together != OpRHS) {
1566       // (X | C1) & C2 --> (X | (C1&C2)) & C2
1567       std::string Op0Name = Op->getName(); Op->setName("");
1568       Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1569       InsertNewInstBefore(Or, TheAnd);
1570       return BinaryOperator::createAnd(Or, AndRHS);
1571     }
1572     break;
1573   case Instruction::Add:
1574     if (Op->hasOneUse()) {
1575       // Adding a one to a single bit bit-field should be turned into an XOR
1576       // of the bit.  First thing to check is to see if this AND is with a
1577       // single bit constant.
1578       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
1579
1580       // Clear bits that are not part of the constant.
1581       AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
1582
1583       // If there is only one bit set...
1584       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
1585         // Ok, at this point, we know that we are masking the result of the
1586         // ADD down to exactly one bit.  If the constant we are adding has
1587         // no bits set below this bit, then we can eliminate the ADD.
1588         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
1589
1590         // Check to see if any bits below the one bit set in AndRHSV are set.
1591         if ((AddRHS & (AndRHSV-1)) == 0) {
1592           // If not, the only thing that can effect the output of the AND is
1593           // the bit specified by AndRHSV.  If that bit is set, the effect of
1594           // the XOR is to toggle the bit.  If it is clear, then the ADD has
1595           // no effect.
1596           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1597             TheAnd.setOperand(0, X);
1598             return &TheAnd;
1599           } else {
1600             std::string Name = Op->getName(); Op->setName("");
1601             // Pull the XOR out of the AND.
1602             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
1603             InsertNewInstBefore(NewAnd, TheAnd);
1604             return BinaryOperator::createXor(NewAnd, AndRHS);
1605           }
1606         }
1607       }
1608     }
1609     break;
1610
1611   case Instruction::Shl: {
1612     // We know that the AND will not produce any of the bits shifted in, so if
1613     // the anded constant includes them, clear them now!
1614     //
1615     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1616     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1617     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1618
1619     if (CI == ShlMask) {   // Masking out bits that the shift already masks
1620       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
1621     } else if (CI != AndRHS) {                  // Reducing bits set in and.
1622       TheAnd.setOperand(1, CI);
1623       return &TheAnd;
1624     }
1625     break;
1626   }
1627   case Instruction::Shr:
1628     // We know that the AND will not produce any of the bits shifted in, so if
1629     // the anded constant includes them, clear them now!  This only applies to
1630     // unsigned shifts, because a signed shr may bring in set bits!
1631     //
1632     if (AndRHS->getType()->isUnsigned()) {
1633       Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1634       Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1635       Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1636
1637       if (CI == ShrMask) {   // Masking out bits that the shift already masks.
1638         return ReplaceInstUsesWith(TheAnd, Op);
1639       } else if (CI != AndRHS) {
1640         TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
1641         return &TheAnd;
1642       }
1643     } else {   // Signed shr.
1644       // See if this is shifting in some sign extension, then masking it out
1645       // with an and.
1646       if (Op->hasOneUse()) {
1647         Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1648         Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1649         Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1650         if (CI == AndRHS) {          // Masking out bits shifted in.
1651           // Make the argument unsigned.
1652           Value *ShVal = Op->getOperand(0);
1653           ShVal = InsertCastBefore(ShVal,
1654                                    ShVal->getType()->getUnsignedVersion(),
1655                                    TheAnd);
1656           ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1657                                                     OpRHS, Op->getName()),
1658                                       TheAnd);
1659           Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1660           ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1661                                                              TheAnd.getName()),
1662                                       TheAnd);
1663           return new CastInst(ShVal, Op->getType());
1664         }
1665       }
1666     }
1667     break;
1668   }
1669   return 0;
1670 }
1671
1672
1673 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1674 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
1675 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi.  IB is the location to
1676 /// insert new instructions.
1677 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1678                                            bool Inside, Instruction &IB) {
1679   assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1680          "Lo is not <= Hi in range emission code!");
1681   if (Inside) {
1682     if (Lo == Hi)  // Trivially false.
1683       return new SetCondInst(Instruction::SetNE, V, V);
1684     if (cast<ConstantIntegral>(Lo)->isMinValue())
1685       return new SetCondInst(Instruction::SetLT, V, Hi);
1686
1687     Constant *AddCST = ConstantExpr::getNeg(Lo);
1688     Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1689     InsertNewInstBefore(Add, IB);
1690     // Convert to unsigned for the comparison.
1691     const Type *UnsType = Add->getType()->getUnsignedVersion();
1692     Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1693     AddCST = ConstantExpr::getAdd(AddCST, Hi);
1694     AddCST = ConstantExpr::getCast(AddCST, UnsType);
1695     return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1696   }
1697
1698   if (Lo == Hi)  // Trivially true.
1699     return new SetCondInst(Instruction::SetEQ, V, V);
1700
1701   Hi = SubOne(cast<ConstantInt>(Hi));
1702   if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1703     return new SetCondInst(Instruction::SetGT, V, Hi);
1704
1705   // Emit X-Lo > Hi-Lo-1
1706   Constant *AddCST = ConstantExpr::getNeg(Lo);
1707   Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1708   InsertNewInstBefore(Add, IB);
1709   // Convert to unsigned for the comparison.
1710   const Type *UnsType = Add->getType()->getUnsignedVersion();
1711   Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1712   AddCST = ConstantExpr::getAdd(AddCST, Hi);
1713   AddCST = ConstantExpr::getCast(AddCST, UnsType);
1714   return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1715 }
1716
1717 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1718 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
1719 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
1720 // not, since all 1s are not contiguous.
1721 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1722   uint64_t V = Val->getRawValue();
1723   if (!isShiftedMask_64(V)) return false;
1724
1725   // look for the first zero bit after the run of ones
1726   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1727   // look for the first non-zero bit
1728   ME = 64-CountLeadingZeros_64(V);
1729   return true;
1730 }
1731
1732
1733
1734 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1735 /// where isSub determines whether the operator is a sub.  If we can fold one of
1736 /// the following xforms:
1737 /// 
1738 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1739 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1740 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1741 ///
1742 /// return (A +/- B).
1743 ///
1744 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1745                                         ConstantIntegral *Mask, bool isSub,
1746                                         Instruction &I) {
1747   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1748   if (!LHSI || LHSI->getNumOperands() != 2 ||
1749       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1750
1751   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1752
1753   switch (LHSI->getOpcode()) {
1754   default: return 0;
1755   case Instruction::And:
1756     if (ConstantExpr::getAnd(N, Mask) == Mask) {
1757       // If the AndRHS is a power of two minus one (0+1+), this is simple.
1758       if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1759         break;
1760
1761       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1762       // part, we don't need any explicit masks to take them out of A.  If that
1763       // is all N is, ignore it.
1764       unsigned MB, ME;
1765       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
1766         Constant *Mask = ConstantInt::getAllOnesValue(RHS->getType());
1767         Mask = ConstantExpr::getUShr(Mask,
1768                                      ConstantInt::get(Type::UByteTy,
1769                                                       (64-MB+1)));
1770         if (MaskedValueIsZero(RHS, cast<ConstantIntegral>(Mask)))
1771           break;
1772       }
1773     }
1774     return 0;
1775   case Instruction::Or:
1776   case Instruction::Xor:
1777     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1778     if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1779         ConstantExpr::getAnd(N, Mask)->isNullValue())
1780       break;
1781     return 0;
1782   }
1783   
1784   Instruction *New;
1785   if (isSub)
1786     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1787   else
1788     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1789   return InsertNewInstBefore(New, I);
1790 }
1791
1792 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1793   bool Changed = SimplifyCommutative(I);
1794   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1795
1796   if (isa<UndefValue>(Op1))                         // X & undef -> 0
1797     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1798
1799   // and X, X = X
1800   if (Op0 == Op1)
1801     return ReplaceInstUsesWith(I, Op1);
1802
1803   if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
1804     // and X, -1 == X
1805     if (AndRHS->isAllOnesValue())
1806       return ReplaceInstUsesWith(I, Op0);
1807     
1808     // and (and X, c1), c2 -> and (x, c1&c2).  Handle this case here, before
1809     // calling MaskedValueIsZero, to avoid inefficient cases where we traipse
1810     // through many levels of ands.
1811     {
1812       Value *X = 0; ConstantInt *C1 = 0;
1813       if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))))
1814         return BinaryOperator::createAnd(X, ConstantExpr::getAnd(C1, AndRHS));
1815     }
1816
1817     if (MaskedValueIsZero(Op0, AndRHS))        // LHS & RHS == 0
1818       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1819
1820     // If the mask is not masking out any bits, there is no reason to do the
1821     // and in the first place.
1822     ConstantIntegral *NotAndRHS =
1823       cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
1824     if (MaskedValueIsZero(Op0, NotAndRHS))
1825       return ReplaceInstUsesWith(I, Op0);
1826
1827     // Optimize a variety of ((val OP C1) & C2) combinations...
1828     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1829       Instruction *Op0I = cast<Instruction>(Op0);
1830       Value *Op0LHS = Op0I->getOperand(0);
1831       Value *Op0RHS = Op0I->getOperand(1);
1832       switch (Op0I->getOpcode()) {
1833       case Instruction::Xor:
1834       case Instruction::Or:
1835         // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1836         // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1837         if (MaskedValueIsZero(Op0LHS, AndRHS))
1838           return BinaryOperator::createAnd(Op0RHS, AndRHS);
1839         if (MaskedValueIsZero(Op0RHS, AndRHS))
1840           return BinaryOperator::createAnd(Op0LHS, AndRHS);
1841
1842         // If the mask is only needed on one incoming arm, push it up.
1843         if (Op0I->hasOneUse()) {
1844           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1845             // Not masking anything out for the LHS, move to RHS.
1846             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1847                                                    Op0RHS->getName()+".masked");
1848             InsertNewInstBefore(NewRHS, I);
1849             return BinaryOperator::create(
1850                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
1851           }
1852           if (!isa<Constant>(NotAndRHS) &&
1853               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1854             // Not masking anything out for the RHS, move to LHS.
1855             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1856                                                    Op0LHS->getName()+".masked");
1857             InsertNewInstBefore(NewLHS, I);
1858             return BinaryOperator::create(
1859                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1860           }
1861         }
1862
1863         break;
1864       case Instruction::And:
1865         // (X & V) & C2 --> 0 iff (V & C2) == 0
1866         if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1867             MaskedValueIsZero(Op0RHS, AndRHS))
1868           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1869         break;
1870       case Instruction::Add:
1871         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1872         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1873         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1874         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1875           return BinaryOperator::createAnd(V, AndRHS);
1876         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1877           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
1878         break;
1879
1880       case Instruction::Sub:
1881         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1882         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1883         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1884         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1885           return BinaryOperator::createAnd(V, AndRHS);
1886         break;
1887       }
1888
1889       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1890         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1891           return Res;
1892     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1893       const Type *SrcTy = CI->getOperand(0)->getType();
1894
1895       // If this is an integer truncation or change from signed-to-unsigned, and
1896       // if the source is an and/or with immediate, transform it.  This
1897       // frequently occurs for bitfield accesses.
1898       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1899         if (SrcTy->getPrimitiveSizeInBits() >= 
1900               I.getType()->getPrimitiveSizeInBits() &&
1901             CastOp->getNumOperands() == 2)
1902           if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
1903             if (CastOp->getOpcode() == Instruction::And) {
1904               // Change: and (cast (and X, C1) to T), C2
1905               // into  : and (cast X to T), trunc(C1)&C2
1906               // This will folds the two ands together, which may allow other
1907               // simplifications.
1908               Instruction *NewCast =
1909                 new CastInst(CastOp->getOperand(0), I.getType(),
1910                              CastOp->getName()+".shrunk");
1911               NewCast = InsertNewInstBefore(NewCast, I);
1912               
1913               Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1914               C3 = ConstantExpr::getAnd(C3, AndRHS);            // trunc(C1)&C2
1915               return BinaryOperator::createAnd(NewCast, C3);
1916             } else if (CastOp->getOpcode() == Instruction::Or) {
1917               // Change: and (cast (or X, C1) to T), C2
1918               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1919               Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1920               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
1921                 return ReplaceInstUsesWith(I, AndRHS);
1922             }
1923       }
1924
1925
1926       // If this is an integer sign or zero extension instruction.
1927       if (SrcTy->isIntegral() &&
1928           SrcTy->getPrimitiveSizeInBits() <
1929           CI->getType()->getPrimitiveSizeInBits()) {
1930
1931         if (SrcTy->isUnsigned()) {
1932           // See if this and is clearing out bits that are known to be zero
1933           // anyway (due to the zero extension).
1934           Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1935           Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1936           Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1937           if (Result == Mask)  // The "and" isn't doing anything, remove it.
1938             return ReplaceInstUsesWith(I, CI);
1939           if (Result != AndRHS) { // Reduce the and RHS constant.
1940             I.setOperand(1, Result);
1941             return &I;
1942           }
1943
1944         } else {
1945           if (CI->hasOneUse() && SrcTy->isInteger()) {
1946             // We can only do this if all of the sign bits brought in are masked
1947             // out.  Compute this by first getting 0000011111, then inverting
1948             // it.
1949             Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1950             Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1951             Mask = ConstantExpr::getNot(Mask);    // 1's in the new bits.
1952             if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1953               // If the and is clearing all of the sign bits, change this to a
1954               // zero extension cast.  To do this, cast the cast input to
1955               // unsigned, then to the requested size.
1956               Value *CastOp = CI->getOperand(0);
1957               Instruction *NC =
1958                 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1959                              CI->getName()+".uns");
1960               NC = InsertNewInstBefore(NC, I);
1961               // Finally, insert a replacement for CI.
1962               NC = new CastInst(NC, CI->getType(), CI->getName());
1963               CI->setName("");
1964               NC = InsertNewInstBefore(NC, I);
1965               WorkList.push_back(CI);  // Delete CI later.
1966               I.setOperand(0, NC);
1967               return &I;               // The AND operand was modified.
1968             }
1969           }
1970         }
1971       }
1972     }
1973
1974     // Try to fold constant and into select arguments.
1975     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1976       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1977         return R;
1978     if (isa<PHINode>(Op0))
1979       if (Instruction *NV = FoldOpIntoPhi(I))
1980         return NV;
1981   }
1982
1983   Value *Op0NotVal = dyn_castNotVal(Op0);
1984   Value *Op1NotVal = dyn_castNotVal(Op1);
1985
1986   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
1987     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1988
1989   // (~A & ~B) == (~(A | B)) - De Morgan's Law
1990   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1991     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1992                                                I.getName()+".demorgan");
1993     InsertNewInstBefore(Or, I);
1994     return BinaryOperator::createNot(Or);
1995   }
1996
1997   if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1998     // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1999     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2000       return R;
2001
2002     Value *LHSVal, *RHSVal;
2003     ConstantInt *LHSCst, *RHSCst;
2004     Instruction::BinaryOps LHSCC, RHSCC;
2005     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2006       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2007         if (LHSVal == RHSVal &&    // Found (X setcc C1) & (X setcc C2)
2008             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2009             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2010             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2011           // Ensure that the larger constant is on the RHS.
2012           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2013           SetCondInst *LHS = cast<SetCondInst>(Op0);
2014           if (cast<ConstantBool>(Cmp)->getValue()) {
2015             std::swap(LHS, RHS);
2016             std::swap(LHSCst, RHSCst);
2017             std::swap(LHSCC, RHSCC);
2018           }
2019
2020           // At this point, we know we have have two setcc instructions
2021           // comparing a value against two constants and and'ing the result
2022           // together.  Because of the above check, we know that we only have
2023           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
2024           // FoldSetCCLogical check above), that the two constants are not
2025           // equal.
2026           assert(LHSCst != RHSCst && "Compares not folded above?");
2027
2028           switch (LHSCC) {
2029           default: assert(0 && "Unknown integer condition code!");
2030           case Instruction::SetEQ:
2031             switch (RHSCC) {
2032             default: assert(0 && "Unknown integer condition code!");
2033             case Instruction::SetEQ:  // (X == 13 & X == 15) -> false
2034             case Instruction::SetGT:  // (X == 13 & X > 15)  -> false
2035               return ReplaceInstUsesWith(I, ConstantBool::False);
2036             case Instruction::SetNE:  // (X == 13 & X != 15) -> X == 13
2037             case Instruction::SetLT:  // (X == 13 & X < 15)  -> X == 13
2038               return ReplaceInstUsesWith(I, LHS);
2039             }
2040           case Instruction::SetNE:
2041             switch (RHSCC) {
2042             default: assert(0 && "Unknown integer condition code!");
2043             case Instruction::SetLT:
2044               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2045                 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2046               break;                        // (X != 13 & X < 15) -> no change
2047             case Instruction::SetEQ:        // (X != 13 & X == 15) -> X == 15
2048             case Instruction::SetGT:        // (X != 13 & X > 15)  -> X > 15
2049               return ReplaceInstUsesWith(I, RHS);
2050             case Instruction::SetNE:
2051               if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2052                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2053                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2054                                                       LHSVal->getName()+".off");
2055                 InsertNewInstBefore(Add, I);
2056                 const Type *UnsType = Add->getType()->getUnsignedVersion();
2057                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2058                 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2059                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2060                 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2061               }
2062               break;                        // (X != 13 & X != 15) -> no change
2063             }
2064             break;
2065           case Instruction::SetLT:
2066             switch (RHSCC) {
2067             default: assert(0 && "Unknown integer condition code!");
2068             case Instruction::SetEQ:  // (X < 13 & X == 15) -> false
2069             case Instruction::SetGT:  // (X < 13 & X > 15)  -> false
2070               return ReplaceInstUsesWith(I, ConstantBool::False);
2071             case Instruction::SetNE:  // (X < 13 & X != 15) -> X < 13
2072             case Instruction::SetLT:  // (X < 13 & X < 15) -> X < 13
2073               return ReplaceInstUsesWith(I, LHS);
2074             }
2075           case Instruction::SetGT:
2076             switch (RHSCC) {
2077             default: assert(0 && "Unknown integer condition code!");
2078             case Instruction::SetEQ:  // (X > 13 & X == 15) -> X > 13
2079               return ReplaceInstUsesWith(I, LHS);
2080             case Instruction::SetGT:  // (X > 13 & X > 15)  -> X > 15
2081               return ReplaceInstUsesWith(I, RHS);
2082             case Instruction::SetNE:
2083               if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2084                 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2085               break;                        // (X > 13 & X != 15) -> no change
2086             case Instruction::SetLT:   // (X > 13 & X < 15) -> (X-14) <u 1
2087               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
2088             }
2089           }
2090         }
2091   }
2092
2093   return Changed ? &I : 0;
2094 }
2095
2096 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2097   bool Changed = SimplifyCommutative(I);
2098   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2099
2100   if (isa<UndefValue>(Op1))
2101     return ReplaceInstUsesWith(I,                         // X | undef -> -1
2102                                ConstantIntegral::getAllOnesValue(I.getType()));
2103
2104   // or X, X = X   or X, 0 == X
2105   if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2106     return ReplaceInstUsesWith(I, Op0);
2107
2108   // or X, -1 == -1
2109   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2110     // If X is known to only contain bits that already exist in RHS, just
2111     // replace this instruction with RHS directly.
2112     if (MaskedValueIsZero(Op0,
2113                           cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
2114       return ReplaceInstUsesWith(I, RHS);
2115
2116     ConstantInt *C1 = 0; Value *X = 0;
2117     // (X & C1) | C2 --> (X | C2) & (C1|C2)
2118     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2119       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2120       Op0->setName("");
2121       InsertNewInstBefore(Or, I);
2122       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2123     }
2124
2125     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2126     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2127       std::string Op0Name = Op0->getName(); Op0->setName("");
2128       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2129       InsertNewInstBefore(Or, I);
2130       return BinaryOperator::createXor(Or,
2131                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
2132     }
2133
2134     // Try to fold constant and into select arguments.
2135     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2136       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2137         return R;
2138     if (isa<PHINode>(Op0))
2139       if (Instruction *NV = FoldOpIntoPhi(I))
2140         return NV;
2141   }
2142
2143   Value *A = 0, *B = 0;
2144   ConstantInt *C1 = 0, *C2 = 0;
2145
2146   if (match(Op0, m_And(m_Value(A), m_Value(B))))
2147     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
2148       return ReplaceInstUsesWith(I, Op1);
2149   if (match(Op1, m_And(m_Value(A), m_Value(B))))
2150     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
2151       return ReplaceInstUsesWith(I, Op0);
2152
2153   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2154   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2155       MaskedValueIsZero(Op1, C1)) {
2156     Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2157     Op0->setName("");
2158     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2159   }
2160
2161   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2162   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2163       MaskedValueIsZero(Op0, C1)) {
2164     Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2165     Op0->setName("");
2166     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2167   }
2168
2169   // (A & C1)|(B & C2)
2170   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2171       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2172
2173     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
2174       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2175
2176
2177     // If we have: ((V + N) & C1) | (V & C2)
2178     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2179     // replace with V+N.
2180     if (C1 == ConstantExpr::getNot(C2)) {
2181       Value *V1 = 0, *V2 = 0;
2182       if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2183           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2184         // Add commutes, try both ways.
2185         if (V1 == B && MaskedValueIsZero(V2, C2))
2186           return ReplaceInstUsesWith(I, A);
2187         if (V2 == B && MaskedValueIsZero(V1, C2))
2188           return ReplaceInstUsesWith(I, A);
2189       }
2190       // Or commutes, try both ways.
2191       if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2192           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2193         // Add commutes, try both ways.
2194         if (V1 == A && MaskedValueIsZero(V2, C1))
2195           return ReplaceInstUsesWith(I, B);
2196         if (V2 == A && MaskedValueIsZero(V1, C1))
2197           return ReplaceInstUsesWith(I, B);
2198       }
2199     }
2200   }
2201
2202   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
2203     if (A == Op1)   // ~A | A == -1
2204       return ReplaceInstUsesWith(I,
2205                                 ConstantIntegral::getAllOnesValue(I.getType()));
2206   } else {
2207     A = 0;
2208   }
2209   // Note, A is still live here!
2210   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
2211     if (Op0 == B)
2212       return ReplaceInstUsesWith(I,
2213                                 ConstantIntegral::getAllOnesValue(I.getType()));
2214
2215     // (~A | ~B) == (~(A & B)) - De Morgan's Law
2216     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2217       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2218                                               I.getName()+".demorgan"), I);
2219       return BinaryOperator::createNot(And);
2220     }
2221   }
2222
2223   // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
2224   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
2225     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2226       return R;
2227
2228     Value *LHSVal, *RHSVal;
2229     ConstantInt *LHSCst, *RHSCst;
2230     Instruction::BinaryOps LHSCC, RHSCC;
2231     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2232       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2233         if (LHSVal == RHSVal &&    // Found (X setcc C1) | (X setcc C2)
2234             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2235             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2236             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2237           // Ensure that the larger constant is on the RHS.
2238           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2239           SetCondInst *LHS = cast<SetCondInst>(Op0);
2240           if (cast<ConstantBool>(Cmp)->getValue()) {
2241             std::swap(LHS, RHS);
2242             std::swap(LHSCst, RHSCst);
2243             std::swap(LHSCC, RHSCC);
2244           }
2245
2246           // At this point, we know we have have two setcc instructions
2247           // comparing a value against two constants and or'ing the result
2248           // together.  Because of the above check, we know that we only have
2249           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
2250           // FoldSetCCLogical check above), that the two constants are not
2251           // equal.
2252           assert(LHSCst != RHSCst && "Compares not folded above?");
2253
2254           switch (LHSCC) {
2255           default: assert(0 && "Unknown integer condition code!");
2256           case Instruction::SetEQ:
2257             switch (RHSCC) {
2258             default: assert(0 && "Unknown integer condition code!");
2259             case Instruction::SetEQ:
2260               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2261                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2262                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2263                                                       LHSVal->getName()+".off");
2264                 InsertNewInstBefore(Add, I);
2265                 const Type *UnsType = Add->getType()->getUnsignedVersion();
2266                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2267                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2268                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2269                 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2270               }
2271               break;                  // (X == 13 | X == 15) -> no change
2272
2273             case Instruction::SetGT:  // (X == 13 | X > 14) -> no change
2274               break;
2275             case Instruction::SetNE:  // (X == 13 | X != 15) -> X != 15
2276             case Instruction::SetLT:  // (X == 13 | X < 15)  -> X < 15
2277               return ReplaceInstUsesWith(I, RHS);
2278             }
2279             break;
2280           case Instruction::SetNE:
2281             switch (RHSCC) {
2282             default: assert(0 && "Unknown integer condition code!");
2283             case Instruction::SetEQ:        // (X != 13 | X == 15) -> X != 13
2284             case Instruction::SetGT:        // (X != 13 | X > 15)  -> X != 13
2285               return ReplaceInstUsesWith(I, LHS);
2286             case Instruction::SetNE:        // (X != 13 | X != 15) -> true
2287             case Instruction::SetLT:        // (X != 13 | X < 15)  -> true
2288               return ReplaceInstUsesWith(I, ConstantBool::True);
2289             }
2290             break;
2291           case Instruction::SetLT:
2292             switch (RHSCC) {
2293             default: assert(0 && "Unknown integer condition code!");
2294             case Instruction::SetEQ:  // (X < 13 | X == 14) -> no change
2295               break;
2296             case Instruction::SetGT:  // (X < 13 | X > 15)  -> (X-13) > 2
2297               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
2298             case Instruction::SetNE:  // (X < 13 | X != 15) -> X != 15
2299             case Instruction::SetLT:  // (X < 13 | X < 15) -> X < 15
2300               return ReplaceInstUsesWith(I, RHS);
2301             }
2302             break;
2303           case Instruction::SetGT:
2304             switch (RHSCC) {
2305             default: assert(0 && "Unknown integer condition code!");
2306             case Instruction::SetEQ:  // (X > 13 | X == 15) -> X > 13
2307             case Instruction::SetGT:  // (X > 13 | X > 15)  -> X > 13
2308               return ReplaceInstUsesWith(I, LHS);
2309             case Instruction::SetNE:  // (X > 13 | X != 15)  -> true
2310             case Instruction::SetLT:  // (X > 13 | X < 15) -> true
2311               return ReplaceInstUsesWith(I, ConstantBool::True);
2312             }
2313           }
2314         }
2315   }
2316
2317   return Changed ? &I : 0;
2318 }
2319
2320 // XorSelf - Implements: X ^ X --> 0
2321 struct XorSelf {
2322   Value *RHS;
2323   XorSelf(Value *rhs) : RHS(rhs) {}
2324   bool shouldApply(Value *LHS) const { return LHS == RHS; }
2325   Instruction *apply(BinaryOperator &Xor) const {
2326     return &Xor;
2327   }
2328 };
2329
2330
2331 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2332   bool Changed = SimplifyCommutative(I);
2333   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2334
2335   if (isa<UndefValue>(Op1))
2336     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
2337
2338   // xor X, X = 0, even if X is nested in a sequence of Xor's.
2339   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2340     assert(Result == &I && "AssociativeOpt didn't work?");
2341     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2342   }
2343
2344   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2345     // xor X, 0 == X
2346     if (RHS->isNullValue())
2347       return ReplaceInstUsesWith(I, Op0);
2348
2349     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2350       // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
2351       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
2352         if (RHS == ConstantBool::True && SCI->hasOneUse())
2353           return new SetCondInst(SCI->getInverseCondition(),
2354                                  SCI->getOperand(0), SCI->getOperand(1));
2355
2356       // ~(c-X) == X-c-1 == X+(-c-1)
2357       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2358         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2359           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2360           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2361                                               ConstantInt::get(I.getType(), 1));
2362           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
2363         }
2364
2365       // ~(~X & Y) --> (X | ~Y)
2366       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2367         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2368         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2369           Instruction *NotY =
2370             BinaryOperator::createNot(Op0I->getOperand(1),
2371                                       Op0I->getOperand(1)->getName()+".not");
2372           InsertNewInstBefore(NotY, I);
2373           return BinaryOperator::createOr(Op0NotVal, NotY);
2374         }
2375       }
2376
2377       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2378         switch (Op0I->getOpcode()) {
2379         case Instruction::Add:
2380           // ~(X-c) --> (-c-1)-X
2381           if (RHS->isAllOnesValue()) {
2382             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2383             return BinaryOperator::createSub(
2384                            ConstantExpr::getSub(NegOp0CI,
2385                                              ConstantInt::get(I.getType(), 1)),
2386                                           Op0I->getOperand(0));
2387           }
2388           break;
2389         case Instruction::And:
2390           // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
2391           if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2392             return BinaryOperator::createOr(Op0, RHS);
2393           break;
2394         case Instruction::Or:
2395           // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
2396           if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
2397             return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
2398           break;
2399         default: break;
2400         }
2401     }
2402
2403     // Try to fold constant and into select arguments.
2404     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2405       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2406         return R;
2407     if (isa<PHINode>(Op0))
2408       if (Instruction *NV = FoldOpIntoPhi(I))
2409         return NV;
2410   }
2411
2412   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
2413     if (X == Op1)
2414       return ReplaceInstUsesWith(I,
2415                                 ConstantIntegral::getAllOnesValue(I.getType()));
2416
2417   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
2418     if (X == Op0)
2419       return ReplaceInstUsesWith(I,
2420                                 ConstantIntegral::getAllOnesValue(I.getType()));
2421
2422   if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
2423     if (Op1I->getOpcode() == Instruction::Or) {
2424       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
2425         cast<BinaryOperator>(Op1I)->swapOperands();
2426         I.swapOperands();
2427         std::swap(Op0, Op1);
2428       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
2429         I.swapOperands();
2430         std::swap(Op0, Op1);
2431       }
2432     } else if (Op1I->getOpcode() == Instruction::Xor) {
2433       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
2434         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2435       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
2436         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2437     }
2438
2439   if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
2440     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
2441       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
2442         cast<BinaryOperator>(Op0I)->swapOperands();
2443       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
2444         Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2445                                                      Op1->getName()+".not"), I);
2446         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
2447       }
2448     } else if (Op0I->getOpcode() == Instruction::Xor) {
2449       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
2450         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2451       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
2452         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2453     }
2454
2455   // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
2456   ConstantInt *C1 = 0, *C2 = 0;
2457   if (match(Op0, m_And(m_Value(), m_ConstantInt(C1))) &&
2458       match(Op1, m_And(m_Value(), m_ConstantInt(C2))) &&
2459       ConstantExpr::getAnd(C1, C2)->isNullValue())
2460     return BinaryOperator::createOr(Op0, Op1);
2461
2462   // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2463   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2464     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2465       return R;
2466
2467   return Changed ? &I : 0;
2468 }
2469
2470 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2471 /// overflowed for this type.
2472 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2473                             ConstantInt *In2) {
2474   Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2475   return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2476 }
2477
2478 static bool isPositive(ConstantInt *C) {
2479   return cast<ConstantSInt>(C)->getValue() >= 0;
2480 }
2481
2482 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2483 /// overflowed for this type.
2484 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2485                             ConstantInt *In2) {
2486   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2487
2488   if (In1->getType()->isUnsigned())
2489     return cast<ConstantUInt>(Result)->getValue() <
2490            cast<ConstantUInt>(In1)->getValue();
2491   if (isPositive(In1) != isPositive(In2))
2492     return false;
2493   if (isPositive(In1))
2494     return cast<ConstantSInt>(Result)->getValue() <
2495            cast<ConstantSInt>(In1)->getValue();
2496   return cast<ConstantSInt>(Result)->getValue() >
2497          cast<ConstantSInt>(In1)->getValue();
2498 }
2499
2500 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2501 /// code necessary to compute the offset from the base pointer (without adding
2502 /// in the base pointer).  Return the result as a signed integer of intptr size.
2503 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2504   TargetData &TD = IC.getTargetData();
2505   gep_type_iterator GTI = gep_type_begin(GEP);
2506   const Type *UIntPtrTy = TD.getIntPtrType();
2507   const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2508   Value *Result = Constant::getNullValue(SIntPtrTy);
2509
2510   // Build a mask for high order bits.
2511   uint64_t PtrSizeMask = ~0ULL;
2512   PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2513
2514   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2515     Value *Op = GEP->getOperand(i);
2516     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
2517     Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2518                                             SIntPtrTy);
2519     if (Constant *OpC = dyn_cast<Constant>(Op)) {
2520       if (!OpC->isNullValue()) {
2521         OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
2522         Scale = ConstantExpr::getMul(OpC, Scale);
2523         if (Constant *RC = dyn_cast<Constant>(Result))
2524           Result = ConstantExpr::getAdd(RC, Scale);
2525         else {
2526           // Emit an add instruction.
2527           Result = IC.InsertNewInstBefore(
2528              BinaryOperator::createAdd(Result, Scale,
2529                                        GEP->getName()+".offs"), I);
2530         }
2531       }
2532     } else {
2533       // Convert to correct type.
2534       Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2535                                                Op->getName()+".c"), I);
2536       if (Size != 1)
2537         // We'll let instcombine(mul) convert this to a shl if possible.
2538         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2539                                                     GEP->getName()+".idx"), I);
2540
2541       // Emit an add instruction.
2542       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
2543                                                     GEP->getName()+".offs"), I);
2544     }
2545   }
2546   return Result;
2547 }
2548
2549 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2550 /// else.  At this point we know that the GEP is on the LHS of the comparison.
2551 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2552                                         Instruction::BinaryOps Cond,
2553                                         Instruction &I) {
2554   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
2555
2556   if (CastInst *CI = dyn_cast<CastInst>(RHS))
2557     if (isa<PointerType>(CI->getOperand(0)->getType()))
2558       RHS = CI->getOperand(0);
2559
2560   Value *PtrBase = GEPLHS->getOperand(0);
2561   if (PtrBase == RHS) {
2562     // As an optimization, we don't actually have to compute the actual value of
2563     // OFFSET if this is a seteq or setne comparison, just return whether each
2564     // index is zero or not.
2565     if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2566       Instruction *InVal = 0;
2567       gep_type_iterator GTI = gep_type_begin(GEPLHS);
2568       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
2569         bool EmitIt = true;
2570         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2571           if (isa<UndefValue>(C))  // undef index -> undef.
2572             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2573           if (C->isNullValue())
2574             EmitIt = false;
2575           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2576             EmitIt = false;  // This is indexing into a zero sized array?
2577           } else if (isa<ConstantInt>(C))
2578             return ReplaceInstUsesWith(I, // No comparison is needed here.
2579                                  ConstantBool::get(Cond == Instruction::SetNE));
2580         }
2581
2582         if (EmitIt) {
2583           Instruction *Comp =
2584             new SetCondInst(Cond, GEPLHS->getOperand(i),
2585                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2586           if (InVal == 0)
2587             InVal = Comp;
2588           else {
2589             InVal = InsertNewInstBefore(InVal, I);
2590             InsertNewInstBefore(Comp, I);
2591             if (Cond == Instruction::SetNE)   // True if any are unequal
2592               InVal = BinaryOperator::createOr(InVal, Comp);
2593             else                              // True if all are equal
2594               InVal = BinaryOperator::createAnd(InVal, Comp);
2595           }
2596         }
2597       }
2598
2599       if (InVal)
2600         return InVal;
2601       else
2602         ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2603                             ConstantBool::get(Cond == Instruction::SetEQ));
2604     }
2605
2606     // Only lower this if the setcc is the only user of the GEP or if we expect
2607     // the result to fold to a constant!
2608     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2609       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
2610       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2611       return new SetCondInst(Cond, Offset,
2612                              Constant::getNullValue(Offset->getType()));
2613     }
2614   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
2615     // If the base pointers are different, but the indices are the same, just
2616     // compare the base pointer.
2617     if (PtrBase != GEPRHS->getOperand(0)) {
2618       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
2619       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
2620                         GEPRHS->getOperand(0)->getType();
2621       if (IndicesTheSame)
2622         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2623           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2624             IndicesTheSame = false;
2625             break;
2626           }
2627
2628       // If all indices are the same, just compare the base pointers.
2629       if (IndicesTheSame)
2630         return new SetCondInst(Cond, GEPLHS->getOperand(0),
2631                                GEPRHS->getOperand(0));
2632
2633       // Otherwise, the base pointers are different and the indices are
2634       // different, bail out.
2635       return 0;
2636     }
2637
2638     // If one of the GEPs has all zero indices, recurse.
2639     bool AllZeros = true;
2640     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2641       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2642           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2643         AllZeros = false;
2644         break;
2645       }
2646     if (AllZeros)
2647       return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2648                           SetCondInst::getSwappedCondition(Cond), I);
2649
2650     // If the other GEP has all zero indices, recurse.
2651     AllZeros = true;
2652     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2653       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2654           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2655         AllZeros = false;
2656         break;
2657       }
2658     if (AllZeros)
2659       return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2660
2661     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2662       // If the GEPs only differ by one index, compare it.
2663       unsigned NumDifferences = 0;  // Keep track of # differences.
2664       unsigned DiffOperand = 0;     // The operand that differs.
2665       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2666         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2667           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2668                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
2669             // Irreconcilable differences.
2670             NumDifferences = 2;
2671             break;
2672           } else {
2673             if (NumDifferences++) break;
2674             DiffOperand = i;
2675           }
2676         }
2677
2678       if (NumDifferences == 0)   // SAME GEP?
2679         return ReplaceInstUsesWith(I, // No comparison is needed here.
2680                                  ConstantBool::get(Cond == Instruction::SetEQ));
2681       else if (NumDifferences == 1) {
2682         Value *LHSV = GEPLHS->getOperand(DiffOperand);
2683         Value *RHSV = GEPRHS->getOperand(DiffOperand);
2684
2685         // Convert the operands to signed values to make sure to perform a
2686         // signed comparison.
2687         const Type *NewTy = LHSV->getType()->getSignedVersion();
2688         if (LHSV->getType() != NewTy)
2689           LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2690                                                   LHSV->getName()), I);
2691         if (RHSV->getType() != NewTy)
2692           RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2693                                                   RHSV->getName()), I);
2694         return new SetCondInst(Cond, LHSV, RHSV);
2695       }
2696     }
2697
2698     // Only lower this if the setcc is the only user of the GEP or if we expect
2699     // the result to fold to a constant!
2700     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2701         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2702       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
2703       Value *L = EmitGEPOffset(GEPLHS, I, *this);
2704       Value *R = EmitGEPOffset(GEPRHS, I, *this);
2705       return new SetCondInst(Cond, L, R);
2706     }
2707   }
2708   return 0;
2709 }
2710
2711
2712 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
2713   bool Changed = SimplifyCommutative(I);
2714   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2715   const Type *Ty = Op0->getType();
2716
2717   // setcc X, X
2718   if (Op0 == Op1)
2719     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
2720
2721   if (isa<UndefValue>(Op1))                  // X setcc undef -> undef
2722     return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2723
2724   // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2725   // addresses never equal each other!  We already know that Op0 != Op1.
2726   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2727        isa<ConstantPointerNull>(Op0)) &&
2728       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
2729        isa<ConstantPointerNull>(Op1)))
2730     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2731
2732   // setcc's with boolean values can always be turned into bitwise operations
2733   if (Ty == Type::BoolTy) {
2734     switch (I.getOpcode()) {
2735     default: assert(0 && "Invalid setcc instruction!");
2736     case Instruction::SetEQ: {     //  seteq bool %A, %B -> ~(A^B)
2737       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
2738       InsertNewInstBefore(Xor, I);
2739       return BinaryOperator::createNot(Xor);
2740     }
2741     case Instruction::SetNE:
2742       return BinaryOperator::createXor(Op0, Op1);
2743
2744     case Instruction::SetGT:
2745       std::swap(Op0, Op1);                   // Change setgt -> setlt
2746       // FALL THROUGH
2747     case Instruction::SetLT: {               // setlt bool A, B -> ~X & Y
2748       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2749       InsertNewInstBefore(Not, I);
2750       return BinaryOperator::createAnd(Not, Op1);
2751     }
2752     case Instruction::SetGE:
2753       std::swap(Op0, Op1);                   // Change setge -> setle
2754       // FALL THROUGH
2755     case Instruction::SetLE: {     //  setle bool %A, %B -> ~A | B
2756       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2757       InsertNewInstBefore(Not, I);
2758       return BinaryOperator::createOr(Not, Op1);
2759     }
2760     }
2761   }
2762
2763   // See if we are doing a comparison between a constant and an instruction that
2764   // can be folded into the comparison.
2765   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2766     // Check to see if we are comparing against the minimum or maximum value...
2767     if (CI->isMinValue()) {
2768       if (I.getOpcode() == Instruction::SetLT)       // A < MIN -> FALSE
2769         return ReplaceInstUsesWith(I, ConstantBool::False);
2770       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN -> TRUE
2771         return ReplaceInstUsesWith(I, ConstantBool::True);
2772       if (I.getOpcode() == Instruction::SetLE)       // A <= MIN -> A == MIN
2773         return BinaryOperator::createSetEQ(Op0, Op1);
2774       if (I.getOpcode() == Instruction::SetGT)       // A > MIN -> A != MIN
2775         return BinaryOperator::createSetNE(Op0, Op1);
2776
2777     } else if (CI->isMaxValue()) {
2778       if (I.getOpcode() == Instruction::SetGT)       // A > MAX -> FALSE
2779         return ReplaceInstUsesWith(I, ConstantBool::False);
2780       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX -> TRUE
2781         return ReplaceInstUsesWith(I, ConstantBool::True);
2782       if (I.getOpcode() == Instruction::SetGE)       // A >= MAX -> A == MAX
2783         return BinaryOperator::createSetEQ(Op0, Op1);
2784       if (I.getOpcode() == Instruction::SetLT)       // A < MAX -> A != MAX
2785         return BinaryOperator::createSetNE(Op0, Op1);
2786
2787       // Comparing against a value really close to min or max?
2788     } else if (isMinValuePlusOne(CI)) {
2789       if (I.getOpcode() == Instruction::SetLT)       // A < MIN+1 -> A == MIN
2790         return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2791       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN-1 -> A != MIN
2792         return BinaryOperator::createSetNE(Op0, SubOne(CI));
2793
2794     } else if (isMaxValueMinusOne(CI)) {
2795       if (I.getOpcode() == Instruction::SetGT)       // A > MAX-1 -> A == MAX
2796         return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2797       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX-1 -> A != MAX
2798         return BinaryOperator::createSetNE(Op0, AddOne(CI));
2799     }
2800
2801     // If we still have a setle or setge instruction, turn it into the
2802     // appropriate setlt or setgt instruction.  Since the border cases have
2803     // already been handled above, this requires little checking.
2804     //
2805     if (I.getOpcode() == Instruction::SetLE)
2806       return BinaryOperator::createSetLT(Op0, AddOne(CI));
2807     if (I.getOpcode() == Instruction::SetGE)
2808       return BinaryOperator::createSetGT(Op0, SubOne(CI));
2809
2810     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2811       switch (LHSI->getOpcode()) {
2812       case Instruction::And:
2813         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2814             LHSI->getOperand(0)->hasOneUse()) {
2815           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2816           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
2817           // happens a LOT in code produced by the C front-end, for bitfield
2818           // access.
2819           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2820           ConstantUInt *ShAmt;
2821           ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2822           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2823           const Type *Ty = LHSI->getType();
2824
2825           // We can fold this as long as we can't shift unknown bits
2826           // into the mask.  This can only happen with signed shift
2827           // rights, as they sign-extend.
2828           if (ShAmt) {
2829             bool CanFold = Shift->getOpcode() != Instruction::Shr ||
2830                            Shift->getType()->isUnsigned();
2831             if (!CanFold) {
2832               // To test for the bad case of the signed shr, see if any
2833               // of the bits shifted in could be tested after the mask.
2834               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2835               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2836
2837               Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
2838               Constant *ShVal =
2839                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2840               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2841                 CanFold = true;
2842             }
2843
2844             if (CanFold) {
2845               Constant *NewCst;
2846               if (Shift->getOpcode() == Instruction::Shl)
2847                 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2848               else
2849                 NewCst = ConstantExpr::getShl(CI, ShAmt);
2850
2851               // Check to see if we are shifting out any of the bits being
2852               // compared.
2853               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2854                 // If we shifted bits out, the fold is not going to work out.
2855                 // As a special case, check to see if this means that the
2856                 // result is always true or false now.
2857                 if (I.getOpcode() == Instruction::SetEQ)
2858                   return ReplaceInstUsesWith(I, ConstantBool::False);
2859                 if (I.getOpcode() == Instruction::SetNE)
2860                   return ReplaceInstUsesWith(I, ConstantBool::True);
2861               } else {
2862                 I.setOperand(1, NewCst);
2863                 Constant *NewAndCST;
2864                 if (Shift->getOpcode() == Instruction::Shl)
2865                   NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2866                 else
2867                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2868                 LHSI->setOperand(1, NewAndCST);
2869                 LHSI->setOperand(0, Shift->getOperand(0));
2870                 WorkList.push_back(Shift); // Shift is dead.
2871                 AddUsesToWorkList(I);
2872                 return &I;
2873               }
2874             }
2875           }
2876         }
2877         break;
2878
2879       case Instruction::Shl:         // (setcc (shl X, ShAmt), CI)
2880         if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2881           switch (I.getOpcode()) {
2882           default: break;
2883           case Instruction::SetEQ:
2884           case Instruction::SetNE: {
2885             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2886
2887             // Check that the shift amount is in range.  If not, don't perform
2888             // undefined shifts.  When the shift is visited it will be
2889             // simplified.
2890             if (ShAmt->getValue() >= TypeBits)
2891               break;
2892
2893             // If we are comparing against bits always shifted out, the
2894             // comparison cannot succeed.
2895             Constant *Comp =
2896               ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2897             if (Comp != CI) {// Comparing against a bit that we know is zero.
2898               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2899               Constant *Cst = ConstantBool::get(IsSetNE);
2900               return ReplaceInstUsesWith(I, Cst);
2901             }
2902
2903             if (LHSI->hasOneUse()) {
2904               // Otherwise strength reduce the shift into an and.
2905               unsigned ShAmtVal = (unsigned)ShAmt->getValue();
2906               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2907
2908               Constant *Mask;
2909               if (CI->getType()->isUnsigned()) {
2910                 Mask = ConstantUInt::get(CI->getType(), Val);
2911               } else if (ShAmtVal != 0) {
2912                 Mask = ConstantSInt::get(CI->getType(), Val);
2913               } else {
2914                 Mask = ConstantInt::getAllOnesValue(CI->getType());
2915               }
2916
2917               Instruction *AndI =
2918                 BinaryOperator::createAnd(LHSI->getOperand(0),
2919                                           Mask, LHSI->getName()+".mask");
2920               Value *And = InsertNewInstBefore(AndI, I);
2921               return new SetCondInst(I.getOpcode(), And,
2922                                      ConstantExpr::getUShr(CI, ShAmt));
2923             }
2924           }
2925           }
2926         }
2927         break;
2928
2929       case Instruction::Shr:         // (setcc (shr X, ShAmt), CI)
2930         if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2931           switch (I.getOpcode()) {
2932           default: break;
2933           case Instruction::SetEQ:
2934           case Instruction::SetNE: {
2935
2936             // Check that the shift amount is in range.  If not, don't perform
2937             // undefined shifts.  When the shift is visited it will be
2938             // simplified.
2939             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2940             if (ShAmt->getValue() >= TypeBits)
2941               break;
2942
2943             // If we are comparing against bits always shifted out, the
2944             // comparison cannot succeed.
2945             Constant *Comp =
2946               ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2947
2948             if (Comp != CI) {// Comparing against a bit that we know is zero.
2949               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2950               Constant *Cst = ConstantBool::get(IsSetNE);
2951               return ReplaceInstUsesWith(I, Cst);
2952             }
2953
2954             if (LHSI->hasOneUse() || CI->isNullValue()) {
2955               unsigned ShAmtVal = (unsigned)ShAmt->getValue();
2956
2957               // Otherwise strength reduce the shift into an and.
2958               uint64_t Val = ~0ULL;          // All ones.
2959               Val <<= ShAmtVal;              // Shift over to the right spot.
2960
2961               Constant *Mask;
2962               if (CI->getType()->isUnsigned()) {
2963                 Val &= ~0ULL >> (64-TypeBits);
2964                 Mask = ConstantUInt::get(CI->getType(), Val);
2965               } else {
2966                 Mask = ConstantSInt::get(CI->getType(), Val);
2967               }
2968
2969               Instruction *AndI =
2970                 BinaryOperator::createAnd(LHSI->getOperand(0),
2971                                           Mask, LHSI->getName()+".mask");
2972               Value *And = InsertNewInstBefore(AndI, I);
2973               return new SetCondInst(I.getOpcode(), And,
2974                                      ConstantExpr::getShl(CI, ShAmt));
2975             }
2976             break;
2977           }
2978           }
2979         }
2980         break;
2981
2982       case Instruction::Div:
2983         // Fold: (div X, C1) op C2 -> range check
2984         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2985           // Fold this div into the comparison, producing a range check.
2986           // Determine, based on the divide type, what the range is being
2987           // checked.  If there is an overflow on the low or high side, remember
2988           // it, otherwise compute the range [low, hi) bounding the new value.
2989           bool LoOverflow = false, HiOverflow = 0;
2990           ConstantInt *LoBound = 0, *HiBound = 0;
2991
2992           ConstantInt *Prod;
2993           bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2994
2995           Instruction::BinaryOps Opcode = I.getOpcode();
2996
2997           if (DivRHS->isNullValue()) {  // Don't hack on divide by zeros.
2998           } else if (LHSI->getType()->isUnsigned()) {  // udiv
2999             LoBound = Prod;
3000             LoOverflow = ProdOV;
3001             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3002           } else if (isPositive(DivRHS)) {             // Divisor is > 0.
3003             if (CI->isNullValue()) {       // (X / pos) op 0
3004               // Can't overflow.
3005               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3006               HiBound = DivRHS;
3007             } else if (isPositive(CI)) {   // (X / pos) op pos
3008               LoBound = Prod;
3009               LoOverflow = ProdOV;
3010               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3011             } else {                       // (X / pos) op neg
3012               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3013               LoOverflow = AddWithOverflow(LoBound, Prod,
3014                                            cast<ConstantInt>(DivRHSH));
3015               HiBound = Prod;
3016               HiOverflow = ProdOV;
3017             }
3018           } else {                                     // Divisor is < 0.
3019             if (CI->isNullValue()) {       // (X / neg) op 0
3020               LoBound = AddOne(DivRHS);
3021               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
3022               if (HiBound == DivRHS)
3023                 LoBound = 0;  // - INTMIN = INTMIN
3024             } else if (isPositive(CI)) {   // (X / neg) op pos
3025               HiOverflow = LoOverflow = ProdOV;
3026               if (!LoOverflow)
3027                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3028               HiBound = AddOne(Prod);
3029             } else {                       // (X / neg) op neg
3030               LoBound = Prod;
3031               LoOverflow = HiOverflow = ProdOV;
3032               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3033             }
3034
3035             // Dividing by a negate swaps the condition.
3036             Opcode = SetCondInst::getSwappedCondition(Opcode);
3037           }
3038
3039           if (LoBound) {
3040             Value *X = LHSI->getOperand(0);
3041             switch (Opcode) {
3042             default: assert(0 && "Unhandled setcc opcode!");
3043             case Instruction::SetEQ:
3044               if (LoOverflow && HiOverflow)
3045                 return ReplaceInstUsesWith(I, ConstantBool::False);
3046               else if (HiOverflow)
3047                 return new SetCondInst(Instruction::SetGE, X, LoBound);
3048               else if (LoOverflow)
3049                 return new SetCondInst(Instruction::SetLT, X, HiBound);
3050               else
3051                 return InsertRangeTest(X, LoBound, HiBound, true, I);
3052             case Instruction::SetNE:
3053               if (LoOverflow && HiOverflow)
3054                 return ReplaceInstUsesWith(I, ConstantBool::True);
3055               else if (HiOverflow)
3056                 return new SetCondInst(Instruction::SetLT, X, LoBound);
3057               else if (LoOverflow)
3058                 return new SetCondInst(Instruction::SetGE, X, HiBound);
3059               else
3060                 return InsertRangeTest(X, LoBound, HiBound, false, I);
3061             case Instruction::SetLT:
3062               if (LoOverflow)
3063                 return ReplaceInstUsesWith(I, ConstantBool::False);
3064               return new SetCondInst(Instruction::SetLT, X, LoBound);
3065             case Instruction::SetGT:
3066               if (HiOverflow)
3067                 return ReplaceInstUsesWith(I, ConstantBool::False);
3068               return new SetCondInst(Instruction::SetGE, X, HiBound);
3069             }
3070           }
3071         }
3072         break;
3073       }
3074
3075     // Simplify seteq and setne instructions...
3076     if (I.getOpcode() == Instruction::SetEQ ||
3077         I.getOpcode() == Instruction::SetNE) {
3078       bool isSetNE = I.getOpcode() == Instruction::SetNE;
3079
3080       // If the first operand is (and|or|xor) with a constant, and the second
3081       // operand is a constant, simplify a bit.
3082       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3083         switch (BO->getOpcode()) {
3084         case Instruction::Rem:
3085           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3086           if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3087               BO->hasOneUse() &&
3088               cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3089             int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3090             if (isPowerOf2_64(V)) {
3091               unsigned L2 = Log2_64(V);
3092               const Type *UTy = BO->getType()->getUnsignedVersion();
3093               Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3094                                                              UTy, "tmp"), I);
3095               Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3096               Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3097                                                     RHSCst, BO->getName()), I);
3098               return BinaryOperator::create(I.getOpcode(), NewRem,
3099                                             Constant::getNullValue(UTy));
3100             }
3101           }
3102           break;
3103
3104         case Instruction::Add:
3105           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3106           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3107             if (BO->hasOneUse())
3108               return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3109                                      ConstantExpr::getSub(CI, BOp1C));
3110           } else if (CI->isNullValue()) {
3111             // Replace ((add A, B) != 0) with (A != -B) if A or B is
3112             // efficiently invertible, or if the add has just this one use.
3113             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3114
3115             if (Value *NegVal = dyn_castNegVal(BOp1))
3116               return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3117             else if (Value *NegVal = dyn_castNegVal(BOp0))
3118               return new SetCondInst(I.getOpcode(), NegVal, BOp1);
3119             else if (BO->hasOneUse()) {
3120               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3121               BO->setName("");
3122               InsertNewInstBefore(Neg, I);
3123               return new SetCondInst(I.getOpcode(), BOp0, Neg);
3124             }
3125           }
3126           break;
3127         case Instruction::Xor:
3128           // For the xor case, we can xor two constants together, eliminating
3129           // the explicit xor.
3130           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3131             return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
3132                                   ConstantExpr::getXor(CI, BOC));
3133
3134           // FALLTHROUGH
3135         case Instruction::Sub:
3136           // Replace (([sub|xor] A, B) != 0) with (A != B)
3137           if (CI->isNullValue())
3138             return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3139                                    BO->getOperand(1));
3140           break;
3141
3142         case Instruction::Or:
3143           // If bits are being or'd in that are not present in the constant we
3144           // are comparing against, then the comparison could never succeed!
3145           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
3146             Constant *NotCI = ConstantExpr::getNot(CI);
3147             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
3148               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3149           }
3150           break;
3151
3152         case Instruction::And:
3153           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3154             // If bits are being compared against that are and'd out, then the
3155             // comparison can never succeed!
3156             if (!ConstantExpr::getAnd(CI,
3157                                       ConstantExpr::getNot(BOC))->isNullValue())
3158               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3159
3160             // If we have ((X & C) == C), turn it into ((X & C) != 0).
3161             if (CI == BOC && isOneBitSet(CI))
3162               return new SetCondInst(isSetNE ? Instruction::SetEQ :
3163                                      Instruction::SetNE, Op0,
3164                                      Constant::getNullValue(CI->getType()));
3165
3166             // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3167             // to be a signed value as appropriate.
3168             if (isSignBit(BOC)) {
3169               Value *X = BO->getOperand(0);
3170               // If 'X' is not signed, insert a cast now...
3171               if (!BOC->getType()->isSigned()) {
3172                 const Type *DestTy = BOC->getType()->getSignedVersion();
3173                 X = InsertCastBefore(X, DestTy, I);
3174               }
3175               return new SetCondInst(isSetNE ? Instruction::SetLT :
3176                                          Instruction::SetGE, X,
3177                                      Constant::getNullValue(X->getType()));
3178             }
3179
3180             // ((X & ~7) == 0) --> X < 8
3181             if (CI->isNullValue() && isHighOnes(BOC)) {
3182               Value *X = BO->getOperand(0);
3183               Constant *NegX = ConstantExpr::getNeg(BOC);
3184
3185               // If 'X' is signed, insert a cast now.
3186               if (NegX->getType()->isSigned()) {
3187                 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3188                 X = InsertCastBefore(X, DestTy, I);
3189                 NegX = ConstantExpr::getCast(NegX, DestTy);
3190               }
3191
3192               return new SetCondInst(isSetNE ? Instruction::SetGE :
3193                                      Instruction::SetLT, X, NegX);
3194             }
3195
3196           }
3197         default: break;
3198         }
3199       }
3200     } else {  // Not a SetEQ/SetNE
3201       // If the LHS is a cast from an integral value of the same size,
3202       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3203         Value *CastOp = Cast->getOperand(0);
3204         const Type *SrcTy = CastOp->getType();
3205         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
3206         if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
3207             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
3208           assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
3209                  "Source and destination signednesses should differ!");
3210           if (Cast->getType()->isSigned()) {
3211             // If this is a signed comparison, check for comparisons in the
3212             // vicinity of zero.
3213             if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3214               // X < 0  => x > 127
3215               return BinaryOperator::createSetGT(CastOp,
3216                          ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
3217             else if (I.getOpcode() == Instruction::SetGT &&
3218                      cast<ConstantSInt>(CI)->getValue() == -1)
3219               // X > -1  => x < 128
3220               return BinaryOperator::createSetLT(CastOp,
3221                          ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
3222           } else {
3223             ConstantUInt *CUI = cast<ConstantUInt>(CI);
3224             if (I.getOpcode() == Instruction::SetLT &&
3225                 CUI->getValue() == 1ULL << (SrcTySize-1))
3226               // X < 128 => X > -1
3227               return BinaryOperator::createSetGT(CastOp,
3228                                                  ConstantSInt::get(SrcTy, -1));
3229             else if (I.getOpcode() == Instruction::SetGT &&
3230                      CUI->getValue() == (1ULL << (SrcTySize-1))-1)
3231               // X > 127 => X < 0
3232               return BinaryOperator::createSetLT(CastOp,
3233                                                  Constant::getNullValue(SrcTy));
3234           }
3235         }
3236       }
3237     }
3238   }
3239
3240   // Handle setcc with constant RHS's that can be integer, FP or pointer.
3241   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3242     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3243       switch (LHSI->getOpcode()) {
3244       case Instruction::GetElementPtr:
3245         if (RHSC->isNullValue()) {
3246           // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3247           bool isAllZeros = true;
3248           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3249             if (!isa<Constant>(LHSI->getOperand(i)) ||
3250                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3251               isAllZeros = false;
3252               break;
3253             }
3254           if (isAllZeros)
3255             return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3256                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
3257         }
3258         break;
3259
3260       case Instruction::PHI:
3261         if (Instruction *NV = FoldOpIntoPhi(I))
3262           return NV;
3263         break;
3264       case Instruction::Select:
3265         // If either operand of the select is a constant, we can fold the
3266         // comparison into the select arms, which will cause one to be
3267         // constant folded and the select turned into a bitwise or.
3268         Value *Op1 = 0, *Op2 = 0;
3269         if (LHSI->hasOneUse()) {
3270           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3271             // Fold the known value into the constant operand.
3272             Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3273             // Insert a new SetCC of the other select operand.
3274             Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3275                                                       LHSI->getOperand(2), RHSC,
3276                                                       I.getName()), I);
3277           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3278             // Fold the known value into the constant operand.
3279             Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3280             // Insert a new SetCC of the other select operand.
3281             Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3282                                                       LHSI->getOperand(1), RHSC,
3283                                                       I.getName()), I);
3284           }
3285         }
3286
3287         if (Op1)
3288           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3289         break;
3290       }
3291   }
3292
3293   // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3294   if (User *GEP = dyn_castGetElementPtr(Op0))
3295     if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3296       return NI;
3297   if (User *GEP = dyn_castGetElementPtr(Op1))
3298     if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3299                            SetCondInst::getSwappedCondition(I.getOpcode()), I))
3300       return NI;
3301
3302   // Test to see if the operands of the setcc are casted versions of other
3303   // values.  If the cast can be stripped off both arguments, we do so now.
3304   if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3305     Value *CastOp0 = CI->getOperand(0);
3306     if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
3307         (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
3308         (I.getOpcode() == Instruction::SetEQ ||
3309          I.getOpcode() == Instruction::SetNE)) {
3310       // We keep moving the cast from the left operand over to the right
3311       // operand, where it can often be eliminated completely.
3312       Op0 = CastOp0;
3313
3314       // If operand #1 is a cast instruction, see if we can eliminate it as
3315       // well.
3316       if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3317         if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
3318                                                                Op0->getType()))
3319           Op1 = CI2->getOperand(0);
3320
3321       // If Op1 is a constant, we can fold the cast into the constant.
3322       if (Op1->getType() != Op0->getType())
3323         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3324           Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3325         } else {
3326           // Otherwise, cast the RHS right before the setcc
3327           Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3328           InsertNewInstBefore(cast<Instruction>(Op1), I);
3329         }
3330       return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3331     }
3332
3333     // Handle the special case of: setcc (cast bool to X), <cst>
3334     // This comes up when you have code like
3335     //   int X = A < B;
3336     //   if (X) ...
3337     // For generality, we handle any zero-extension of any operand comparison
3338     // with a constant or another cast from the same type.
3339     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3340       if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3341         return R;
3342   }
3343   return Changed ? &I : 0;
3344 }
3345
3346 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3347 // We only handle extending casts so far.
3348 //
3349 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3350   Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3351   const Type *SrcTy = LHSCIOp->getType();
3352   const Type *DestTy = SCI.getOperand(0)->getType();
3353   Value *RHSCIOp;
3354
3355   if (!DestTy->isIntegral() || !SrcTy->isIntegral())
3356     return 0;
3357
3358   unsigned SrcBits  = SrcTy->getPrimitiveSizeInBits();
3359   unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3360   if (SrcBits >= DestBits) return 0;  // Only handle extending cast.
3361
3362   // Is this a sign or zero extension?
3363   bool isSignSrc  = SrcTy->isSigned();
3364   bool isSignDest = DestTy->isSigned();
3365
3366   if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3367     // Not an extension from the same type?
3368     RHSCIOp = CI->getOperand(0);
3369     if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3370   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3371     // Compute the constant that would happen if we truncated to SrcTy then
3372     // reextended to DestTy.
3373     Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3374
3375     if (ConstantExpr::getCast(Res, DestTy) == CI) {
3376       RHSCIOp = Res;
3377     } else {
3378       // If the value cannot be represented in the shorter type, we cannot emit
3379       // a simple comparison.
3380       if (SCI.getOpcode() == Instruction::SetEQ)
3381         return ReplaceInstUsesWith(SCI, ConstantBool::False);
3382       if (SCI.getOpcode() == Instruction::SetNE)
3383         return ReplaceInstUsesWith(SCI, ConstantBool::True);
3384
3385       // Evaluate the comparison for LT.
3386       Value *Result;
3387       if (DestTy->isSigned()) {
3388         // We're performing a signed comparison.
3389         if (isSignSrc) {
3390           // Signed extend and signed comparison.
3391           if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3392             Result = ConstantBool::False;
3393           else
3394             Result = ConstantBool::True;              // X < (large) --> true
3395         } else {
3396           // Unsigned extend and signed comparison.
3397           if (cast<ConstantSInt>(CI)->getValue() < 0)
3398             Result = ConstantBool::False;
3399           else
3400             Result = ConstantBool::True;
3401         }
3402       } else {
3403         // We're performing an unsigned comparison.
3404         if (!isSignSrc) {
3405           // Unsigned extend & compare -> always true.
3406           Result = ConstantBool::True;
3407         } else {
3408           // We're performing an unsigned comp with a sign extended value.
3409           // This is true if the input is >= 0. [aka >s -1]
3410           Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3411           Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3412                                                   NegOne, SCI.getName()), SCI);
3413         }
3414       }
3415
3416       // Finally, return the value computed.
3417       if (SCI.getOpcode() == Instruction::SetLT) {
3418         return ReplaceInstUsesWith(SCI, Result);
3419       } else {
3420         assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3421         if (Constant *CI = dyn_cast<Constant>(Result))
3422           return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3423         else
3424           return BinaryOperator::createNot(Result);
3425       }
3426     }
3427   } else {
3428     return 0;
3429   }
3430
3431   // Okay, just insert a compare of the reduced operands now!
3432   return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3433 }
3434
3435 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
3436   assert(I.getOperand(1)->getType() == Type::UByteTy);
3437   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3438   bool isLeftShift = I.getOpcode() == Instruction::Shl;
3439
3440   // shl X, 0 == X and shr X, 0 == X
3441   // shl 0, X == 0 and shr 0, X == 0
3442   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
3443       Op0 == Constant::getNullValue(Op0->getType()))
3444     return ReplaceInstUsesWith(I, Op0);
3445
3446   if (isa<UndefValue>(Op0)) {            // undef >>s X -> undef
3447     if (!isLeftShift && I.getType()->isSigned())
3448       return ReplaceInstUsesWith(I, Op0);
3449     else                         // undef << X -> 0   AND  undef >>u X -> 0
3450       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3451   }
3452   if (isa<UndefValue>(Op1)) {
3453     if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
3454       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3455     else
3456       return ReplaceInstUsesWith(I, Op0);          // X >>s undef -> X
3457   }
3458
3459   // shr int -1, X = -1   (for any arithmetic shift rights of ~0)
3460   if (!isLeftShift)
3461     if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3462       if (CSI->isAllOnesValue())
3463         return ReplaceInstUsesWith(I, CSI);
3464
3465   // Try to fold constant and into select arguments.
3466   if (isa<Constant>(Op0))
3467     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3468       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3469         return R;
3470
3471   // See if we can turn a signed shr into an unsigned shr.
3472   if (!isLeftShift && I.getType()->isSigned()) {
3473     if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3474       Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3475       V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3476                                             I.getName()), I);
3477       return new CastInst(V, I.getType());
3478     }
3479   }
3480
3481   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
3482     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3483       return Res;
3484   return 0;
3485 }
3486
3487 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
3488                                                ShiftInst &I) {
3489   bool isLeftShift = I.getOpcode() == Instruction::Shl;
3490   bool isSignedShift = Op0->getType()->isSigned();
3491   bool isUnsignedShift = !isSignedShift;
3492
3493   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3494   // of a signed value.
3495   //
3496   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
3497   if (Op1->getValue() >= TypeBits) {
3498     if (isUnsignedShift || isLeftShift)
3499       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3500     else {
3501       I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3502       return &I;
3503     }
3504   }
3505   
3506   // ((X*C1) << C2) == (X * (C1 << C2))
3507   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3508     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3509       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
3510         return BinaryOperator::createMul(BO->getOperand(0),
3511                                          ConstantExpr::getShl(BOOp, Op1));
3512   
3513   // Try to fold constant and into select arguments.
3514   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3515     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3516       return R;
3517   if (isa<PHINode>(Op0))
3518     if (Instruction *NV = FoldOpIntoPhi(I))
3519       return NV;
3520   
3521   if (Op0->hasOneUse()) {
3522     // If this is a SHL of a sign-extending cast, see if we can turn the input
3523     // into a zero extending cast (a simple strength reduction).
3524     if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3525       const Type *SrcTy = CI->getOperand(0)->getType();
3526       if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3527           SrcTy->getPrimitiveSizeInBits() <
3528           CI->getType()->getPrimitiveSizeInBits()) {
3529         // We can change it to a zero extension if we are shifting out all of
3530         // the sign extended bits.  To check this, form a mask of all of the
3531         // sign extend bits, then shift them left and see if we have anything
3532         // left.
3533         Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); //     1111
3534         Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());   // 00001111
3535         Mask = ConstantExpr::getNot(Mask);   // 1's in the sign bits: 11110000
3536         if (ConstantExpr::getShl(Mask, Op1)->isNullValue()) {
3537           // If the shift is nuking all of the sign bits, change this to a
3538           // zero extension cast.  To do this, cast the cast input to
3539           // unsigned, then to the requested size.
3540           Value *CastOp = CI->getOperand(0);
3541           Instruction *NC =
3542             new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3543                          CI->getName()+".uns");
3544           NC = InsertNewInstBefore(NC, I);
3545           // Finally, insert a replacement for CI.
3546           NC = new CastInst(NC, CI->getType(), CI->getName());
3547           CI->setName("");
3548           NC = InsertNewInstBefore(NC, I);
3549           WorkList.push_back(CI);  // Delete CI later.
3550           I.setOperand(0, NC);
3551           return &I;               // The SHL operand was modified.
3552         }
3553       }
3554     }
3555     
3556     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3557       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
3558       Value *V1, *V2;
3559       ConstantInt *CC;
3560       switch (Op0BO->getOpcode()) {
3561         default: break;
3562         case Instruction::Add:
3563         case Instruction::And:
3564         case Instruction::Or:
3565         case Instruction::Xor:
3566           // These operators commute.
3567           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
3568           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3569               match(Op0BO->getOperand(1),
3570                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
3571             Instruction *YS = new ShiftInst(Instruction::Shl, 
3572                                             Op0BO->getOperand(0), Op1,
3573                                             Op0BO->getName());
3574             InsertNewInstBefore(YS, I); // (Y << C)
3575             Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3576                                                     V1,
3577                                                     Op0BO->getOperand(1)->getName());
3578             InsertNewInstBefore(X, I);  // (X + (Y << C))
3579             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3580             C2 = ConstantExpr::getShl(C2, Op1);
3581             return BinaryOperator::createAnd(X, C2);
3582           }
3583           
3584           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
3585           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3586               match(Op0BO->getOperand(1),
3587                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
3588                           m_ConstantInt(CC))) && V2 == Op1 &&
3589               cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
3590             Instruction *YS = new ShiftInst(Instruction::Shl, 
3591                                             Op0BO->getOperand(0), Op1,
3592                                             Op0BO->getName());
3593             InsertNewInstBefore(YS, I); // (Y << C)
3594             Instruction *XM =
3595               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
3596                                         V1->getName()+".mask");
3597             InsertNewInstBefore(XM, I); // X & (CC << C)
3598             
3599             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3600           }
3601           
3602           // FALL THROUGH.
3603         case Instruction::Sub:
3604           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
3605           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3606               match(Op0BO->getOperand(0),
3607                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
3608             Instruction *YS = new ShiftInst(Instruction::Shl, 
3609                                             Op0BO->getOperand(1), Op1,
3610                                             Op0BO->getName());
3611             InsertNewInstBefore(YS, I); // (Y << C)
3612             Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3613                                                     V1,
3614                                                     Op0BO->getOperand(0)->getName());
3615             InsertNewInstBefore(X, I);  // (X + (Y << C))
3616             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3617             C2 = ConstantExpr::getShl(C2, Op1);
3618             return BinaryOperator::createAnd(X, C2);
3619           }
3620           
3621           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3622               match(Op0BO->getOperand(0),
3623                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
3624                           m_ConstantInt(CC))) && V2 == Op1 &&
3625               cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
3626             Instruction *YS = new ShiftInst(Instruction::Shl, 
3627                                             Op0BO->getOperand(1), Op1,
3628                                             Op0BO->getName());
3629             InsertNewInstBefore(YS, I); // (Y << C)
3630             Instruction *XM =
3631               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
3632                                         V1->getName()+".mask");
3633             InsertNewInstBefore(XM, I); // X & (CC << C)
3634             
3635             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3636           }
3637           
3638           break;
3639       }
3640       
3641       
3642       // If the operand is an bitwise operator with a constant RHS, and the
3643       // shift is the only use, we can pull it out of the shift.
3644       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3645         bool isValid = true;     // Valid only for And, Or, Xor
3646         bool highBitSet = false; // Transform if high bit of constant set?
3647         
3648         switch (Op0BO->getOpcode()) {
3649           default: isValid = false; break;   // Do not perform transform!
3650           case Instruction::Add:
3651             isValid = isLeftShift;
3652             break;
3653           case Instruction::Or:
3654           case Instruction::Xor:
3655             highBitSet = false;
3656             break;
3657           case Instruction::And:
3658             highBitSet = true;
3659             break;
3660         }
3661         
3662         // If this is a signed shift right, and the high bit is modified
3663         // by the logical operation, do not perform the transformation.
3664         // The highBitSet boolean indicates the value of the high bit of
3665         // the constant which would cause it to be modified for this
3666         // operation.
3667         //
3668         if (isValid && !isLeftShift && isSignedShift) {
3669           uint64_t Val = Op0C->getRawValue();
3670           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3671         }
3672         
3673         if (isValid) {
3674           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
3675           
3676           Instruction *NewShift =
3677             new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
3678                           Op0BO->getName());
3679           Op0BO->setName("");
3680           InsertNewInstBefore(NewShift, I);
3681           
3682           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3683                                         NewRHS);
3684         }
3685       }
3686     }
3687   }
3688   
3689   // Find out if this is a shift of a shift by a constant.
3690   ShiftInst *ShiftOp = 0;
3691   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
3692     ShiftOp = Op0SI;
3693   else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3694     // If this is a noop-integer case of a shift instruction, use the shift.
3695     if (CI->getOperand(0)->getType()->isInteger() &&
3696         CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3697         CI->getType()->getPrimitiveSizeInBits() &&
3698         isa<ShiftInst>(CI->getOperand(0))) {
3699       ShiftOp = cast<ShiftInst>(CI->getOperand(0));
3700     }
3701   }
3702   
3703   if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
3704     // Find the operands and properties of the input shift.  Note that the
3705     // signedness of the input shift may differ from the current shift if there
3706     // is a noop cast between the two.
3707     bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
3708     bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
3709     bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
3710     
3711     ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
3712
3713     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3714     unsigned ShiftAmt2 = (unsigned)Op1->getValue();
3715     
3716     // Check for (A << c1) << c2   and   (A >> c1) >> c2.
3717     if (isLeftShift == isShiftOfLeftShift) {
3718       // Do not fold these shifts if the first one is signed and the second one
3719       // is unsigned and this is a right shift.  Further, don't do any folding
3720       // on them.
3721       if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
3722         return 0;
3723       
3724       unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
3725       if (Amt > Op0->getType()->getPrimitiveSizeInBits())
3726         Amt = Op0->getType()->getPrimitiveSizeInBits();
3727       
3728       Value *Op = ShiftOp->getOperand(0);
3729       if (isShiftOfSignedShift != isSignedShift)
3730         Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
3731       return new ShiftInst(I.getOpcode(), Op,
3732                            ConstantUInt::get(Type::UByteTy, Amt));
3733     }
3734     
3735     // Check for (A << c1) >> c2 or (A >> c1) << c2.  If we are dealing with
3736     // signed types, we can only support the (A >> c1) << c2 configuration,
3737     // because it can not turn an arbitrary bit of A into a sign bit.
3738     if (isUnsignedShift || isLeftShift) {
3739       // Calculate bitmask for what gets shifted off the edge.
3740       Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
3741       if (isLeftShift)
3742         C = ConstantExpr::getShl(C, ShiftAmt1C);
3743       else
3744         C = ConstantExpr::getUShr(C, ShiftAmt1C);
3745       
3746       Value *Op = ShiftOp->getOperand(0);
3747       if (isShiftOfSignedShift != isSignedShift)
3748         Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
3749       
3750       Instruction *Mask =
3751         BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
3752       InsertNewInstBefore(Mask, I);
3753       
3754       // Figure out what flavor of shift we should use...
3755       if (ShiftAmt1 == ShiftAmt2) {
3756         return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
3757       } else if (ShiftAmt1 < ShiftAmt2) {
3758         return new ShiftInst(I.getOpcode(), Mask,
3759                          ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3760       } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
3761         if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
3762           // Make sure to emit an unsigned shift right, not a signed one.
3763           Mask = InsertNewInstBefore(new CastInst(Mask, 
3764                                         Mask->getType()->getUnsignedVersion(),
3765                                                   Op->getName()), I);
3766           Mask = new ShiftInst(Instruction::Shr, Mask,
3767                          ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3768           InsertNewInstBefore(Mask, I);
3769           return new CastInst(Mask, I.getType());
3770         } else {
3771           return new ShiftInst(ShiftOp->getOpcode(), Mask,
3772                     ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3773         }
3774       } else {
3775         // (X >>s C1) << C2  where C1 > C2  === (X >>s (C1-C2)) & mask
3776         Op = InsertNewInstBefore(new CastInst(Mask,
3777                                               I.getType()->getSignedVersion(),
3778                                               Mask->getName()), I);
3779         Instruction *Shift =
3780           new ShiftInst(ShiftOp->getOpcode(), Op,
3781                         ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3782         InsertNewInstBefore(Shift, I);
3783         
3784         C = ConstantIntegral::getAllOnesValue(Shift->getType());
3785         C = ConstantExpr::getShl(C, Op1);
3786         Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
3787         InsertNewInstBefore(Mask, I);
3788         return new CastInst(Mask, I.getType());
3789       }
3790     } else {
3791       // We can handle signed (X << C1) >>s C2 if it's a sign extend.  In
3792       // this case, C1 == C2 and C1 is 8, 16, or 32.
3793       if (ShiftAmt1 == ShiftAmt2) {
3794         const Type *SExtType = 0;
3795         switch (ShiftAmt1) {
3796         case 8 : SExtType = Type::SByteTy; break;
3797         case 16: SExtType = Type::ShortTy; break;
3798         case 32: SExtType = Type::IntTy; break;
3799         }
3800         
3801         if (SExtType) {
3802           Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
3803                                                SExtType, "sext");
3804           InsertNewInstBefore(NewTrunc, I);
3805           return new CastInst(NewTrunc, I.getType());
3806         }
3807       }
3808     }
3809   }
3810   return 0;
3811 }
3812
3813 enum CastType {
3814   Noop     = 0,
3815   Truncate = 1,
3816   Signext  = 2,
3817   Zeroext  = 3
3818 };
3819
3820 /// getCastType - In the future, we will split the cast instruction into these
3821 /// various types.  Until then, we have to do the analysis here.
3822 static CastType getCastType(const Type *Src, const Type *Dest) {
3823   assert(Src->isIntegral() && Dest->isIntegral() &&
3824          "Only works on integral types!");
3825   unsigned SrcSize = Src->getPrimitiveSizeInBits();
3826   unsigned DestSize = Dest->getPrimitiveSizeInBits();
3827
3828   if (SrcSize == DestSize) return Noop;
3829   if (SrcSize > DestSize)  return Truncate;
3830   if (Src->isSigned()) return Signext;
3831   return Zeroext;
3832 }
3833
3834
3835 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3836 // instruction.
3837 //
3838 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
3839                                    const Type *DstTy, TargetData *TD) {
3840
3841   // It is legal to eliminate the instruction if casting A->B->A if the sizes
3842   // are identical and the bits don't get reinterpreted (for example
3843   // int->float->int would not be allowed).
3844   if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
3845     return true;
3846
3847   // If we are casting between pointer and integer types, treat pointers as
3848   // integers of the appropriate size for the code below.
3849   if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3850   if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3851   if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
3852
3853   // Allow free casting and conversion of sizes as long as the sign doesn't
3854   // change...
3855   if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
3856     CastType FirstCast = getCastType(SrcTy, MidTy);
3857     CastType SecondCast = getCastType(MidTy, DstTy);
3858
3859     // Capture the effect of these two casts.  If the result is a legal cast,
3860     // the CastType is stored here, otherwise a special code is used.
3861     static const unsigned CastResult[] = {
3862       // First cast is noop
3863       0, 1, 2, 3,
3864       // First cast is a truncate
3865       1, 1, 4, 4,         // trunc->extend is not safe to eliminate
3866       // First cast is a sign ext
3867       2, 5, 2, 4,         // signext->zeroext never ok
3868       // First cast is a zero ext
3869       3, 5, 3, 3,
3870     };
3871
3872     unsigned Result = CastResult[FirstCast*4+SecondCast];
3873     switch (Result) {
3874     default: assert(0 && "Illegal table value!");
3875     case 0:
3876     case 1:
3877     case 2:
3878     case 3:
3879       // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3880       // truncates, we could eliminate more casts.
3881       return (unsigned)getCastType(SrcTy, DstTy) == Result;
3882     case 4:
3883       return false;  // Not possible to eliminate this here.
3884     case 5:
3885       // Sign or zero extend followed by truncate is always ok if the result
3886       // is a truncate or noop.
3887       CastType ResultCast = getCastType(SrcTy, DstTy);
3888       if (ResultCast == Noop || ResultCast == Truncate)
3889         return true;
3890       // Otherwise we are still growing the value, we are only safe if the
3891       // result will match the sign/zeroextendness of the result.
3892       return ResultCast == FirstCast;
3893     }
3894   }
3895   
3896   // If this is a cast from 'float -> double -> integer', cast from
3897   // 'float -> integer' directly, as the value isn't changed by the 
3898   // float->double conversion.
3899   if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
3900       DstTy->isIntegral() && 
3901       SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
3902     return true;
3903   
3904   return false;
3905 }
3906
3907 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
3908   if (V->getType() == Ty || isa<Constant>(V)) return false;
3909   if (const CastInst *CI = dyn_cast<CastInst>(V))
3910     if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3911                                TD))
3912       return false;
3913   return true;
3914 }
3915
3916 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3917 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
3918 /// casts that are known to not do anything...
3919 ///
3920 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3921                                              Instruction *InsertBefore) {
3922   if (V->getType() == DestTy) return V;
3923   if (Constant *C = dyn_cast<Constant>(V))
3924     return ConstantExpr::getCast(C, DestTy);
3925
3926   CastInst *CI = new CastInst(V, DestTy, V->getName());
3927   InsertNewInstBefore(CI, *InsertBefore);
3928   return CI;
3929 }
3930
3931 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
3932 /// expression.  If so, decompose it, returning some value X, such that Val is
3933 /// X*Scale+Offset.
3934 ///
3935 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
3936                                         unsigned &Offset) {
3937   assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
3938   if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
3939     Offset = CI->getValue();
3940     Scale  = 1;
3941     return ConstantUInt::get(Type::UIntTy, 0);
3942   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
3943     if (I->getNumOperands() == 2) {
3944       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
3945         if (I->getOpcode() == Instruction::Shl) {
3946           // This is a value scaled by '1 << the shift amt'.
3947           Scale = 1U << CUI->getValue();
3948           Offset = 0;
3949           return I->getOperand(0);
3950         } else if (I->getOpcode() == Instruction::Mul) {
3951           // This value is scaled by 'CUI'.
3952           Scale = CUI->getValue();
3953           Offset = 0;
3954           return I->getOperand(0);
3955         } else if (I->getOpcode() == Instruction::Add) {
3956           // We have X+C.  Check to see if we really have (X*C2)+C1, where C1 is
3957           // divisible by C2.
3958           unsigned SubScale;
3959           Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
3960                                                     Offset);
3961           Offset += CUI->getValue();
3962           if (SubScale > 1 && (Offset % SubScale == 0)) {
3963             Scale = SubScale;
3964             return SubVal;
3965           }
3966         }
3967       }
3968     }
3969   }
3970
3971   // Otherwise, we can't look past this.
3972   Scale = 1;
3973   Offset = 0;
3974   return Val;
3975 }
3976
3977
3978 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
3979 /// try to eliminate the cast by moving the type information into the alloc.
3980 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
3981                                                    AllocationInst &AI) {
3982   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
3983   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
3984   
3985   // Remove any uses of AI that are dead.
3986   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
3987   std::vector<Instruction*> DeadUsers;
3988   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
3989     Instruction *User = cast<Instruction>(*UI++);
3990     if (isInstructionTriviallyDead(User)) {
3991       while (UI != E && *UI == User)
3992         ++UI; // If this instruction uses AI more than once, don't break UI.
3993       
3994       // Add operands to the worklist.
3995       AddUsesToWorkList(*User);
3996       ++NumDeadInst;
3997       DEBUG(std::cerr << "IC: DCE: " << *User);
3998       
3999       User->eraseFromParent();
4000       removeFromWorkList(User);
4001     }
4002   }
4003   
4004   // Get the type really allocated and the type casted to.
4005   const Type *AllocElTy = AI.getAllocatedType();
4006   const Type *CastElTy = PTy->getElementType();
4007   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
4008
4009   unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4010   unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4011   if (CastElTyAlign < AllocElTyAlign) return 0;
4012
4013   // If the allocation has multiple uses, only promote it if we are strictly
4014   // increasing the alignment of the resultant allocation.  If we keep it the
4015   // same, we open the door to infinite loops of various kinds.
4016   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4017
4018   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4019   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
4020   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
4021
4022   // See if we can satisfy the modulus by pulling a scale out of the array
4023   // size argument.
4024   unsigned ArraySizeScale, ArrayOffset;
4025   Value *NumElements = // See if the array size is a decomposable linear expr.
4026     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4027  
4028   // If we can now satisfy the modulus, by using a non-1 scale, we really can
4029   // do the xform.
4030   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4031       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
4032
4033   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4034   Value *Amt = 0;
4035   if (Scale == 1) {
4036     Amt = NumElements;
4037   } else {
4038     Amt = ConstantUInt::get(Type::UIntTy, Scale);
4039     if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4040       Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4041     else if (Scale != 1) {
4042       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4043       Amt = InsertNewInstBefore(Tmp, AI);
4044     }
4045   }
4046   
4047   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4048     Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4049     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4050     Amt = InsertNewInstBefore(Tmp, AI);
4051   }
4052   
4053   std::string Name = AI.getName(); AI.setName("");
4054   AllocationInst *New;
4055   if (isa<MallocInst>(AI))
4056     New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
4057   else
4058     New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
4059   InsertNewInstBefore(New, AI);
4060   
4061   // If the allocation has multiple uses, insert a cast and change all things
4062   // that used it to use the new cast.  This will also hack on CI, but it will
4063   // die soon.
4064   if (!AI.hasOneUse()) {
4065     AddUsesToWorkList(AI);
4066     CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4067     InsertNewInstBefore(NewCast, AI);
4068     AI.replaceAllUsesWith(NewCast);
4069   }
4070   return ReplaceInstUsesWith(CI, New);
4071 }
4072
4073
4074 // CastInst simplification
4075 //
4076 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
4077   Value *Src = CI.getOperand(0);
4078
4079   // If the user is casting a value to the same type, eliminate this cast
4080   // instruction...
4081   if (CI.getType() == Src->getType())
4082     return ReplaceInstUsesWith(CI, Src);
4083
4084   if (isa<UndefValue>(Src))   // cast undef -> undef
4085     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4086
4087   // If casting the result of another cast instruction, try to eliminate this
4088   // one!
4089   //
4090   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
4091     Value *A = CSrc->getOperand(0);
4092     if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4093                                CI.getType(), TD)) {
4094       // This instruction now refers directly to the cast's src operand.  This
4095       // has a good chance of making CSrc dead.
4096       CI.setOperand(0, CSrc->getOperand(0));
4097       return &CI;
4098     }
4099
4100     // If this is an A->B->A cast, and we are dealing with integral types, try
4101     // to convert this into a logical 'and' instruction.
4102     //
4103     if (A->getType()->isInteger() &&
4104         CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
4105         CSrc->getType()->isUnsigned() &&   // B->A cast must zero extend
4106         CSrc->getType()->getPrimitiveSizeInBits() <
4107                     CI.getType()->getPrimitiveSizeInBits()&&
4108         A->getType()->getPrimitiveSizeInBits() ==
4109               CI.getType()->getPrimitiveSizeInBits()) {
4110       assert(CSrc->getType() != Type::ULongTy &&
4111              "Cannot have type bigger than ulong!");
4112       uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
4113       Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4114                                           AndValue);
4115       AndOp = ConstantExpr::getCast(AndOp, A->getType());
4116       Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4117       if (And->getType() != CI.getType()) {
4118         And->setName(CSrc->getName()+".mask");
4119         InsertNewInstBefore(And, CI);
4120         And = new CastInst(And, CI.getType());
4121       }
4122       return And;
4123     }
4124   }
4125
4126   // If this is a cast to bool, turn it into the appropriate setne instruction.
4127   if (CI.getType() == Type::BoolTy)
4128     return BinaryOperator::createSetNE(CI.getOperand(0),
4129                        Constant::getNullValue(CI.getOperand(0)->getType()));
4130
4131   // If casting the result of a getelementptr instruction with no offset, turn
4132   // this into a cast of the original pointer!
4133   //
4134   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
4135     bool AllZeroOperands = true;
4136     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4137       if (!isa<Constant>(GEP->getOperand(i)) ||
4138           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4139         AllZeroOperands = false;
4140         break;
4141       }
4142     if (AllZeroOperands) {
4143       CI.setOperand(0, GEP->getOperand(0));
4144       return &CI;
4145     }
4146   }
4147
4148   // If we are casting a malloc or alloca to a pointer to a type of the same
4149   // size, rewrite the allocation instruction to allocate the "right" type.
4150   //
4151   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
4152     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4153       return V;
4154
4155   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4156     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4157       return NV;
4158   if (isa<PHINode>(Src))
4159     if (Instruction *NV = FoldOpIntoPhi(CI))
4160       return NV;
4161
4162   // If the source value is an instruction with only this use, we can attempt to
4163   // propagate the cast into the instruction.  Also, only handle integral types
4164   // for now.
4165   if (Instruction *SrcI = dyn_cast<Instruction>(Src))
4166     if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
4167         CI.getType()->isInteger()) {  // Don't mess with casts to bool here
4168       const Type *DestTy = CI.getType();
4169       unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4170       unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
4171
4172       Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4173       Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4174
4175       switch (SrcI->getOpcode()) {
4176       case Instruction::Add:
4177       case Instruction::Mul:
4178       case Instruction::And:
4179       case Instruction::Or:
4180       case Instruction::Xor:
4181         // If we are discarding information, or just changing the sign, rewrite.
4182         if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4183           // Don't insert two casts if they cannot be eliminated.  We allow two
4184           // casts to be inserted if the sizes are the same.  This could only be
4185           // converting signedness, which is a noop.
4186           if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4187               !ValueRequiresCast(Op0, DestTy, TD)) {
4188             Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4189             Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4190             return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4191                              ->getOpcode(), Op0c, Op1c);
4192           }
4193         }
4194
4195         // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
4196         if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4197             Op1 == ConstantBool::True &&
4198             (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4199           Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4200           return BinaryOperator::createXor(New,
4201                                            ConstantInt::get(CI.getType(), 1));
4202         }
4203         break;
4204       case Instruction::Shl:
4205         // Allow changing the sign of the source operand.  Do not allow changing
4206         // the size of the shift, UNLESS the shift amount is a constant.  We
4207         // mush not change variable sized shifts to a smaller size, because it
4208         // is undefined to shift more bits out than exist in the value.
4209         if (DestBitSize == SrcBitSize ||
4210             (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4211           Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4212           return new ShiftInst(Instruction::Shl, Op0c, Op1);
4213         }
4214         break;
4215       case Instruction::Shr:
4216         // If this is a signed shr, and if all bits shifted in are about to be
4217         // truncated off, turn it into an unsigned shr to allow greater
4218         // simplifications.
4219         if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4220             isa<ConstantInt>(Op1)) {
4221           unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4222           if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4223             // Convert to unsigned.
4224             Value *N1 = InsertOperandCastBefore(Op0,
4225                                      Op0->getType()->getUnsignedVersion(), &CI);
4226             // Insert the new shift, which is now unsigned.
4227             N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4228                                                    Op1, Src->getName()), CI);
4229             return new CastInst(N1, CI.getType());
4230           }
4231         }
4232         break;
4233
4234       case Instruction::SetNE:
4235         if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4236           if (Op1C->getRawValue() == 0) {
4237             // If the input only has the low bit set, simplify directly.
4238             Constant *Not1 =
4239               ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
4240             // cast (X != 0) to int  --> X if X&~1 == 0
4241             if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4242               if (CI.getType() == Op0->getType())
4243                 return ReplaceInstUsesWith(CI, Op0);
4244               else
4245                 return new CastInst(Op0, CI.getType());
4246             }
4247
4248             // If the input is an and with a single bit, shift then simplify.
4249             ConstantInt *AndRHS;
4250             if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4251               if (AndRHS->getRawValue() &&
4252                   (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
4253                 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
4254                 // Perform an unsigned shr by shiftamt.  Convert input to
4255                 // unsigned if it is signed.
4256                 Value *In = Op0;
4257                 if (In->getType()->isSigned())
4258                   In = InsertNewInstBefore(new CastInst(In,
4259                         In->getType()->getUnsignedVersion(), In->getName()),CI);
4260                 // Insert the shift to put the result in the low bit.
4261                 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4262                                       ConstantInt::get(Type::UByteTy, ShiftAmt),
4263                                                    In->getName()+".lobit"), CI);
4264                 if (CI.getType() == In->getType())
4265                   return ReplaceInstUsesWith(CI, In);
4266                 else
4267                   return new CastInst(In, CI.getType());
4268               }
4269           }
4270         }
4271         break;
4272       case Instruction::SetEQ:
4273         // We if we are just checking for a seteq of a single bit and casting it
4274         // to an integer.  If so, shift the bit to the appropriate place then
4275         // cast to integer to avoid the comparison.
4276         if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4277           // Is Op1C a power of two or zero?
4278           if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4279             // cast (X == 1) to int -> X iff X has only the low bit set.
4280             if (Op1C->getRawValue() == 1) {
4281               Constant *Not1 =
4282                 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
4283               if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4284                 if (CI.getType() == Op0->getType())
4285                   return ReplaceInstUsesWith(CI, Op0);
4286                 else
4287                   return new CastInst(Op0, CI.getType());
4288               }
4289             }
4290           }
4291         }
4292         break;
4293       }
4294     }
4295       
4296   return 0;
4297 }
4298
4299 /// GetSelectFoldableOperands - We want to turn code that looks like this:
4300 ///   %C = or %A, %B
4301 ///   %D = select %cond, %C, %A
4302 /// into:
4303 ///   %C = select %cond, %B, 0
4304 ///   %D = or %A, %C
4305 ///
4306 /// Assuming that the specified instruction is an operand to the select, return
4307 /// a bitmask indicating which operands of this instruction are foldable if they
4308 /// equal the other incoming value of the select.
4309 ///
4310 static unsigned GetSelectFoldableOperands(Instruction *I) {
4311   switch (I->getOpcode()) {
4312   case Instruction::Add:
4313   case Instruction::Mul:
4314   case Instruction::And:
4315   case Instruction::Or:
4316   case Instruction::Xor:
4317     return 3;              // Can fold through either operand.
4318   case Instruction::Sub:   // Can only fold on the amount subtracted.
4319   case Instruction::Shl:   // Can only fold on the shift amount.
4320   case Instruction::Shr:
4321     return 1;
4322   default:
4323     return 0;              // Cannot fold
4324   }
4325 }
4326
4327 /// GetSelectFoldableConstant - For the same transformation as the previous
4328 /// function, return the identity constant that goes into the select.
4329 static Constant *GetSelectFoldableConstant(Instruction *I) {
4330   switch (I->getOpcode()) {
4331   default: assert(0 && "This cannot happen!"); abort();
4332   case Instruction::Add:
4333   case Instruction::Sub:
4334   case Instruction::Or:
4335   case Instruction::Xor:
4336     return Constant::getNullValue(I->getType());
4337   case Instruction::Shl:
4338   case Instruction::Shr:
4339     return Constant::getNullValue(Type::UByteTy);
4340   case Instruction::And:
4341     return ConstantInt::getAllOnesValue(I->getType());
4342   case Instruction::Mul:
4343     return ConstantInt::get(I->getType(), 1);
4344   }
4345 }
4346
4347 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4348 /// have the same opcode and only one use each.  Try to simplify this.
4349 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4350                                           Instruction *FI) {
4351   if (TI->getNumOperands() == 1) {
4352     // If this is a non-volatile load or a cast from the same type,
4353     // merge.
4354     if (TI->getOpcode() == Instruction::Cast) {
4355       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4356         return 0;
4357     } else {
4358       return 0;  // unknown unary op.
4359     }
4360
4361     // Fold this by inserting a select from the input values.
4362     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4363                                        FI->getOperand(0), SI.getName()+".v");
4364     InsertNewInstBefore(NewSI, SI);
4365     return new CastInst(NewSI, TI->getType());
4366   }
4367
4368   // Only handle binary operators here.
4369   if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4370     return 0;
4371
4372   // Figure out if the operations have any operands in common.
4373   Value *MatchOp, *OtherOpT, *OtherOpF;
4374   bool MatchIsOpZero;
4375   if (TI->getOperand(0) == FI->getOperand(0)) {
4376     MatchOp  = TI->getOperand(0);
4377     OtherOpT = TI->getOperand(1);
4378     OtherOpF = FI->getOperand(1);
4379     MatchIsOpZero = true;
4380   } else if (TI->getOperand(1) == FI->getOperand(1)) {
4381     MatchOp  = TI->getOperand(1);
4382     OtherOpT = TI->getOperand(0);
4383     OtherOpF = FI->getOperand(0);
4384     MatchIsOpZero = false;
4385   } else if (!TI->isCommutative()) {
4386     return 0;
4387   } else if (TI->getOperand(0) == FI->getOperand(1)) {
4388     MatchOp  = TI->getOperand(0);
4389     OtherOpT = TI->getOperand(1);
4390     OtherOpF = FI->getOperand(0);
4391     MatchIsOpZero = true;
4392   } else if (TI->getOperand(1) == FI->getOperand(0)) {
4393     MatchOp  = TI->getOperand(1);
4394     OtherOpT = TI->getOperand(0);
4395     OtherOpF = FI->getOperand(1);
4396     MatchIsOpZero = true;
4397   } else {
4398     return 0;
4399   }
4400
4401   // If we reach here, they do have operations in common.
4402   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4403                                      OtherOpF, SI.getName()+".v");
4404   InsertNewInstBefore(NewSI, SI);
4405
4406   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4407     if (MatchIsOpZero)
4408       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4409     else
4410       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4411   } else {
4412     if (MatchIsOpZero)
4413       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4414     else
4415       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4416   }
4417 }
4418
4419 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
4420   Value *CondVal = SI.getCondition();
4421   Value *TrueVal = SI.getTrueValue();
4422   Value *FalseVal = SI.getFalseValue();
4423
4424   // select true, X, Y  -> X
4425   // select false, X, Y -> Y
4426   if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
4427     if (C == ConstantBool::True)
4428       return ReplaceInstUsesWith(SI, TrueVal);
4429     else {
4430       assert(C == ConstantBool::False);
4431       return ReplaceInstUsesWith(SI, FalseVal);
4432     }
4433
4434   // select C, X, X -> X
4435   if (TrueVal == FalseVal)
4436     return ReplaceInstUsesWith(SI, TrueVal);
4437
4438   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
4439     return ReplaceInstUsesWith(SI, FalseVal);
4440   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
4441     return ReplaceInstUsesWith(SI, TrueVal);
4442   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
4443     if (isa<Constant>(TrueVal))
4444       return ReplaceInstUsesWith(SI, TrueVal);
4445     else
4446       return ReplaceInstUsesWith(SI, FalseVal);
4447   }
4448
4449   if (SI.getType() == Type::BoolTy)
4450     if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4451       if (C == ConstantBool::True) {
4452         // Change: A = select B, true, C --> A = or B, C
4453         return BinaryOperator::createOr(CondVal, FalseVal);
4454       } else {
4455         // Change: A = select B, false, C --> A = and !B, C
4456         Value *NotCond =
4457           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4458                                              "not."+CondVal->getName()), SI);
4459         return BinaryOperator::createAnd(NotCond, FalseVal);
4460       }
4461     } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4462       if (C == ConstantBool::False) {
4463         // Change: A = select B, C, false --> A = and B, C
4464         return BinaryOperator::createAnd(CondVal, TrueVal);
4465       } else {
4466         // Change: A = select B, C, true --> A = or !B, C
4467         Value *NotCond =
4468           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4469                                              "not."+CondVal->getName()), SI);
4470         return BinaryOperator::createOr(NotCond, TrueVal);
4471       }
4472     }
4473
4474   // Selecting between two integer constants?
4475   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4476     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4477       // select C, 1, 0 -> cast C to int
4478       if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4479         return new CastInst(CondVal, SI.getType());
4480       } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4481         // select C, 0, 1 -> cast !C to int
4482         Value *NotCond =
4483           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4484                                                "not."+CondVal->getName()), SI);
4485         return new CastInst(NotCond, SI.getType());
4486       }
4487
4488       // If one of the constants is zero (we know they can't both be) and we
4489       // have a setcc instruction with zero, and we have an 'and' with the
4490       // non-constant value, eliminate this whole mess.  This corresponds to
4491       // cases like this: ((X & 27) ? 27 : 0)
4492       if (TrueValC->isNullValue() || FalseValC->isNullValue())
4493         if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4494           if ((IC->getOpcode() == Instruction::SetEQ ||
4495                IC->getOpcode() == Instruction::SetNE) &&
4496               isa<ConstantInt>(IC->getOperand(1)) &&
4497               cast<Constant>(IC->getOperand(1))->isNullValue())
4498             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4499               if (ICA->getOpcode() == Instruction::And &&
4500                   isa<ConstantInt>(ICA->getOperand(1)) &&
4501                   (ICA->getOperand(1) == TrueValC ||
4502                    ICA->getOperand(1) == FalseValC) &&
4503                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4504                 // Okay, now we know that everything is set up, we just don't
4505                 // know whether we have a setne or seteq and whether the true or
4506                 // false val is the zero.
4507                 bool ShouldNotVal = !TrueValC->isNullValue();
4508                 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4509                 Value *V = ICA;
4510                 if (ShouldNotVal)
4511                   V = InsertNewInstBefore(BinaryOperator::create(
4512                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
4513                 return ReplaceInstUsesWith(SI, V);
4514               }
4515     }
4516
4517   // See if we are selecting two values based on a comparison of the two values.
4518   if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4519     if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4520       // Transform (X == Y) ? X : Y  -> Y
4521       if (SCI->getOpcode() == Instruction::SetEQ)
4522         return ReplaceInstUsesWith(SI, FalseVal);
4523       // Transform (X != Y) ? X : Y  -> X
4524       if (SCI->getOpcode() == Instruction::SetNE)
4525         return ReplaceInstUsesWith(SI, TrueVal);
4526       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4527
4528     } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4529       // Transform (X == Y) ? Y : X  -> X
4530       if (SCI->getOpcode() == Instruction::SetEQ)
4531         return ReplaceInstUsesWith(SI, FalseVal);
4532       // Transform (X != Y) ? Y : X  -> Y
4533       if (SCI->getOpcode() == Instruction::SetNE)
4534         return ReplaceInstUsesWith(SI, TrueVal);
4535       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4536     }
4537   }
4538
4539   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4540     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4541       if (TI->hasOneUse() && FI->hasOneUse()) {
4542         bool isInverse = false;
4543         Instruction *AddOp = 0, *SubOp = 0;
4544
4545         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4546         if (TI->getOpcode() == FI->getOpcode())
4547           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4548             return IV;
4549
4550         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
4551         // even legal for FP.
4552         if (TI->getOpcode() == Instruction::Sub &&
4553             FI->getOpcode() == Instruction::Add) {
4554           AddOp = FI; SubOp = TI;
4555         } else if (FI->getOpcode() == Instruction::Sub &&
4556                    TI->getOpcode() == Instruction::Add) {
4557           AddOp = TI; SubOp = FI;
4558         }
4559
4560         if (AddOp) {
4561           Value *OtherAddOp = 0;
4562           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4563             OtherAddOp = AddOp->getOperand(1);
4564           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4565             OtherAddOp = AddOp->getOperand(0);
4566           }
4567
4568           if (OtherAddOp) {
4569             // So at this point we know we have:
4570             //        select C, (add X, Y), (sub X, ?)
4571             // We can do the transform profitably if either 'Y' = '?' or '?' is
4572             // a constant.
4573             if (SubOp->getOperand(1) == AddOp ||
4574                 isa<Constant>(SubOp->getOperand(1))) {
4575               Value *NegVal;
4576               if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4577                 NegVal = ConstantExpr::getNeg(C);
4578               } else {
4579                 NegVal = InsertNewInstBefore(
4580                            BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4581               }
4582
4583               Value *NewTrueOp = OtherAddOp;
4584               Value *NewFalseOp = NegVal;
4585               if (AddOp != TI)
4586                 std::swap(NewTrueOp, NewFalseOp);
4587               Instruction *NewSel =
4588                 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
4589
4590               NewSel = InsertNewInstBefore(NewSel, SI);
4591               return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
4592             }
4593           }
4594         }
4595       }
4596
4597   // See if we can fold the select into one of our operands.
4598   if (SI.getType()->isInteger()) {
4599     // See the comment above GetSelectFoldableOperands for a description of the
4600     // transformation we are doing here.
4601     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4602       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4603           !isa<Constant>(FalseVal))
4604         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4605           unsigned OpToFold = 0;
4606           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4607             OpToFold = 1;
4608           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4609             OpToFold = 2;
4610           }
4611
4612           if (OpToFold) {
4613             Constant *C = GetSelectFoldableConstant(TVI);
4614             std::string Name = TVI->getName(); TVI->setName("");
4615             Instruction *NewSel =
4616               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4617                              Name);
4618             InsertNewInstBefore(NewSel, SI);
4619             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4620               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4621             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4622               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4623             else {
4624               assert(0 && "Unknown instruction!!");
4625             }
4626           }
4627         }
4628
4629     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4630       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4631           !isa<Constant>(TrueVal))
4632         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4633           unsigned OpToFold = 0;
4634           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4635             OpToFold = 1;
4636           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4637             OpToFold = 2;
4638           }
4639
4640           if (OpToFold) {
4641             Constant *C = GetSelectFoldableConstant(FVI);
4642             std::string Name = FVI->getName(); FVI->setName("");
4643             Instruction *NewSel =
4644               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4645                              Name);
4646             InsertNewInstBefore(NewSel, SI);
4647             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4648               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4649             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4650               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4651             else {
4652               assert(0 && "Unknown instruction!!");
4653             }
4654           }
4655         }
4656   }
4657
4658   if (BinaryOperator::isNot(CondVal)) {
4659     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4660     SI.setOperand(1, FalseVal);
4661     SI.setOperand(2, TrueVal);
4662     return &SI;
4663   }
4664
4665   return 0;
4666 }
4667
4668
4669 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
4670 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
4671 /// the heavy lifting.
4672 ///
4673 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
4674   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
4675   if (!II) return visitCallSite(&CI);
4676   
4677   // Intrinsics cannot occur in an invoke, so handle them here instead of in
4678   // visitCallSite.
4679   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
4680     bool Changed = false;
4681
4682     // memmove/cpy/set of zero bytes is a noop.
4683     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4684       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4685
4686       // FIXME: Increase alignment here.
4687
4688       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4689         if (CI->getRawValue() == 1) {
4690           // Replace the instruction with just byte operations.  We would
4691           // transform other cases to loads/stores, but we don't know if
4692           // alignment is sufficient.
4693         }
4694     }
4695
4696     // If we have a memmove and the source operation is a constant global,
4697     // then the source and dest pointers can't alias, so we can change this
4698     // into a call to memcpy.
4699     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II))
4700       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4701         if (GVSrc->isConstant()) {
4702           Module *M = CI.getParent()->getParent()->getParent();
4703           Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4704                                      CI.getCalledFunction()->getFunctionType());
4705           CI.setOperand(0, MemCpy);
4706           Changed = true;
4707         }
4708
4709     if (Changed) return II;
4710   } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(II)) {
4711     // If this stoppoint is at the same source location as the previous
4712     // stoppoint in the chain, it is not needed.
4713     if (DbgStopPointInst *PrevSPI =
4714         dyn_cast<DbgStopPointInst>(SPI->getChain()))
4715       if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4716           SPI->getColNo() == PrevSPI->getColNo()) {
4717         SPI->replaceAllUsesWith(PrevSPI);
4718         return EraseInstFromFunction(CI);
4719       }
4720   } else {
4721     switch (II->getIntrinsicID()) {
4722     default: break;
4723     case Intrinsic::stackrestore: {
4724       // If the save is right next to the restore, remove the restore.  This can
4725       // happen when variable allocas are DCE'd.
4726       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
4727         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
4728           BasicBlock::iterator BI = SS;
4729           if (&*++BI == II)
4730             return EraseInstFromFunction(CI);
4731         }
4732       }
4733       
4734       // If the stack restore is in a return/unwind block and if there are no
4735       // allocas or calls between the restore and the return, nuke the restore.
4736       TerminatorInst *TI = II->getParent()->getTerminator();
4737       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
4738         BasicBlock::iterator BI = II;
4739         bool CannotRemove = false;
4740         for (++BI; &*BI != TI; ++BI) {
4741           if (isa<AllocaInst>(BI) ||
4742               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
4743             CannotRemove = true;
4744             break;
4745           }
4746         }
4747         if (!CannotRemove)
4748           return EraseInstFromFunction(CI);
4749       }
4750       break;
4751     }
4752     }
4753   }
4754
4755   return visitCallSite(II);
4756 }
4757
4758 // InvokeInst simplification
4759 //
4760 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
4761   return visitCallSite(&II);
4762 }
4763
4764 // visitCallSite - Improvements for call and invoke instructions.
4765 //
4766 Instruction *InstCombiner::visitCallSite(CallSite CS) {
4767   bool Changed = false;
4768
4769   // If the callee is a constexpr cast of a function, attempt to move the cast
4770   // to the arguments of the call/invoke.
4771   if (transformConstExprCastCall(CS)) return 0;
4772
4773   Value *Callee = CS.getCalledValue();
4774
4775   if (Function *CalleeF = dyn_cast<Function>(Callee))
4776     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4777       Instruction *OldCall = CS.getInstruction();
4778       // If the call and callee calling conventions don't match, this call must
4779       // be unreachable, as the call is undefined.
4780       new StoreInst(ConstantBool::True,
4781                     UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4782       if (!OldCall->use_empty())
4783         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4784       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
4785         return EraseInstFromFunction(*OldCall);
4786       return 0;
4787     }
4788
4789   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4790     // This instruction is not reachable, just remove it.  We insert a store to
4791     // undef so that we know that this code is not reachable, despite the fact
4792     // that we can't modify the CFG here.
4793     new StoreInst(ConstantBool::True,
4794                   UndefValue::get(PointerType::get(Type::BoolTy)),
4795                   CS.getInstruction());
4796
4797     if (!CS.getInstruction()->use_empty())
4798       CS.getInstruction()->
4799         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4800
4801     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4802       // Don't break the CFG, insert a dummy cond branch.
4803       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4804                      ConstantBool::True, II);
4805     }
4806     return EraseInstFromFunction(*CS.getInstruction());
4807   }
4808
4809   const PointerType *PTy = cast<PointerType>(Callee->getType());
4810   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4811   if (FTy->isVarArg()) {
4812     // See if we can optimize any arguments passed through the varargs area of
4813     // the call.
4814     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4815            E = CS.arg_end(); I != E; ++I)
4816       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4817         // If this cast does not effect the value passed through the varargs
4818         // area, we can eliminate the use of the cast.
4819         Value *Op = CI->getOperand(0);
4820         if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4821           *I = Op;
4822           Changed = true;
4823         }
4824       }
4825   }
4826
4827   return Changed ? CS.getInstruction() : 0;
4828 }
4829
4830 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
4831 // attempt to move the cast to the arguments of the call/invoke.
4832 //
4833 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4834   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4835   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
4836   if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
4837     return false;
4838   Function *Callee = cast<Function>(CE->getOperand(0));
4839   Instruction *Caller = CS.getInstruction();
4840
4841   // Okay, this is a cast from a function to a different type.  Unless doing so
4842   // would cause a type conversion of one of our arguments, change this call to
4843   // be a direct call with arguments casted to the appropriate types.
4844   //
4845   const FunctionType *FT = Callee->getFunctionType();
4846   const Type *OldRetTy = Caller->getType();
4847
4848   // Check to see if we are changing the return type...
4849   if (OldRetTy != FT->getReturnType()) {
4850     if (Callee->isExternal() &&
4851         !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4852         !Caller->use_empty())
4853       return false;   // Cannot transform this return value...
4854
4855     // If the callsite is an invoke instruction, and the return value is used by
4856     // a PHI node in a successor, we cannot change the return type of the call
4857     // because there is no place to put the cast instruction (without breaking
4858     // the critical edge).  Bail out in this case.
4859     if (!Caller->use_empty())
4860       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4861         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4862              UI != E; ++UI)
4863           if (PHINode *PN = dyn_cast<PHINode>(*UI))
4864             if (PN->getParent() == II->getNormalDest() ||
4865                 PN->getParent() == II->getUnwindDest())
4866               return false;
4867   }
4868
4869   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4870   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4871
4872   CallSite::arg_iterator AI = CS.arg_begin();
4873   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4874     const Type *ParamTy = FT->getParamType(i);
4875     bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
4876     if (Callee->isExternal() && !isConvertible) return false;
4877   }
4878
4879   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4880       Callee->isExternal())
4881     return false;   // Do not delete arguments unless we have a function body...
4882
4883   // Okay, we decided that this is a safe thing to do: go ahead and start
4884   // inserting cast instructions as necessary...
4885   std::vector<Value*> Args;
4886   Args.reserve(NumActualArgs);
4887
4888   AI = CS.arg_begin();
4889   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4890     const Type *ParamTy = FT->getParamType(i);
4891     if ((*AI)->getType() == ParamTy) {
4892       Args.push_back(*AI);
4893     } else {
4894       Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4895                                          *Caller));
4896     }
4897   }
4898
4899   // If the function takes more arguments than the call was taking, add them
4900   // now...
4901   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4902     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4903
4904   // If we are removing arguments to the function, emit an obnoxious warning...
4905   if (FT->getNumParams() < NumActualArgs)
4906     if (!FT->isVarArg()) {
4907       std::cerr << "WARNING: While resolving call to function '"
4908                 << Callee->getName() << "' arguments were dropped!\n";
4909     } else {
4910       // Add all of the arguments in their promoted form to the arg list...
4911       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4912         const Type *PTy = getPromotedType((*AI)->getType());
4913         if (PTy != (*AI)->getType()) {
4914           // Must promote to pass through va_arg area!
4915           Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4916           InsertNewInstBefore(Cast, *Caller);
4917           Args.push_back(Cast);
4918         } else {
4919           Args.push_back(*AI);
4920         }
4921       }
4922     }
4923
4924   if (FT->getReturnType() == Type::VoidTy)
4925     Caller->setName("");   // Void type should not have a name...
4926
4927   Instruction *NC;
4928   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4929     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
4930                         Args, Caller->getName(), Caller);
4931     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
4932   } else {
4933     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
4934     if (cast<CallInst>(Caller)->isTailCall())
4935       cast<CallInst>(NC)->setTailCall();
4936    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
4937   }
4938
4939   // Insert a cast of the return type as necessary...
4940   Value *NV = NC;
4941   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4942     if (NV->getType() != Type::VoidTy) {
4943       NV = NC = new CastInst(NC, Caller->getType(), "tmp");
4944
4945       // If this is an invoke instruction, we should insert it after the first
4946       // non-phi, instruction in the normal successor block.
4947       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4948         BasicBlock::iterator I = II->getNormalDest()->begin();
4949         while (isa<PHINode>(I)) ++I;
4950         InsertNewInstBefore(NC, *I);
4951       } else {
4952         // Otherwise, it's a call, just insert cast right after the call instr
4953         InsertNewInstBefore(NC, *Caller);
4954       }
4955       AddUsersToWorkList(*Caller);
4956     } else {
4957       NV = UndefValue::get(Caller->getType());
4958     }
4959   }
4960
4961   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4962     Caller->replaceAllUsesWith(NV);
4963   Caller->getParent()->getInstList().erase(Caller);
4964   removeFromWorkList(Caller);
4965   return true;
4966 }
4967
4968
4969 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4970 // operator and they all are only used by the PHI, PHI together their
4971 // inputs, and do the operation once, to the result of the PHI.
4972 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4973   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4974
4975   // Scan the instruction, looking for input operations that can be folded away.
4976   // If all input operands to the phi are the same instruction (e.g. a cast from
4977   // the same type or "+42") we can pull the operation through the PHI, reducing
4978   // code size and simplifying code.
4979   Constant *ConstantOp = 0;
4980   const Type *CastSrcTy = 0;
4981   if (isa<CastInst>(FirstInst)) {
4982     CastSrcTy = FirstInst->getOperand(0)->getType();
4983   } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4984     // Can fold binop or shift if the RHS is a constant.
4985     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4986     if (ConstantOp == 0) return 0;
4987   } else {
4988     return 0;  // Cannot fold this operation.
4989   }
4990
4991   // Check to see if all arguments are the same operation.
4992   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4993     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4994     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4995     if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4996       return 0;
4997     if (CastSrcTy) {
4998       if (I->getOperand(0)->getType() != CastSrcTy)
4999         return 0;  // Cast operation must match.
5000     } else if (I->getOperand(1) != ConstantOp) {
5001       return 0;
5002     }
5003   }
5004
5005   // Okay, they are all the same operation.  Create a new PHI node of the
5006   // correct type, and PHI together all of the LHS's of the instructions.
5007   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5008                                PN.getName()+".in");
5009   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
5010
5011   Value *InVal = FirstInst->getOperand(0);
5012   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
5013
5014   // Add all operands to the new PHI.
5015   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5016     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5017     if (NewInVal != InVal)
5018       InVal = 0;
5019     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5020   }
5021
5022   Value *PhiVal;
5023   if (InVal) {
5024     // The new PHI unions all of the same values together.  This is really
5025     // common, so we handle it intelligently here for compile-time speed.
5026     PhiVal = InVal;
5027     delete NewPN;
5028   } else {
5029     InsertNewInstBefore(NewPN, PN);
5030     PhiVal = NewPN;
5031   }
5032
5033   // Insert and return the new operation.
5034   if (isa<CastInst>(FirstInst))
5035     return new CastInst(PhiVal, PN.getType());
5036   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
5037     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
5038   else
5039     return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
5040                          PhiVal, ConstantOp);
5041 }
5042
5043 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5044 /// that is dead.
5045 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5046   if (PN->use_empty()) return true;
5047   if (!PN->hasOneUse()) return false;
5048
5049   // Remember this node, and if we find the cycle, return.
5050   if (!PotentiallyDeadPHIs.insert(PN).second)
5051     return true;
5052
5053   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5054     return DeadPHICycle(PU, PotentiallyDeadPHIs);
5055
5056   return false;
5057 }
5058
5059 // PHINode simplification
5060 //
5061 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
5062   if (Value *V = PN.hasConstantValue())
5063     return ReplaceInstUsesWith(PN, V);
5064
5065   // If the only user of this instruction is a cast instruction, and all of the
5066   // incoming values are constants, change this PHI to merge together the casted
5067   // constants.
5068   if (PN.hasOneUse())
5069     if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5070       if (CI->getType() != PN.getType()) {  // noop casts will be folded
5071         bool AllConstant = true;
5072         for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5073           if (!isa<Constant>(PN.getIncomingValue(i))) {
5074             AllConstant = false;
5075             break;
5076           }
5077         if (AllConstant) {
5078           // Make a new PHI with all casted values.
5079           PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5080           for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5081             Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5082             New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5083                              PN.getIncomingBlock(i));
5084           }
5085
5086           // Update the cast instruction.
5087           CI->setOperand(0, New);
5088           WorkList.push_back(CI);    // revisit the cast instruction to fold.
5089           WorkList.push_back(New);   // Make sure to revisit the new Phi
5090           return &PN;                // PN is now dead!
5091         }
5092       }
5093
5094   // If all PHI operands are the same operation, pull them through the PHI,
5095   // reducing code size.
5096   if (isa<Instruction>(PN.getIncomingValue(0)) &&
5097       PN.getIncomingValue(0)->hasOneUse())
5098     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5099       return Result;
5100
5101   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
5102   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5103   // PHI)... break the cycle.
5104   if (PN.hasOneUse())
5105     if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5106       std::set<PHINode*> PotentiallyDeadPHIs;
5107       PotentiallyDeadPHIs.insert(&PN);
5108       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5109         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5110     }
5111
5112   return 0;
5113 }
5114
5115 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5116                                       Instruction *InsertPoint,
5117                                       InstCombiner *IC) {
5118   unsigned PS = IC->getTargetData().getPointerSize();
5119   const Type *VTy = V->getType();
5120   if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5121     // We must insert a cast to ensure we sign-extend.
5122     V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5123                                              V->getName()), *InsertPoint);
5124   return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5125                                  *InsertPoint);
5126 }
5127
5128
5129 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
5130   Value *PtrOp = GEP.getOperand(0);
5131   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
5132   // If so, eliminate the noop.
5133   if (GEP.getNumOperands() == 1)
5134     return ReplaceInstUsesWith(GEP, PtrOp);
5135
5136   if (isa<UndefValue>(GEP.getOperand(0)))
5137     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5138
5139   bool HasZeroPointerIndex = false;
5140   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5141     HasZeroPointerIndex = C->isNullValue();
5142
5143   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
5144     return ReplaceInstUsesWith(GEP, PtrOp);
5145
5146   // Eliminate unneeded casts for indices.
5147   bool MadeChange = false;
5148   gep_type_iterator GTI = gep_type_begin(GEP);
5149   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5150     if (isa<SequentialType>(*GTI)) {
5151       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5152         Value *Src = CI->getOperand(0);
5153         const Type *SrcTy = Src->getType();
5154         const Type *DestTy = CI->getType();
5155         if (Src->getType()->isInteger()) {
5156           if (SrcTy->getPrimitiveSizeInBits() ==
5157                        DestTy->getPrimitiveSizeInBits()) {
5158             // We can always eliminate a cast from ulong or long to the other.
5159             // We can always eliminate a cast from uint to int or the other on
5160             // 32-bit pointer platforms.
5161             if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
5162               MadeChange = true;
5163               GEP.setOperand(i, Src);
5164             }
5165           } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5166                      SrcTy->getPrimitiveSize() == 4) {
5167             // We can always eliminate a cast from int to [u]long.  We can
5168             // eliminate a cast from uint to [u]long iff the target is a 32-bit
5169             // pointer target.
5170             if (SrcTy->isSigned() ||
5171                 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
5172               MadeChange = true;
5173               GEP.setOperand(i, Src);
5174             }
5175           }
5176         }
5177       }
5178       // If we are using a wider index than needed for this platform, shrink it
5179       // to what we need.  If the incoming value needs a cast instruction,
5180       // insert it.  This explicit cast can make subsequent optimizations more
5181       // obvious.
5182       Value *Op = GEP.getOperand(i);
5183       if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
5184         if (Constant *C = dyn_cast<Constant>(Op)) {
5185           GEP.setOperand(i, ConstantExpr::getCast(C,
5186                                      TD->getIntPtrType()->getSignedVersion()));
5187           MadeChange = true;
5188         } else {
5189           Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5190                                                 Op->getName()), GEP);
5191           GEP.setOperand(i, Op);
5192           MadeChange = true;
5193         }
5194
5195       // If this is a constant idx, make sure to canonicalize it to be a signed
5196       // operand, otherwise CSE and other optimizations are pessimized.
5197       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5198         GEP.setOperand(i, ConstantExpr::getCast(CUI,
5199                                           CUI->getType()->getSignedVersion()));
5200         MadeChange = true;
5201       }
5202     }
5203   if (MadeChange) return &GEP;
5204
5205   // Combine Indices - If the source pointer to this getelementptr instruction
5206   // is a getelementptr instruction, combine the indices of the two
5207   // getelementptr instructions into a single instruction.
5208   //
5209   std::vector<Value*> SrcGEPOperands;
5210   if (User *Src = dyn_castGetElementPtr(PtrOp))
5211     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
5212
5213   if (!SrcGEPOperands.empty()) {
5214     // Note that if our source is a gep chain itself that we wait for that
5215     // chain to be resolved before we perform this transformation.  This
5216     // avoids us creating a TON of code in some cases.
5217     //
5218     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5219         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5220       return 0;   // Wait until our source is folded to completion.
5221
5222     std::vector<Value *> Indices;
5223
5224     // Find out whether the last index in the source GEP is a sequential idx.
5225     bool EndsWithSequential = false;
5226     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5227            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
5228       EndsWithSequential = !isa<StructType>(*I);
5229
5230     // Can we combine the two pointer arithmetics offsets?
5231     if (EndsWithSequential) {
5232       // Replace: gep (gep %P, long B), long A, ...
5233       // With:    T = long A+B; gep %P, T, ...
5234       //
5235       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
5236       if (SO1 == Constant::getNullValue(SO1->getType())) {
5237         Sum = GO1;
5238       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5239         Sum = SO1;
5240       } else {
5241         // If they aren't the same type, convert both to an integer of the
5242         // target's pointer size.
5243         if (SO1->getType() != GO1->getType()) {
5244           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5245             SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5246           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5247             GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5248           } else {
5249             unsigned PS = TD->getPointerSize();
5250             if (SO1->getType()->getPrimitiveSize() == PS) {
5251               // Convert GO1 to SO1's type.
5252               GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5253
5254             } else if (GO1->getType()->getPrimitiveSize() == PS) {
5255               // Convert SO1 to GO1's type.
5256               SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5257             } else {
5258               const Type *PT = TD->getIntPtrType();
5259               SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5260               GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5261             }
5262           }
5263         }
5264         if (isa<Constant>(SO1) && isa<Constant>(GO1))
5265           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5266         else {
5267           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5268           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
5269         }
5270       }
5271
5272       // Recycle the GEP we already have if possible.
5273       if (SrcGEPOperands.size() == 2) {
5274         GEP.setOperand(0, SrcGEPOperands[0]);
5275         GEP.setOperand(1, Sum);
5276         return &GEP;
5277       } else {
5278         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5279                        SrcGEPOperands.end()-1);
5280         Indices.push_back(Sum);
5281         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5282       }
5283     } else if (isa<Constant>(*GEP.idx_begin()) &&
5284                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
5285                SrcGEPOperands.size() != 1) {
5286       // Otherwise we can do the fold if the first index of the GEP is a zero
5287       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5288                      SrcGEPOperands.end());
5289       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5290     }
5291
5292     if (!Indices.empty())
5293       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
5294
5295   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
5296     // GEP of global variable.  If all of the indices for this GEP are
5297     // constants, we can promote this to a constexpr instead of an instruction.
5298
5299     // Scan for nonconstants...
5300     std::vector<Constant*> Indices;
5301     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5302     for (; I != E && isa<Constant>(*I); ++I)
5303       Indices.push_back(cast<Constant>(*I));
5304
5305     if (I == E) {  // If they are all constants...
5306       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
5307
5308       // Replace all uses of the GEP with the new constexpr...
5309       return ReplaceInstUsesWith(GEP, CE);
5310     }
5311   } else if (Value *X = isCast(PtrOp)) {  // Is the operand a cast?
5312     if (!isa<PointerType>(X->getType())) {
5313       // Not interesting.  Source pointer must be a cast from pointer.
5314     } else if (HasZeroPointerIndex) {
5315       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5316       // into     : GEP [10 x ubyte]* X, long 0, ...
5317       //
5318       // This occurs when the program declares an array extern like "int X[];"
5319       //
5320       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5321       const PointerType *XTy = cast<PointerType>(X->getType());
5322       if (const ArrayType *XATy =
5323           dyn_cast<ArrayType>(XTy->getElementType()))
5324         if (const ArrayType *CATy =
5325             dyn_cast<ArrayType>(CPTy->getElementType()))
5326           if (CATy->getElementType() == XATy->getElementType()) {
5327             // At this point, we know that the cast source type is a pointer
5328             // to an array of the same type as the destination pointer
5329             // array.  Because the array type is never stepped over (there
5330             // is a leading zero) we can fold the cast into this GEP.
5331             GEP.setOperand(0, X);
5332             return &GEP;
5333           }
5334     } else if (GEP.getNumOperands() == 2) {
5335       // Transform things like:
5336       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5337       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
5338       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5339       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5340       if (isa<ArrayType>(SrcElTy) &&
5341           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5342           TD->getTypeSize(ResElTy)) {
5343         Value *V = InsertNewInstBefore(
5344                new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5345                                      GEP.getOperand(1), GEP.getName()), GEP);
5346         return new CastInst(V, GEP.getType());
5347       }
5348       
5349       // Transform things like:
5350       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5351       //   (where tmp = 8*tmp2) into:
5352       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5353       
5354       if (isa<ArrayType>(SrcElTy) &&
5355           (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5356         uint64_t ArrayEltSize =
5357             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5358         
5359         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
5360         // allow either a mul, shift, or constant here.
5361         Value *NewIdx = 0;
5362         ConstantInt *Scale = 0;
5363         if (ArrayEltSize == 1) {
5364           NewIdx = GEP.getOperand(1);
5365           Scale = ConstantInt::get(NewIdx->getType(), 1);
5366         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
5367           NewIdx = ConstantInt::get(CI->getType(), 1);
5368           Scale = CI;
5369         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5370           if (Inst->getOpcode() == Instruction::Shl &&
5371               isa<ConstantInt>(Inst->getOperand(1))) {
5372             unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5373             if (Inst->getType()->isSigned())
5374               Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5375             else
5376               Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5377             NewIdx = Inst->getOperand(0);
5378           } else if (Inst->getOpcode() == Instruction::Mul &&
5379                      isa<ConstantInt>(Inst->getOperand(1))) {
5380             Scale = cast<ConstantInt>(Inst->getOperand(1));
5381             NewIdx = Inst->getOperand(0);
5382           }
5383         }
5384
5385         // If the index will be to exactly the right offset with the scale taken
5386         // out, perform the transformation.
5387         if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5388           if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5389             Scale = ConstantSInt::get(C->getType(),
5390                                       (int64_t)C->getRawValue() / 
5391                                       (int64_t)ArrayEltSize);
5392           else
5393             Scale = ConstantUInt::get(Scale->getType(),
5394                                       Scale->getRawValue() / ArrayEltSize);
5395           if (Scale->getRawValue() != 1) {
5396             Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5397             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5398             NewIdx = InsertNewInstBefore(Sc, GEP);
5399           }
5400
5401           // Insert the new GEP instruction.
5402           Instruction *Idx =
5403             new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5404                                   NewIdx, GEP.getName());
5405           Idx = InsertNewInstBefore(Idx, GEP);
5406           return new CastInst(Idx, GEP.getType());
5407         }
5408       }
5409     }
5410   }
5411
5412   return 0;
5413 }
5414
5415 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5416   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5417   if (AI.isArrayAllocation())    // Check C != 1
5418     if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5419       const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
5420       AllocationInst *New = 0;
5421
5422       // Create and insert the replacement instruction...
5423       if (isa<MallocInst>(AI))
5424         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
5425       else {
5426         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
5427         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
5428       }
5429
5430       InsertNewInstBefore(New, AI);
5431
5432       // Scan to the end of the allocation instructions, to skip over a block of
5433       // allocas if possible...
5434       //
5435       BasicBlock::iterator It = New;
5436       while (isa<AllocationInst>(*It)) ++It;
5437
5438       // Now that I is pointing to the first non-allocation-inst in the block,
5439       // insert our getelementptr instruction...
5440       //
5441       Value *NullIdx = Constant::getNullValue(Type::IntTy);
5442       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5443                                        New->getName()+".sub", It);
5444
5445       // Now make everything use the getelementptr instead of the original
5446       // allocation.
5447       return ReplaceInstUsesWith(AI, V);
5448     } else if (isa<UndefValue>(AI.getArraySize())) {
5449       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5450     }
5451
5452   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5453   // Note that we only do this for alloca's, because malloc should allocate and
5454   // return a unique pointer, even for a zero byte allocation.
5455   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
5456       TD->getTypeSize(AI.getAllocatedType()) == 0)
5457     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5458
5459   return 0;
5460 }
5461
5462 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5463   Value *Op = FI.getOperand(0);
5464
5465   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5466   if (CastInst *CI = dyn_cast<CastInst>(Op))
5467     if (isa<PointerType>(CI->getOperand(0)->getType())) {
5468       FI.setOperand(0, CI->getOperand(0));
5469       return &FI;
5470     }
5471
5472   // free undef -> unreachable.
5473   if (isa<UndefValue>(Op)) {
5474     // Insert a new store to null because we cannot modify the CFG here.
5475     new StoreInst(ConstantBool::True,
5476                   UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5477     return EraseInstFromFunction(FI);
5478   }
5479
5480   // If we have 'free null' delete the instruction.  This can happen in stl code
5481   // when lots of inlining happens.
5482   if (isa<ConstantPointerNull>(Op))
5483     return EraseInstFromFunction(FI);
5484
5485   return 0;
5486 }
5487
5488
5489 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
5490 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5491   User *CI = cast<User>(LI.getOperand(0));
5492   Value *CastOp = CI->getOperand(0);
5493
5494   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5495   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5496     const Type *SrcPTy = SrcTy->getElementType();
5497
5498     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5499       // If the source is an array, the code below will not succeed.  Check to
5500       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
5501       // constants.
5502       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5503         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5504           if (ASrcTy->getNumElements() != 0) {
5505             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5506             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5507             SrcTy = cast<PointerType>(CastOp->getType());
5508             SrcPTy = SrcTy->getElementType();
5509           }
5510
5511       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
5512           // Do not allow turning this into a load of an integer, which is then
5513           // casted to a pointer, this pessimizes pointer analysis a lot.
5514           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
5515           IC.getTargetData().getTypeSize(SrcPTy) ==
5516                IC.getTargetData().getTypeSize(DestPTy)) {
5517
5518         // Okay, we are casting from one integer or pointer type to another of
5519         // the same size.  Instead of casting the pointer before the load, cast
5520         // the result of the loaded value.
5521         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5522                                                              CI->getName(),
5523                                                          LI.isVolatile()),LI);
5524         // Now cast the result of the load.
5525         return new CastInst(NewLoad, LI.getType());
5526       }
5527     }
5528   }
5529   return 0;
5530 }
5531
5532 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
5533 /// from this value cannot trap.  If it is not obviously safe to load from the
5534 /// specified pointer, we do a quick local scan of the basic block containing
5535 /// ScanFrom, to determine if the address is already accessed.
5536 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5537   // If it is an alloca or global variable, it is always safe to load from.
5538   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5539
5540   // Otherwise, be a little bit agressive by scanning the local block where we
5541   // want to check to see if the pointer is already being loaded or stored
5542   // from/to.  If so, the previous load or store would have already trapped,
5543   // so there is no harm doing an extra load (also, CSE will later eliminate
5544   // the load entirely).
5545   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5546
5547   while (BBI != E) {
5548     --BBI;
5549
5550     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5551       if (LI->getOperand(0) == V) return true;
5552     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5553       if (SI->getOperand(1) == V) return true;
5554
5555   }
5556   return false;
5557 }
5558
5559 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5560   Value *Op = LI.getOperand(0);
5561
5562   // load (cast X) --> cast (load X) iff safe
5563   if (CastInst *CI = dyn_cast<CastInst>(Op))
5564     if (Instruction *Res = InstCombineLoadCast(*this, LI))
5565       return Res;
5566
5567   // None of the following transforms are legal for volatile loads.
5568   if (LI.isVolatile()) return 0;
5569   
5570   if (&LI.getParent()->front() != &LI) {
5571     BasicBlock::iterator BBI = &LI; --BBI;
5572     // If the instruction immediately before this is a store to the same
5573     // address, do a simple form of store->load forwarding.
5574     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5575       if (SI->getOperand(1) == LI.getOperand(0))
5576         return ReplaceInstUsesWith(LI, SI->getOperand(0));
5577     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5578       if (LIB->getOperand(0) == LI.getOperand(0))
5579         return ReplaceInstUsesWith(LI, LIB);
5580   }
5581
5582   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5583     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5584         isa<UndefValue>(GEPI->getOperand(0))) {
5585       // Insert a new store to null instruction before the load to indicate
5586       // that this code is not reachable.  We do this instead of inserting
5587       // an unreachable instruction directly because we cannot modify the
5588       // CFG.
5589       new StoreInst(UndefValue::get(LI.getType()),
5590                     Constant::getNullValue(Op->getType()), &LI);
5591       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5592     }
5593
5594   if (Constant *C = dyn_cast<Constant>(Op)) {
5595     // load null/undef -> undef
5596     if ((C->isNullValue() || isa<UndefValue>(C))) {
5597       // Insert a new store to null instruction before the load to indicate that
5598       // this code is not reachable.  We do this instead of inserting an
5599       // unreachable instruction directly because we cannot modify the CFG.
5600       new StoreInst(UndefValue::get(LI.getType()),
5601                     Constant::getNullValue(Op->getType()), &LI);
5602       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5603     }
5604
5605     // Instcombine load (constant global) into the value loaded.
5606     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5607       if (GV->isConstant() && !GV->isExternal())
5608         return ReplaceInstUsesWith(LI, GV->getInitializer());
5609
5610     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5611     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5612       if (CE->getOpcode() == Instruction::GetElementPtr) {
5613         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5614           if (GV->isConstant() && !GV->isExternal())
5615             if (Constant *V = 
5616                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
5617               return ReplaceInstUsesWith(LI, V);
5618         if (CE->getOperand(0)->isNullValue()) {
5619           // Insert a new store to null instruction before the load to indicate
5620           // that this code is not reachable.  We do this instead of inserting
5621           // an unreachable instruction directly because we cannot modify the
5622           // CFG.
5623           new StoreInst(UndefValue::get(LI.getType()),
5624                         Constant::getNullValue(Op->getType()), &LI);
5625           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5626         }
5627
5628       } else if (CE->getOpcode() == Instruction::Cast) {
5629         if (Instruction *Res = InstCombineLoadCast(*this, LI))
5630           return Res;
5631       }
5632   }
5633
5634   if (Op->hasOneUse()) {
5635     // Change select and PHI nodes to select values instead of addresses: this
5636     // helps alias analysis out a lot, allows many others simplifications, and
5637     // exposes redundancy in the code.
5638     //
5639     // Note that we cannot do the transformation unless we know that the
5640     // introduced loads cannot trap!  Something like this is valid as long as
5641     // the condition is always false: load (select bool %C, int* null, int* %G),
5642     // but it would not be valid if we transformed it to load from null
5643     // unconditionally.
5644     //
5645     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5646       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
5647       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5648           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
5649         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
5650                                      SI->getOperand(1)->getName()+".val"), LI);
5651         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
5652                                      SI->getOperand(2)->getName()+".val"), LI);
5653         return new SelectInst(SI->getCondition(), V1, V2);
5654       }
5655
5656       // load (select (cond, null, P)) -> load P
5657       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5658         if (C->isNullValue()) {
5659           LI.setOperand(0, SI->getOperand(2));
5660           return &LI;
5661         }
5662
5663       // load (select (cond, P, null)) -> load P
5664       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5665         if (C->isNullValue()) {
5666           LI.setOperand(0, SI->getOperand(1));
5667           return &LI;
5668         }
5669
5670     } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5671       // load (phi (&V1, &V2, &V3))  --> phi(load &V1, load &V2, load &V3)
5672       bool Safe = PN->getParent() == LI.getParent();
5673
5674       // Scan all of the instructions between the PHI and the load to make
5675       // sure there are no instructions that might possibly alter the value
5676       // loaded from the PHI.
5677       if (Safe) {
5678         BasicBlock::iterator I = &LI;
5679         for (--I; !isa<PHINode>(I); --I)
5680           if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5681             Safe = false;
5682             break;
5683           }
5684       }
5685
5686       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
5687         if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
5688                                     PN->getIncomingBlock(i)->getTerminator()))
5689           Safe = false;
5690
5691       if (Safe) {
5692         // Create the PHI.
5693         PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5694         InsertNewInstBefore(NewPN, *PN);
5695         std::map<BasicBlock*,Value*> LoadMap;  // Don't insert duplicate loads
5696
5697         for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5698           BasicBlock *BB = PN->getIncomingBlock(i);
5699           Value *&TheLoad = LoadMap[BB];
5700           if (TheLoad == 0) {
5701             Value *InVal = PN->getIncomingValue(i);
5702             TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5703                                                        InVal->getName()+".val"),
5704                                           *BB->getTerminator());
5705           }
5706           NewPN->addIncoming(TheLoad, BB);
5707         }
5708         return ReplaceInstUsesWith(LI, NewPN);
5709       }
5710     }
5711   }
5712   return 0;
5713 }
5714
5715 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5716 /// when possible.
5717 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5718   User *CI = cast<User>(SI.getOperand(1));
5719   Value *CastOp = CI->getOperand(0);
5720
5721   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5722   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5723     const Type *SrcPTy = SrcTy->getElementType();
5724
5725     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5726       // If the source is an array, the code below will not succeed.  Check to
5727       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
5728       // constants.
5729       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5730         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5731           if (ASrcTy->getNumElements() != 0) {
5732             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5733             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5734             SrcTy = cast<PointerType>(CastOp->getType());
5735             SrcPTy = SrcTy->getElementType();
5736           }
5737
5738       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
5739           IC.getTargetData().getTypeSize(SrcPTy) ==
5740                IC.getTargetData().getTypeSize(DestPTy)) {
5741
5742         // Okay, we are casting from one integer or pointer type to another of
5743         // the same size.  Instead of casting the pointer before the store, cast
5744         // the value to be stored.
5745         Value *NewCast;
5746         if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5747           NewCast = ConstantExpr::getCast(C, SrcPTy);
5748         else
5749           NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5750                                                         SrcPTy,
5751                                          SI.getOperand(0)->getName()+".c"), SI);
5752
5753         return new StoreInst(NewCast, CastOp);
5754       }
5755     }
5756   }
5757   return 0;
5758 }
5759
5760 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5761   Value *Val = SI.getOperand(0);
5762   Value *Ptr = SI.getOperand(1);
5763
5764   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
5765     removeFromWorkList(&SI);
5766     SI.eraseFromParent();
5767     ++NumCombined;
5768     return 0;
5769   }
5770
5771   if (SI.isVolatile()) return 0;  // Don't hack volatile loads.
5772
5773   // store X, null    -> turns into 'unreachable' in SimplifyCFG
5774   if (isa<ConstantPointerNull>(Ptr)) {
5775     if (!isa<UndefValue>(Val)) {
5776       SI.setOperand(0, UndefValue::get(Val->getType()));
5777       if (Instruction *U = dyn_cast<Instruction>(Val))
5778         WorkList.push_back(U);  // Dropped a use.
5779       ++NumCombined;
5780     }
5781     return 0;  // Do not modify these!
5782   }
5783
5784   // store undef, Ptr -> noop
5785   if (isa<UndefValue>(Val)) {
5786     removeFromWorkList(&SI);
5787     SI.eraseFromParent();
5788     ++NumCombined;
5789     return 0;
5790   }
5791
5792   // If the pointer destination is a cast, see if we can fold the cast into the
5793   // source instead.
5794   if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5795     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5796       return Res;
5797   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5798     if (CE->getOpcode() == Instruction::Cast)
5799       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5800         return Res;
5801
5802   
5803   // If this store is the last instruction in the basic block, and if the block
5804   // ends with an unconditional branch, try to move it to the successor block.
5805   BasicBlock::iterator BBI = &SI; ++BBI;
5806   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5807     if (BI->isUnconditional()) {
5808       // Check to see if the successor block has exactly two incoming edges.  If
5809       // so, see if the other predecessor contains a store to the same location.
5810       // if so, insert a PHI node (if needed) and move the stores down.
5811       BasicBlock *Dest = BI->getSuccessor(0);
5812
5813       pred_iterator PI = pred_begin(Dest);
5814       BasicBlock *Other = 0;
5815       if (*PI != BI->getParent())
5816         Other = *PI;
5817       ++PI;
5818       if (PI != pred_end(Dest)) {
5819         if (*PI != BI->getParent())
5820           if (Other)
5821             Other = 0;
5822           else
5823             Other = *PI;
5824         if (++PI != pred_end(Dest))
5825           Other = 0;
5826       }
5827       if (Other) {  // If only one other pred...
5828         BBI = Other->getTerminator();
5829         // Make sure this other block ends in an unconditional branch and that
5830         // there is an instruction before the branch.
5831         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5832             BBI != Other->begin()) {
5833           --BBI;
5834           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5835           
5836           // If this instruction is a store to the same location.
5837           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5838             // Okay, we know we can perform this transformation.  Insert a PHI
5839             // node now if we need it.
5840             Value *MergedVal = OtherStore->getOperand(0);
5841             if (MergedVal != SI.getOperand(0)) {
5842               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5843               PN->reserveOperandSpace(2);
5844               PN->addIncoming(SI.getOperand(0), SI.getParent());
5845               PN->addIncoming(OtherStore->getOperand(0), Other);
5846               MergedVal = InsertNewInstBefore(PN, Dest->front());
5847             }
5848             
5849             // Advance to a place where it is safe to insert the new store and
5850             // insert it.
5851             BBI = Dest->begin();
5852             while (isa<PHINode>(BBI)) ++BBI;
5853             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5854                                               OtherStore->isVolatile()), *BBI);
5855
5856             // Nuke the old stores.
5857             removeFromWorkList(&SI);
5858             removeFromWorkList(OtherStore);
5859             SI.eraseFromParent();
5860             OtherStore->eraseFromParent();
5861             ++NumCombined;
5862             return 0;
5863           }
5864         }
5865       }
5866     }
5867   
5868   return 0;
5869 }
5870
5871
5872 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5873   // Change br (not X), label True, label False to: br X, label False, True
5874   Value *X = 0;
5875   BasicBlock *TrueDest;
5876   BasicBlock *FalseDest;
5877   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5878       !isa<Constant>(X)) {
5879     // Swap Destinations and condition...
5880     BI.setCondition(X);
5881     BI.setSuccessor(0, FalseDest);
5882     BI.setSuccessor(1, TrueDest);
5883     return &BI;
5884   }
5885
5886   // Cannonicalize setne -> seteq
5887   Instruction::BinaryOps Op; Value *Y;
5888   if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5889                       TrueDest, FalseDest)))
5890     if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5891          Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5892       SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5893       std::string Name = I->getName(); I->setName("");
5894       Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5895       Value *NewSCC =  BinaryOperator::create(NewOpcode, X, Y, Name, I);
5896       // Swap Destinations and condition...
5897       BI.setCondition(NewSCC);
5898       BI.setSuccessor(0, FalseDest);
5899       BI.setSuccessor(1, TrueDest);
5900       removeFromWorkList(I);
5901       I->getParent()->getInstList().erase(I);
5902       WorkList.push_back(cast<Instruction>(NewSCC));
5903       return &BI;
5904     }
5905
5906   return 0;
5907 }
5908
5909 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5910   Value *Cond = SI.getCondition();
5911   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5912     if (I->getOpcode() == Instruction::Add)
5913       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5914         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5915         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
5916           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
5917                                                 AddRHS));
5918         SI.setOperand(0, I->getOperand(0));
5919         WorkList.push_back(I);
5920         return &SI;
5921       }
5922   }
5923   return 0;
5924 }
5925
5926 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
5927   if (ConstantAggregateZero *C = 
5928       dyn_cast<ConstantAggregateZero>(EI.getOperand(0))) {
5929     // If packed val is constant 0, replace extract with scalar 0
5930     const Type *Ty = cast<PackedType>(C->getType())->getElementType();
5931     EI.replaceAllUsesWith(Constant::getNullValue(Ty));
5932     return ReplaceInstUsesWith(EI, Constant::getNullValue(Ty));
5933   }
5934   if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
5935     // If packed val is constant with uniform operands, replace EI
5936     // with that operand
5937     Constant *op0 = cast<Constant>(C->getOperand(0));
5938     for (unsigned i = 1; i < C->getNumOperands(); ++i)
5939       if (C->getOperand(i) != op0) return 0;
5940     return ReplaceInstUsesWith(EI, op0);
5941   }
5942   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
5943     if (I->hasOneUse()) {
5944       // Push extractelement into predecessor operation if legal and
5945       // profitable to do so
5946       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
5947         if (!isa<Constant>(BO->getOperand(0)) &&
5948             !isa<Constant>(BO->getOperand(1)))
5949           return 0;
5950         ExtractElementInst *newEI0 = 
5951           new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
5952                                  EI.getName());
5953         ExtractElementInst *newEI1 =
5954           new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
5955                                  EI.getName());
5956         InsertNewInstBefore(newEI0, EI);
5957         InsertNewInstBefore(newEI1, EI);
5958         return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
5959       }
5960       switch(I->getOpcode()) {
5961       case Instruction::Load: {
5962         Value *Ptr = InsertCastBefore(I->getOperand(0),
5963                                       PointerType::get(EI.getType()), EI);
5964         GetElementPtrInst *GEP = 
5965           new GetElementPtrInst(Ptr, EI.getOperand(1),
5966                                 I->getName() + ".gep");
5967         InsertNewInstBefore(GEP, EI);
5968         return new LoadInst(GEP);
5969       }
5970       default:
5971         return 0;
5972       }
5973     }
5974   return 0;
5975 }
5976
5977
5978 void InstCombiner::removeFromWorkList(Instruction *I) {
5979   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5980                  WorkList.end());
5981 }
5982
5983
5984 /// TryToSinkInstruction - Try to move the specified instruction from its
5985 /// current block into the beginning of DestBlock, which can only happen if it's
5986 /// safe to move the instruction past all of the instructions between it and the
5987 /// end of its block.
5988 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5989   assert(I->hasOneUse() && "Invariants didn't hold!");
5990
5991   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
5992   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
5993
5994   // Do not sink alloca instructions out of the entry block.
5995   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5996     return false;
5997
5998   // We can only sink load instructions if there is nothing between the load and
5999   // the end of block that could change the value.
6000   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6001     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
6002          Scan != E; ++Scan)
6003       if (Scan->mayWriteToMemory())
6004         return false;
6005   }
6006
6007   BasicBlock::iterator InsertPos = DestBlock->begin();
6008   while (isa<PHINode>(InsertPos)) ++InsertPos;
6009
6010   I->moveBefore(InsertPos);
6011   ++NumSunkInst;
6012   return true;
6013 }
6014
6015 bool InstCombiner::runOnFunction(Function &F) {
6016   bool Changed = false;
6017   TD = &getAnalysis<TargetData>();
6018
6019   {
6020     // Populate the worklist with the reachable instructions.
6021     std::set<BasicBlock*> Visited;
6022     for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
6023            E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
6024       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
6025         WorkList.push_back(I);
6026
6027     // Do a quick scan over the function.  If we find any blocks that are
6028     // unreachable, remove any instructions inside of them.  This prevents
6029     // the instcombine code from having to deal with some bad special cases.
6030     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6031       if (!Visited.count(BB)) {
6032         Instruction *Term = BB->getTerminator();
6033         while (Term != BB->begin()) {   // Remove instrs bottom-up
6034           BasicBlock::iterator I = Term; --I;
6035
6036           DEBUG(std::cerr << "IC: DCE: " << *I);
6037           ++NumDeadInst;
6038
6039           if (!I->use_empty())
6040             I->replaceAllUsesWith(UndefValue::get(I->getType()));
6041           I->eraseFromParent();
6042         }
6043       }
6044   }
6045
6046   while (!WorkList.empty()) {
6047     Instruction *I = WorkList.back();  // Get an instruction from the worklist
6048     WorkList.pop_back();
6049
6050     // Check to see if we can DCE or ConstantPropagate the instruction...
6051     // Check to see if we can DIE the instruction...
6052     if (isInstructionTriviallyDead(I)) {
6053       // Add operands to the worklist...
6054       if (I->getNumOperands() < 4)
6055         AddUsesToWorkList(*I);
6056       ++NumDeadInst;
6057
6058       DEBUG(std::cerr << "IC: DCE: " << *I);
6059
6060       I->eraseFromParent();
6061       removeFromWorkList(I);
6062       continue;
6063     }
6064
6065     // Instruction isn't dead, see if we can constant propagate it...
6066     if (Constant *C = ConstantFoldInstruction(I)) {
6067       Value* Ptr = I->getOperand(0);
6068       if (isa<GetElementPtrInst>(I) &&
6069           cast<Constant>(Ptr)->isNullValue() &&
6070           !isa<ConstantPointerNull>(C) &&
6071           cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
6072         // If this is a constant expr gep that is effectively computing an
6073         // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6074         bool isFoldableGEP = true;
6075         for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6076           if (!isa<ConstantInt>(I->getOperand(i)))
6077             isFoldableGEP = false;
6078         if (isFoldableGEP) {
6079           uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
6080                              std::vector<Value*>(I->op_begin()+1, I->op_end()));
6081           C = ConstantUInt::get(Type::ULongTy, Offset);
6082           C = ConstantExpr::getCast(C, TD->getIntPtrType());
6083           C = ConstantExpr::getCast(C, I->getType());
6084         }
6085       }
6086
6087       DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6088
6089       // Add operands to the worklist...
6090       AddUsesToWorkList(*I);
6091       ReplaceInstUsesWith(*I, C);
6092
6093       ++NumConstProp;
6094       I->getParent()->getInstList().erase(I);
6095       removeFromWorkList(I);
6096       continue;
6097     }
6098
6099     // See if we can trivially sink this instruction to a successor basic block.
6100     if (I->hasOneUse()) {
6101       BasicBlock *BB = I->getParent();
6102       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6103       if (UserParent != BB) {
6104         bool UserIsSuccessor = false;
6105         // See if the user is one of our successors.
6106         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6107           if (*SI == UserParent) {
6108             UserIsSuccessor = true;
6109             break;
6110           }
6111
6112         // If the user is one of our immediate successors, and if that successor
6113         // only has us as a predecessors (we'd have to split the critical edge
6114         // otherwise), we can keep going.
6115         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6116             next(pred_begin(UserParent)) == pred_end(UserParent))
6117           // Okay, the CFG is simple enough, try to sink this instruction.
6118           Changed |= TryToSinkInstruction(I, UserParent);
6119       }
6120     }
6121
6122     // Now that we have an instruction, try combining it to simplify it...
6123     if (Instruction *Result = visit(*I)) {
6124       ++NumCombined;
6125       // Should we replace the old instruction with a new one?
6126       if (Result != I) {
6127         DEBUG(std::cerr << "IC: Old = " << *I
6128                         << "    New = " << *Result);
6129
6130         // Everything uses the new instruction now.
6131         I->replaceAllUsesWith(Result);
6132
6133         // Push the new instruction and any users onto the worklist.
6134         WorkList.push_back(Result);
6135         AddUsersToWorkList(*Result);
6136
6137         // Move the name to the new instruction first...
6138         std::string OldName = I->getName(); I->setName("");
6139         Result->setName(OldName);
6140
6141         // Insert the new instruction into the basic block...
6142         BasicBlock *InstParent = I->getParent();
6143         BasicBlock::iterator InsertPos = I;
6144
6145         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
6146           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6147             ++InsertPos;
6148
6149         InstParent->getInstList().insert(InsertPos, Result);
6150
6151         // Make sure that we reprocess all operands now that we reduced their
6152         // use counts.
6153         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6154           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6155             WorkList.push_back(OpI);
6156
6157         // Instructions can end up on the worklist more than once.  Make sure
6158         // we do not process an instruction that has been deleted.
6159         removeFromWorkList(I);
6160
6161         // Erase the old instruction.
6162         InstParent->getInstList().erase(I);
6163       } else {
6164         DEBUG(std::cerr << "IC: MOD = " << *I);
6165
6166         // If the instruction was modified, it's possible that it is now dead.
6167         // if so, remove it.
6168         if (isInstructionTriviallyDead(I)) {
6169           // Make sure we process all operands now that we are reducing their
6170           // use counts.
6171           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6172             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6173               WorkList.push_back(OpI);
6174
6175           // Instructions may end up in the worklist more than once.  Erase all
6176           // occurrences of this instruction.
6177           removeFromWorkList(I);
6178           I->eraseFromParent();
6179         } else {
6180           WorkList.push_back(Result);
6181           AddUsersToWorkList(*Result);
6182         }
6183       }
6184       Changed = true;
6185     }
6186   }
6187
6188   return Changed;
6189 }
6190
6191 FunctionPass *llvm::createInstructionCombiningPass() {
6192   return new InstCombiner();
6193 }
6194