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