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