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