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