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