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