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