54eb91f185d2a021059b85fa86e8fd64e75018c8
[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. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp 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/Analysis/ConstantFolding.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/GetElementPtrTypeIterator.h"
49 #include "llvm/Support/InstVisitor.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/PatternMatch.h"
52 #include "llvm/Support/Compiler.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/Statistic.h"
56 #include "llvm/ADT/STLExtras.h"
57 #include <algorithm>
58 #include <set>
59 using namespace llvm;
60 using namespace llvm::PatternMatch;
61
62 STATISTIC(NumCombined , "Number of insts combined");
63 STATISTIC(NumConstProp, "Number of constant folds");
64 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
65 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
66 STATISTIC(NumSunkInst , "Number of instructions sunk");
67
68 namespace {
69   class VISIBILITY_HIDDEN InstCombiner
70     : public FunctionPass,
71       public InstVisitor<InstCombiner, Instruction*> {
72     // Worklist of all of the instructions that need to be simplified.
73     std::vector<Instruction*> WorkList;
74     TargetData *TD;
75
76     /// AddUsersToWorkList - When an instruction is simplified, add all users of
77     /// the instruction to the work lists because they might get more simplified
78     /// now.
79     ///
80     void AddUsersToWorkList(Value &I) {
81       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
82            UI != UE; ++UI)
83         WorkList.push_back(cast<Instruction>(*UI));
84     }
85
86     /// AddUsesToWorkList - When an instruction is simplified, add operands to
87     /// the work lists because they might get more simplified now.
88     ///
89     void AddUsesToWorkList(Instruction &I) {
90       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
91         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
92           WorkList.push_back(Op);
93     }
94     
95     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
96     /// dead.  Add all of its operands to the worklist, turning them into
97     /// undef's to reduce the number of uses of those instructions.
98     ///
99     /// Return the specified operand before it is turned into an undef.
100     ///
101     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
102       Value *R = I.getOperand(op);
103       
104       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
105         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
106           WorkList.push_back(Op);
107           // Set the operand to undef to drop the use.
108           I.setOperand(i, UndefValue::get(Op->getType()));
109         }
110       
111       return R;
112     }
113
114     // removeFromWorkList - remove all instances of I from the worklist.
115     void removeFromWorkList(Instruction *I);
116   public:
117     virtual bool runOnFunction(Function &F);
118
119     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
120       AU.addRequired<TargetData>();
121       AU.addPreservedID(LCSSAID);
122       AU.setPreservesCFG();
123     }
124
125     TargetData &getTargetData() const { return *TD; }
126
127     // Visitation implementation - Implement instruction combining for different
128     // instruction types.  The semantics are as follows:
129     // Return Value:
130     //    null        - No change was made
131     //     I          - Change was made, I is still valid, I may be dead though
132     //   otherwise    - Change was made, replace I with returned instruction
133     //
134     Instruction *visitAdd(BinaryOperator &I);
135     Instruction *visitSub(BinaryOperator &I);
136     Instruction *visitMul(BinaryOperator &I);
137     Instruction *visitURem(BinaryOperator &I);
138     Instruction *visitSRem(BinaryOperator &I);
139     Instruction *visitFRem(BinaryOperator &I);
140     Instruction *commonRemTransforms(BinaryOperator &I);
141     Instruction *commonIRemTransforms(BinaryOperator &I);
142     Instruction *commonDivTransforms(BinaryOperator &I);
143     Instruction *commonIDivTransforms(BinaryOperator &I);
144     Instruction *visitUDiv(BinaryOperator &I);
145     Instruction *visitSDiv(BinaryOperator &I);
146     Instruction *visitFDiv(BinaryOperator &I);
147     Instruction *visitAnd(BinaryOperator &I);
148     Instruction *visitOr (BinaryOperator &I);
149     Instruction *visitXor(BinaryOperator &I);
150     Instruction *visitShl(BinaryOperator &I);
151     Instruction *visitAShr(BinaryOperator &I);
152     Instruction *visitLShr(BinaryOperator &I);
153     Instruction *commonShiftTransforms(BinaryOperator &I);
154     Instruction *visitFCmpInst(FCmpInst &I);
155     Instruction *visitICmpInst(ICmpInst &I);
156     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
157
158     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
159                              ICmpInst::Predicate Cond, Instruction &I);
160     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
161                                      BinaryOperator &I);
162     Instruction *commonCastTransforms(CastInst &CI);
163     Instruction *commonIntCastTransforms(CastInst &CI);
164     Instruction *visitTrunc(CastInst &CI);
165     Instruction *visitZExt(CastInst &CI);
166     Instruction *visitSExt(CastInst &CI);
167     Instruction *visitFPTrunc(CastInst &CI);
168     Instruction *visitFPExt(CastInst &CI);
169     Instruction *visitFPToUI(CastInst &CI);
170     Instruction *visitFPToSI(CastInst &CI);
171     Instruction *visitUIToFP(CastInst &CI);
172     Instruction *visitSIToFP(CastInst &CI);
173     Instruction *visitPtrToInt(CastInst &CI);
174     Instruction *visitIntToPtr(CastInst &CI);
175     Instruction *visitBitCast(CastInst &CI);
176     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
177                                 Instruction *FI);
178     Instruction *visitSelectInst(SelectInst &CI);
179     Instruction *visitCallInst(CallInst &CI);
180     Instruction *visitInvokeInst(InvokeInst &II);
181     Instruction *visitPHINode(PHINode &PN);
182     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
183     Instruction *visitAllocationInst(AllocationInst &AI);
184     Instruction *visitFreeInst(FreeInst &FI);
185     Instruction *visitLoadInst(LoadInst &LI);
186     Instruction *visitStoreInst(StoreInst &SI);
187     Instruction *visitBranchInst(BranchInst &BI);
188     Instruction *visitSwitchInst(SwitchInst &SI);
189     Instruction *visitInsertElementInst(InsertElementInst &IE);
190     Instruction *visitExtractElementInst(ExtractElementInst &EI);
191     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
192
193     // visitInstruction - Specify what to return for unhandled instructions...
194     Instruction *visitInstruction(Instruction &I) { return 0; }
195
196   private:
197     Instruction *visitCallSite(CallSite CS);
198     bool transformConstExprCastCall(CallSite CS);
199
200   public:
201     // InsertNewInstBefore - insert an instruction New before instruction Old
202     // in the program.  Add the new instruction to the worklist.
203     //
204     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
205       assert(New && New->getParent() == 0 &&
206              "New instruction already inserted into a basic block!");
207       BasicBlock *BB = Old.getParent();
208       BB->getInstList().insert(&Old, New);  // Insert inst
209       WorkList.push_back(New);              // Add to worklist
210       return New;
211     }
212
213     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
214     /// This also adds the cast to the worklist.  Finally, this returns the
215     /// cast.
216     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
217                             Instruction &Pos) {
218       if (V->getType() == Ty) return V;
219
220       if (Constant *CV = dyn_cast<Constant>(V))
221         return ConstantExpr::getCast(opc, CV, Ty);
222       
223       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
224       WorkList.push_back(C);
225       return C;
226     }
227
228     // ReplaceInstUsesWith - This method is to be used when an instruction is
229     // found to be dead, replacable with another preexisting expression.  Here
230     // we add all uses of I to the worklist, replace all uses of I with the new
231     // value, then return I, so that the inst combiner will know that I was
232     // modified.
233     //
234     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
235       AddUsersToWorkList(I);         // Add all modified instrs to worklist
236       if (&I != V) {
237         I.replaceAllUsesWith(V);
238         return &I;
239       } else {
240         // If we are replacing the instruction with itself, this must be in a
241         // segment of unreachable code, so just clobber the instruction.
242         I.replaceAllUsesWith(UndefValue::get(I.getType()));
243         return &I;
244       }
245     }
246
247     // UpdateValueUsesWith - This method is to be used when an value is
248     // found to be replacable with another preexisting expression or was
249     // updated.  Here we add all uses of I to the worklist, replace all uses of
250     // I with the new value (unless the instruction was just updated), then
251     // return true, so that the inst combiner will know that I was modified.
252     //
253     bool UpdateValueUsesWith(Value *Old, Value *New) {
254       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
255       if (Old != New)
256         Old->replaceAllUsesWith(New);
257       if (Instruction *I = dyn_cast<Instruction>(Old))
258         WorkList.push_back(I);
259       if (Instruction *I = dyn_cast<Instruction>(New))
260         WorkList.push_back(I);
261       return true;
262     }
263     
264     // EraseInstFromFunction - When dealing with an instruction that has side
265     // effects or produces a void value, we can't rely on DCE to delete the
266     // instruction.  Instead, visit methods should return the value returned by
267     // this function.
268     Instruction *EraseInstFromFunction(Instruction &I) {
269       assert(I.use_empty() && "Cannot erase instruction that is used!");
270       AddUsesToWorkList(I);
271       removeFromWorkList(&I);
272       I.eraseFromParent();
273       return 0;  // Don't do anything with FI
274     }
275
276   private:
277     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
278     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
279     /// casts that are known to not do anything...
280     ///
281     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
282                                    Value *V, const Type *DestTy,
283                                    Instruction *InsertBefore);
284
285     /// SimplifyCommutative - This performs a few simplifications for 
286     /// commutative operators.
287     bool SimplifyCommutative(BinaryOperator &I);
288
289     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
290     /// most-complex to least-complex order.
291     bool SimplifyCompare(CmpInst &I);
292
293     bool SimplifyDemandedBits(Value *V, uint64_t Mask, 
294                               uint64_t &KnownZero, uint64_t &KnownOne,
295                               unsigned Depth = 0);
296
297     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
298                                       uint64_t &UndefElts, unsigned Depth = 0);
299       
300     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
301     // PHI node as operand #0, see if we can fold the instruction into the PHI
302     // (which is only possible if all operands to the PHI are constants).
303     Instruction *FoldOpIntoPhi(Instruction &I);
304
305     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
306     // operator and they all are only used by the PHI, PHI together their
307     // inputs, and do the operation once, to the result of the PHI.
308     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
309     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
310     
311     
312     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
313                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
314     
315     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
316                               bool isSub, Instruction &I);
317     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
318                                  bool isSigned, bool Inside, Instruction &IB);
319     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
320     Instruction *MatchBSwap(BinaryOperator &I);
321
322     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
323   };
324
325   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
326 }
327
328 // getComplexity:  Assign a complexity or rank value to LLVM Values...
329 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
330 static unsigned getComplexity(Value *V) {
331   if (isa<Instruction>(V)) {
332     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
333       return 3;
334     return 4;
335   }
336   if (isa<Argument>(V)) return 3;
337   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
338 }
339
340 // isOnlyUse - Return true if this instruction will be deleted if we stop using
341 // it.
342 static bool isOnlyUse(Value *V) {
343   return V->hasOneUse() || isa<Constant>(V);
344 }
345
346 // getPromotedType - Return the specified type promoted as it would be to pass
347 // though a va_arg area...
348 static const Type *getPromotedType(const Type *Ty) {
349   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
350     if (ITy->getBitWidth() < 32)
351       return Type::Int32Ty;
352   } else if (Ty == Type::FloatTy)
353     return Type::DoubleTy;
354   return Ty;
355 }
356
357 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
358 /// expression bitcast,  return the operand value, otherwise return null.
359 static Value *getBitCastOperand(Value *V) {
360   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
361     return I->getOperand(0);
362   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
363     if (CE->getOpcode() == Instruction::BitCast)
364       return CE->getOperand(0);
365   return 0;
366 }
367
368 /// This function is a wrapper around CastInst::isEliminableCastPair. It
369 /// simply extracts arguments and returns what that function returns.
370 static Instruction::CastOps 
371 isEliminableCastPair(
372   const CastInst *CI, ///< The first cast instruction
373   unsigned opcode,       ///< The opcode of the second cast instruction
374   const Type *DstTy,     ///< The target type for the second cast instruction
375   TargetData *TD         ///< The target data for pointer size
376 ) {
377   
378   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
379   const Type *MidTy = CI->getType();                  // B from above
380
381   // Get the opcodes of the two Cast instructions
382   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
383   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
384
385   return Instruction::CastOps(
386       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
387                                      DstTy, TD->getIntPtrType()));
388 }
389
390 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
391 /// in any code being generated.  It does not require codegen if V is simple
392 /// enough or if the cast can be folded into other casts.
393 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
394                               const Type *Ty, TargetData *TD) {
395   if (V->getType() == Ty || isa<Constant>(V)) return false;
396   
397   // If this is another cast that can be eliminated, it isn't codegen either.
398   if (const CastInst *CI = dyn_cast<CastInst>(V))
399     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
400       return false;
401   return true;
402 }
403
404 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
405 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
406 /// casts that are known to not do anything...
407 ///
408 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
409                                              Value *V, const Type *DestTy,
410                                              Instruction *InsertBefore) {
411   if (V->getType() == DestTy) return V;
412   if (Constant *C = dyn_cast<Constant>(V))
413     return ConstantExpr::getCast(opcode, C, DestTy);
414   
415   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
416 }
417
418 // SimplifyCommutative - This performs a few simplifications for commutative
419 // operators:
420 //
421 //  1. Order operands such that they are listed from right (least complex) to
422 //     left (most complex).  This puts constants before unary operators before
423 //     binary operators.
424 //
425 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
426 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
427 //
428 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
429   bool Changed = false;
430   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
431     Changed = !I.swapOperands();
432
433   if (!I.isAssociative()) return Changed;
434   Instruction::BinaryOps Opcode = I.getOpcode();
435   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
436     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
437       if (isa<Constant>(I.getOperand(1))) {
438         Constant *Folded = ConstantExpr::get(I.getOpcode(),
439                                              cast<Constant>(I.getOperand(1)),
440                                              cast<Constant>(Op->getOperand(1)));
441         I.setOperand(0, Op->getOperand(0));
442         I.setOperand(1, Folded);
443         return true;
444       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
445         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
446             isOnlyUse(Op) && isOnlyUse(Op1)) {
447           Constant *C1 = cast<Constant>(Op->getOperand(1));
448           Constant *C2 = cast<Constant>(Op1->getOperand(1));
449
450           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
451           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
452           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
453                                                     Op1->getOperand(0),
454                                                     Op1->getName(), &I);
455           WorkList.push_back(New);
456           I.setOperand(0, New);
457           I.setOperand(1, Folded);
458           return true;
459         }
460     }
461   return Changed;
462 }
463
464 /// SimplifyCompare - For a CmpInst this function just orders the operands
465 /// so that theyare listed from right (least complex) to left (most complex).
466 /// This puts constants before unary operators before binary operators.
467 bool InstCombiner::SimplifyCompare(CmpInst &I) {
468   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
469     return false;
470   I.swapOperands();
471   // Compare instructions are not associative so there's nothing else we can do.
472   return true;
473 }
474
475 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
476 // if the LHS is a constant zero (which is the 'negate' form).
477 //
478 static inline Value *dyn_castNegVal(Value *V) {
479   if (BinaryOperator::isNeg(V))
480     return BinaryOperator::getNegArgument(V);
481
482   // Constants can be considered to be negated values if they can be folded.
483   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
484     return ConstantExpr::getNeg(C);
485   return 0;
486 }
487
488 static inline Value *dyn_castNotVal(Value *V) {
489   if (BinaryOperator::isNot(V))
490     return BinaryOperator::getNotArgument(V);
491
492   // Constants can be considered to be not'ed values...
493   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
494     return ConstantExpr::getNot(C);
495   return 0;
496 }
497
498 // dyn_castFoldableMul - If this value is a multiply that can be folded into
499 // other computations (because it has a constant operand), return the
500 // non-constant operand of the multiply, and set CST to point to the multiplier.
501 // Otherwise, return null.
502 //
503 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
504   if (V->hasOneUse() && V->getType()->isInteger())
505     if (Instruction *I = dyn_cast<Instruction>(V)) {
506       if (I->getOpcode() == Instruction::Mul)
507         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
508           return I->getOperand(0);
509       if (I->getOpcode() == Instruction::Shl)
510         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
511           // The multiplier is really 1 << CST.
512           Constant *One = ConstantInt::get(V->getType(), 1);
513           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
514           return I->getOperand(0);
515         }
516     }
517   return 0;
518 }
519
520 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
521 /// expression, return it.
522 static User *dyn_castGetElementPtr(Value *V) {
523   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
524   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
525     if (CE->getOpcode() == Instruction::GetElementPtr)
526       return cast<User>(V);
527   return false;
528 }
529
530 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
531 static ConstantInt *AddOne(ConstantInt *C) {
532   return cast<ConstantInt>(ConstantExpr::getAdd(C,
533                                          ConstantInt::get(C->getType(), 1)));
534 }
535 static ConstantInt *SubOne(ConstantInt *C) {
536   return cast<ConstantInt>(ConstantExpr::getSub(C,
537                                          ConstantInt::get(C->getType(), 1)));
538 }
539
540 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
541 /// known to be either zero or one and return them in the KnownZero/KnownOne
542 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
543 /// processing.
544 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
545                               uint64_t &KnownOne, unsigned Depth = 0) {
546   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
547   // we cannot optimize based on the assumption that it is zero without changing
548   // it to be an explicit zero.  If we don't change it to zero, other code could
549   // optimized based on the contradictory assumption that it is non-zero.
550   // Because instcombine aggressively folds operations with undef args anyway,
551   // this won't lose us code quality.
552   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
553     // We know all of the bits for a constant!
554     KnownOne = CI->getZExtValue() & Mask;
555     KnownZero = ~KnownOne & Mask;
556     return;
557   }
558
559   KnownZero = KnownOne = 0;   // Don't know anything.
560   if (Depth == 6 || Mask == 0)
561     return;  // Limit search depth.
562
563   uint64_t KnownZero2, KnownOne2;
564   Instruction *I = dyn_cast<Instruction>(V);
565   if (!I) return;
566
567   Mask &= cast<IntegerType>(V->getType())->getBitMask();
568   
569   switch (I->getOpcode()) {
570   case Instruction::And:
571     // If either the LHS or the RHS are Zero, the result is zero.
572     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
573     Mask &= ~KnownZero;
574     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
575     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
576     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
577     
578     // Output known-1 bits are only known if set in both the LHS & RHS.
579     KnownOne &= KnownOne2;
580     // Output known-0 are known to be clear if zero in either the LHS | RHS.
581     KnownZero |= KnownZero2;
582     return;
583   case Instruction::Or:
584     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
585     Mask &= ~KnownOne;
586     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
587     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
588     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
589     
590     // Output known-0 bits are only known if clear in both the LHS & RHS.
591     KnownZero &= KnownZero2;
592     // Output known-1 are known to be set if set in either the LHS | RHS.
593     KnownOne |= KnownOne2;
594     return;
595   case Instruction::Xor: {
596     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
597     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
598     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
599     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
600     
601     // Output known-0 bits are known if clear or set in both the LHS & RHS.
602     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
603     // Output known-1 are known to be set if set in only one of the LHS, RHS.
604     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
605     KnownZero = KnownZeroOut;
606     return;
607   }
608   case Instruction::Select:
609     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
610     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
611     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
612     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
613
614     // Only known if known in both the LHS and RHS.
615     KnownOne &= KnownOne2;
616     KnownZero &= KnownZero2;
617     return;
618   case Instruction::FPTrunc:
619   case Instruction::FPExt:
620   case Instruction::FPToUI:
621   case Instruction::FPToSI:
622   case Instruction::SIToFP:
623   case Instruction::PtrToInt:
624   case Instruction::UIToFP:
625   case Instruction::IntToPtr:
626     return; // Can't work with floating point or pointers
627   case Instruction::Trunc: 
628     // All these have integer operands
629     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
630     return;
631   case Instruction::BitCast: {
632     const Type *SrcTy = I->getOperand(0)->getType();
633     if (SrcTy->isInteger()) {
634       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
635       return;
636     }
637     break;
638   }
639   case Instruction::ZExt:  {
640     // Compute the bits in the result that are not present in the input.
641     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
642     uint64_t NotIn = ~SrcTy->getBitMask();
643     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
644       
645     Mask &= SrcTy->getBitMask();
646     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
647     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
648     // The top bits are known to be zero.
649     KnownZero |= NewBits;
650     return;
651   }
652   case Instruction::SExt: {
653     // Compute the bits in the result that are not present in the input.
654     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
655     uint64_t NotIn = ~SrcTy->getBitMask();
656     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
657       
658     Mask &= SrcTy->getBitMask();
659     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
660     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
661
662     // If the sign bit of the input is known set or clear, then we know the
663     // top bits of the result.
664     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
665     if (KnownZero & InSignBit) {          // Input sign bit known zero
666       KnownZero |= NewBits;
667       KnownOne &= ~NewBits;
668     } else if (KnownOne & InSignBit) {    // Input sign bit known set
669       KnownOne |= NewBits;
670       KnownZero &= ~NewBits;
671     } else {                              // Input sign bit unknown
672       KnownZero &= ~NewBits;
673       KnownOne &= ~NewBits;
674     }
675     return;
676   }
677   case Instruction::Shl:
678     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
679     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
680       uint64_t ShiftAmt = SA->getZExtValue();
681       Mask >>= ShiftAmt;
682       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
683       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
684       KnownZero <<= ShiftAmt;
685       KnownOne  <<= ShiftAmt;
686       KnownZero |= (1ULL << ShiftAmt)-1;  // low bits known zero.
687       return;
688     }
689     break;
690   case Instruction::LShr:
691     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
692     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
693       // Compute the new bits that are at the top now.
694       uint64_t ShiftAmt = SA->getZExtValue();
695       uint64_t HighBits = (1ULL << ShiftAmt)-1;
696       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
697       
698       // Unsigned shift right.
699       Mask <<= ShiftAmt;
700       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
701       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
702       KnownZero >>= ShiftAmt;
703       KnownOne  >>= ShiftAmt;
704       KnownZero |= HighBits;  // high bits known zero.
705       return;
706     }
707     break;
708   case Instruction::AShr:
709     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
710     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
711       // Compute the new bits that are at the top now.
712       uint64_t ShiftAmt = SA->getZExtValue();
713       uint64_t HighBits = (1ULL << ShiftAmt)-1;
714       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
715       
716       // Signed shift right.
717       Mask <<= ShiftAmt;
718       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
719       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
720       KnownZero >>= ShiftAmt;
721       KnownOne  >>= ShiftAmt;
722         
723       // Handle the sign bits.
724       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
725       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
726         
727       if (KnownZero & SignBit) {       // New bits are known zero.
728         KnownZero |= HighBits;
729       } else if (KnownOne & SignBit) { // New bits are known one.
730         KnownOne |= HighBits;
731       }
732       return;
733     }
734     break;
735   }
736 }
737
738 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
739 /// this predicate to simplify operations downstream.  Mask is known to be zero
740 /// for bits that V cannot have.
741 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
742   uint64_t KnownZero, KnownOne;
743   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
744   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
745   return (KnownZero & Mask) == Mask;
746 }
747
748 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
749 /// specified instruction is a constant integer.  If so, check to see if there
750 /// are any bits set in the constant that are not demanded.  If so, shrink the
751 /// constant and return true.
752 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
753                                    uint64_t Demanded) {
754   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
755   if (!OpC) return false;
756
757   // If there are no bits set that aren't demanded, nothing to do.
758   if ((~Demanded & OpC->getZExtValue()) == 0)
759     return false;
760
761   // This is producing any bits that are not needed, shrink the RHS.
762   uint64_t Val = Demanded & OpC->getZExtValue();
763   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
764   return true;
765 }
766
767 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
768 // set of known zero and one bits, compute the maximum and minimum values that
769 // could have the specified known zero and known one bits, returning them in
770 // min/max.
771 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
772                                                    uint64_t KnownZero,
773                                                    uint64_t KnownOne,
774                                                    int64_t &Min, int64_t &Max) {
775   uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
776   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
777
778   uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
779   
780   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
781   // bit if it is unknown.
782   Min = KnownOne;
783   Max = KnownOne|UnknownBits;
784   
785   if (SignBit & UnknownBits) { // Sign bit is unknown
786     Min |= SignBit;
787     Max &= ~SignBit;
788   }
789   
790   // Sign extend the min/max values.
791   int ShAmt = 64-Ty->getPrimitiveSizeInBits();
792   Min = (Min << ShAmt) >> ShAmt;
793   Max = (Max << ShAmt) >> ShAmt;
794 }
795
796 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
797 // a set of known zero and one bits, compute the maximum and minimum values that
798 // could have the specified known zero and known one bits, returning them in
799 // min/max.
800 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
801                                                      uint64_t KnownZero,
802                                                      uint64_t KnownOne,
803                                                      uint64_t &Min,
804                                                      uint64_t &Max) {
805   uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
806   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
807   
808   // The minimum value is when the unknown bits are all zeros.
809   Min = KnownOne;
810   // The maximum value is when the unknown bits are all ones.
811   Max = KnownOne|UnknownBits;
812 }
813
814
815 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
816 /// DemandedMask bits of the result of V are ever used downstream.  If we can
817 /// use this information to simplify V, do so and return true.  Otherwise,
818 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
819 /// the expression (used to simplify the caller).  The KnownZero/One bits may
820 /// only be accurate for those bits in the DemandedMask.
821 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
822                                         uint64_t &KnownZero, uint64_t &KnownOne,
823                                         unsigned Depth) {
824   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
825     // We know all of the bits for a constant!
826     KnownOne = CI->getZExtValue() & DemandedMask;
827     KnownZero = ~KnownOne & DemandedMask;
828     return false;
829   }
830   
831   KnownZero = KnownOne = 0;
832   if (!V->hasOneUse()) {    // Other users may use these bits.
833     if (Depth != 0) {       // Not at the root.
834       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
835       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
836       return false;
837     }
838     // If this is the root being simplified, allow it to have multiple uses,
839     // just set the DemandedMask to all bits.
840     DemandedMask = cast<IntegerType>(V->getType())->getBitMask();
841   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
842     if (V != UndefValue::get(V->getType()))
843       return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
844     return false;
845   } else if (Depth == 6) {        // Limit search depth.
846     return false;
847   }
848   
849   Instruction *I = dyn_cast<Instruction>(V);
850   if (!I) return false;        // Only analyze instructions.
851
852   DemandedMask &= cast<IntegerType>(V->getType())->getBitMask();
853   
854   uint64_t KnownZero2 = 0, KnownOne2 = 0;
855   switch (I->getOpcode()) {
856   default: break;
857   case Instruction::And:
858     // If either the LHS or the RHS are Zero, the result is zero.
859     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
860                              KnownZero, KnownOne, Depth+1))
861       return true;
862     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
863
864     // If something is known zero on the RHS, the bits aren't demanded on the
865     // LHS.
866     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
867                              KnownZero2, KnownOne2, Depth+1))
868       return true;
869     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
870
871     // If all of the demanded bits are known 1 on one side, return the other.
872     // These bits cannot contribute to the result of the 'and'.
873     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
874       return UpdateValueUsesWith(I, I->getOperand(0));
875     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
876       return UpdateValueUsesWith(I, I->getOperand(1));
877     
878     // If all of the demanded bits in the inputs are known zeros, return zero.
879     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
880       return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
881       
882     // If the RHS is a constant, see if we can simplify it.
883     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
884       return UpdateValueUsesWith(I, I);
885       
886     // Output known-1 bits are only known if set in both the LHS & RHS.
887     KnownOne &= KnownOne2;
888     // Output known-0 are known to be clear if zero in either the LHS | RHS.
889     KnownZero |= KnownZero2;
890     break;
891   case Instruction::Or:
892     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
893                              KnownZero, KnownOne, Depth+1))
894       return true;
895     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
896     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
897                              KnownZero2, KnownOne2, Depth+1))
898       return true;
899     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
900     
901     // If all of the demanded bits are known zero on one side, return the other.
902     // These bits cannot contribute to the result of the 'or'.
903     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
904       return UpdateValueUsesWith(I, I->getOperand(0));
905     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
906       return UpdateValueUsesWith(I, I->getOperand(1));
907
908     // If all of the potentially set bits on one side are known to be set on
909     // the other side, just use the 'other' side.
910     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
911         (DemandedMask & (~KnownZero)))
912       return UpdateValueUsesWith(I, I->getOperand(0));
913     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
914         (DemandedMask & (~KnownZero2)))
915       return UpdateValueUsesWith(I, I->getOperand(1));
916         
917     // If the RHS is a constant, see if we can simplify it.
918     if (ShrinkDemandedConstant(I, 1, DemandedMask))
919       return UpdateValueUsesWith(I, I);
920           
921     // Output known-0 bits are only known if clear in both the LHS & RHS.
922     KnownZero &= KnownZero2;
923     // Output known-1 are known to be set if set in either the LHS | RHS.
924     KnownOne |= KnownOne2;
925     break;
926   case Instruction::Xor: {
927     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
928                              KnownZero, KnownOne, Depth+1))
929       return true;
930     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
931     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
932                              KnownZero2, KnownOne2, Depth+1))
933       return true;
934     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
935     
936     // If all of the demanded bits are known zero on one side, return the other.
937     // These bits cannot contribute to the result of the 'xor'.
938     if ((DemandedMask & KnownZero) == DemandedMask)
939       return UpdateValueUsesWith(I, I->getOperand(0));
940     if ((DemandedMask & KnownZero2) == DemandedMask)
941       return UpdateValueUsesWith(I, I->getOperand(1));
942     
943     // Output known-0 bits are known if clear or set in both the LHS & RHS.
944     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
945     // Output known-1 are known to be set if set in only one of the LHS, RHS.
946     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
947     
948     // If all of the demanded bits are known to be zero on one side or the
949     // other, turn this into an *inclusive* or.
950     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
951     if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
952       Instruction *Or =
953         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
954                                  I->getName());
955       InsertNewInstBefore(Or, *I);
956       return UpdateValueUsesWith(I, Or);
957     }
958     
959     // If all of the demanded bits on one side are known, and all of the set
960     // bits on that side are also known to be set on the other side, turn this
961     // into an AND, as we know the bits will be cleared.
962     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
963     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
964       if ((KnownOne & KnownOne2) == KnownOne) {
965         Constant *AndC = ConstantInt::get(I->getType(), 
966                                           ~KnownOne & DemandedMask);
967         Instruction *And = 
968           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
969         InsertNewInstBefore(And, *I);
970         return UpdateValueUsesWith(I, And);
971       }
972     }
973     
974     // If the RHS is a constant, see if we can simplify it.
975     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
976     if (ShrinkDemandedConstant(I, 1, DemandedMask))
977       return UpdateValueUsesWith(I, I);
978     
979     KnownZero = KnownZeroOut;
980     KnownOne  = KnownOneOut;
981     break;
982   }
983   case Instruction::Select:
984     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
985                              KnownZero, KnownOne, Depth+1))
986       return true;
987     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
988                              KnownZero2, KnownOne2, Depth+1))
989       return true;
990     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
991     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
992     
993     // If the operands are constants, see if we can simplify them.
994     if (ShrinkDemandedConstant(I, 1, DemandedMask))
995       return UpdateValueUsesWith(I, I);
996     if (ShrinkDemandedConstant(I, 2, DemandedMask))
997       return UpdateValueUsesWith(I, I);
998     
999     // Only known if known in both the LHS and RHS.
1000     KnownOne &= KnownOne2;
1001     KnownZero &= KnownZero2;
1002     break;
1003   case Instruction::Trunc:
1004     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1005                              KnownZero, KnownOne, Depth+1))
1006       return true;
1007     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1008     break;
1009   case Instruction::BitCast:
1010     if (!I->getOperand(0)->getType()->isInteger())
1011       return false;
1012       
1013     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1014                              KnownZero, KnownOne, Depth+1))
1015       return true;
1016     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1017     break;
1018   case Instruction::ZExt: {
1019     // Compute the bits in the result that are not present in the input.
1020     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1021     uint64_t NotIn = ~SrcTy->getBitMask();
1022     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
1023     
1024     DemandedMask &= SrcTy->getBitMask();
1025     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1026                              KnownZero, KnownOne, Depth+1))
1027       return true;
1028     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1029     // The top bits are known to be zero.
1030     KnownZero |= NewBits;
1031     break;
1032   }
1033   case Instruction::SExt: {
1034     // Compute the bits in the result that are not present in the input.
1035     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1036     uint64_t NotIn = ~SrcTy->getBitMask();
1037     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
1038     
1039     // Get the sign bit for the source type
1040     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1041     int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
1042
1043     // If any of the sign extended bits are demanded, we know that the sign
1044     // bit is demanded.
1045     if (NewBits & DemandedMask)
1046       InputDemandedBits |= InSignBit;
1047       
1048     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1049                              KnownZero, KnownOne, Depth+1))
1050       return true;
1051     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1052       
1053     // If the sign bit of the input is known set or clear, then we know the
1054     // top bits of the result.
1055
1056     // If the input sign bit is known zero, or if the NewBits are not demanded
1057     // convert this into a zero extension.
1058     if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1059       // Convert to ZExt cast
1060       CastInst *NewCast = CastInst::create(
1061         Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1062       return UpdateValueUsesWith(I, NewCast);
1063     } else if (KnownOne & InSignBit) {    // Input sign bit known set
1064       KnownOne |= NewBits;
1065       KnownZero &= ~NewBits;
1066     } else {                              // Input sign bit unknown
1067       KnownZero &= ~NewBits;
1068       KnownOne &= ~NewBits;
1069     }
1070     break;
1071   }
1072   case Instruction::Add:
1073     // If there is a constant on the RHS, there are a variety of xformations
1074     // we can do.
1075     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1076       // If null, this should be simplified elsewhere.  Some of the xforms here
1077       // won't work if the RHS is zero.
1078       if (RHS->isNullValue())
1079         break;
1080       
1081       // Figure out what the input bits are.  If the top bits of the and result
1082       // are not demanded, then the add doesn't demand them from its input
1083       // either.
1084       
1085       // Shift the demanded mask up so that it's at the top of the uint64_t.
1086       unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1087       unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1088       
1089       // If the top bit of the output is demanded, demand everything from the
1090       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1091       uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
1092
1093       // Find information about known zero/one bits in the input.
1094       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1095                                KnownZero2, KnownOne2, Depth+1))
1096         return true;
1097
1098       // If the RHS of the add has bits set that can't affect the input, reduce
1099       // the constant.
1100       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1101         return UpdateValueUsesWith(I, I);
1102       
1103       // Avoid excess work.
1104       if (KnownZero2 == 0 && KnownOne2 == 0)
1105         break;
1106       
1107       // Turn it into OR if input bits are zero.
1108       if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1109         Instruction *Or =
1110           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1111                                    I->getName());
1112         InsertNewInstBefore(Or, *I);
1113         return UpdateValueUsesWith(I, Or);
1114       }
1115       
1116       // We can say something about the output known-zero and known-one bits,
1117       // depending on potential carries from the input constant and the
1118       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1119       // bits set and the RHS constant is 0x01001, then we know we have a known
1120       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1121       
1122       // To compute this, we first compute the potential carry bits.  These are
1123       // the bits which may be modified.  I'm not aware of a better way to do
1124       // this scan.
1125       uint64_t RHSVal = RHS->getZExtValue();
1126       
1127       bool CarryIn = false;
1128       uint64_t CarryBits = 0;
1129       uint64_t CurBit = 1;
1130       for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1131         // Record the current carry in.
1132         if (CarryIn) CarryBits |= CurBit;
1133         
1134         bool CarryOut;
1135         
1136         // This bit has a carry out unless it is "zero + zero" or
1137         // "zero + anything" with no carry in.
1138         if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1139           CarryOut = false;  // 0 + 0 has no carry out, even with carry in.
1140         } else if (!CarryIn &&
1141                    ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1142           CarryOut = false;  // 0 + anything has no carry out if no carry in.
1143         } else {
1144           // Otherwise, we have to assume we have a carry out.
1145           CarryOut = true;
1146         }
1147         
1148         // This stage's carry out becomes the next stage's carry-in.
1149         CarryIn = CarryOut;
1150       }
1151       
1152       // Now that we know which bits have carries, compute the known-1/0 sets.
1153       
1154       // Bits are known one if they are known zero in one operand and one in the
1155       // other, and there is no input carry.
1156       KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1157       
1158       // Bits are known zero if they are known zero in both operands and there
1159       // is no input carry.
1160       KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1161     }
1162     break;
1163   case Instruction::Shl:
1164     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1165       uint64_t ShiftAmt = SA->getZExtValue();
1166       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt, 
1167                                KnownZero, KnownOne, Depth+1))
1168         return true;
1169       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1170       KnownZero <<= ShiftAmt;
1171       KnownOne  <<= ShiftAmt;
1172       KnownZero |= (1ULL << ShiftAmt) - 1;  // low bits known zero.
1173     }
1174     break;
1175   case Instruction::LShr:
1176     // For a logical shift right
1177     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1178       unsigned ShiftAmt = SA->getZExtValue();
1179       
1180       // Compute the new bits that are at the top now.
1181       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1182       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1183       uint64_t TypeMask = cast<IntegerType>(I->getType())->getBitMask();
1184       // Unsigned shift right.
1185       if (SimplifyDemandedBits(I->getOperand(0),
1186                               (DemandedMask << ShiftAmt) & TypeMask,
1187                                KnownZero, KnownOne, Depth+1))
1188         return true;
1189       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1190       KnownZero &= TypeMask;
1191       KnownOne  &= TypeMask;
1192       KnownZero >>= ShiftAmt;
1193       KnownOne  >>= ShiftAmt;
1194       KnownZero |= HighBits;  // high bits known zero.
1195     }
1196     break;
1197   case Instruction::AShr:
1198     // If this is an arithmetic shift right and only the low-bit is set, we can
1199     // always convert this into a logical shr, even if the shift amount is
1200     // variable.  The low bit of the shift cannot be an input sign bit unless
1201     // the shift amount is >= the size of the datatype, which is undefined.
1202     if (DemandedMask == 1) {
1203       // Perform the logical shift right.
1204       Value *NewVal = BinaryOperator::createLShr(
1205                         I->getOperand(0), I->getOperand(1), I->getName());
1206       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1207       return UpdateValueUsesWith(I, NewVal);
1208     }    
1209     
1210     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1211       unsigned ShiftAmt = SA->getZExtValue();
1212       
1213       // Compute the new bits that are at the top now.
1214       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1215       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1216       uint64_t TypeMask = cast<IntegerType>(I->getType())->getBitMask();
1217       // Signed shift right.
1218       if (SimplifyDemandedBits(I->getOperand(0),
1219                                (DemandedMask << ShiftAmt) & TypeMask,
1220                                KnownZero, KnownOne, Depth+1))
1221         return true;
1222       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1223       KnownZero &= TypeMask;
1224       KnownOne  &= TypeMask;
1225       KnownZero >>= ShiftAmt;
1226       KnownOne  >>= ShiftAmt;
1227         
1228       // Handle the sign bits.
1229       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1230       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
1231         
1232       // If the input sign bit is known to be zero, or if none of the top bits
1233       // are demanded, turn this into an unsigned shift right.
1234       if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1235         // Perform the logical shift right.
1236         Value *NewVal = BinaryOperator::createLShr(
1237                           I->getOperand(0), SA, I->getName());
1238         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1239         return UpdateValueUsesWith(I, NewVal);
1240       } else if (KnownOne & SignBit) { // New bits are known one.
1241         KnownOne |= HighBits;
1242       }
1243     }
1244     break;
1245   }
1246   
1247   // If the client is only demanding bits that we know, return the known
1248   // constant.
1249   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1250     return UpdateValueUsesWith(I, ConstantInt::get(I->getType(), KnownOne));
1251   return false;
1252 }  
1253
1254
1255 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1256 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1257 /// actually used by the caller.  This method analyzes which elements of the
1258 /// operand are undef and returns that information in UndefElts.
1259 ///
1260 /// If the information about demanded elements can be used to simplify the
1261 /// operation, the operation is simplified, then the resultant value is
1262 /// returned.  This returns null if no change was made.
1263 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1264                                                 uint64_t &UndefElts,
1265                                                 unsigned Depth) {
1266   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1267   assert(VWidth <= 64 && "Vector too wide to analyze!");
1268   uint64_t EltMask = ~0ULL >> (64-VWidth);
1269   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1270          "Invalid DemandedElts!");
1271
1272   if (isa<UndefValue>(V)) {
1273     // If the entire vector is undefined, just return this info.
1274     UndefElts = EltMask;
1275     return 0;
1276   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1277     UndefElts = EltMask;
1278     return UndefValue::get(V->getType());
1279   }
1280   
1281   UndefElts = 0;
1282   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1283     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1284     Constant *Undef = UndefValue::get(EltTy);
1285
1286     std::vector<Constant*> Elts;
1287     for (unsigned i = 0; i != VWidth; ++i)
1288       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1289         Elts.push_back(Undef);
1290         UndefElts |= (1ULL << i);
1291       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1292         Elts.push_back(Undef);
1293         UndefElts |= (1ULL << i);
1294       } else {                               // Otherwise, defined.
1295         Elts.push_back(CP->getOperand(i));
1296       }
1297         
1298     // If we changed the constant, return it.
1299     Constant *NewCP = ConstantVector::get(Elts);
1300     return NewCP != CP ? NewCP : 0;
1301   } else if (isa<ConstantAggregateZero>(V)) {
1302     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1303     // set to undef.
1304     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1305     Constant *Zero = Constant::getNullValue(EltTy);
1306     Constant *Undef = UndefValue::get(EltTy);
1307     std::vector<Constant*> Elts;
1308     for (unsigned i = 0; i != VWidth; ++i)
1309       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1310     UndefElts = DemandedElts ^ EltMask;
1311     return ConstantVector::get(Elts);
1312   }
1313   
1314   if (!V->hasOneUse()) {    // Other users may use these bits.
1315     if (Depth != 0) {       // Not at the root.
1316       // TODO: Just compute the UndefElts information recursively.
1317       return false;
1318     }
1319     return false;
1320   } else if (Depth == 10) {        // Limit search depth.
1321     return false;
1322   }
1323   
1324   Instruction *I = dyn_cast<Instruction>(V);
1325   if (!I) return false;        // Only analyze instructions.
1326   
1327   bool MadeChange = false;
1328   uint64_t UndefElts2;
1329   Value *TmpV;
1330   switch (I->getOpcode()) {
1331   default: break;
1332     
1333   case Instruction::InsertElement: {
1334     // If this is a variable index, we don't know which element it overwrites.
1335     // demand exactly the same input as we produce.
1336     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1337     if (Idx == 0) {
1338       // Note that we can't propagate undef elt info, because we don't know
1339       // which elt is getting updated.
1340       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1341                                         UndefElts2, Depth+1);
1342       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1343       break;
1344     }
1345     
1346     // If this is inserting an element that isn't demanded, remove this
1347     // insertelement.
1348     unsigned IdxNo = Idx->getZExtValue();
1349     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1350       return AddSoonDeadInstToWorklist(*I, 0);
1351     
1352     // Otherwise, the element inserted overwrites whatever was there, so the
1353     // input demanded set is simpler than the output set.
1354     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1355                                       DemandedElts & ~(1ULL << IdxNo),
1356                                       UndefElts, Depth+1);
1357     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1358
1359     // The inserted element is defined.
1360     UndefElts |= 1ULL << IdxNo;
1361     break;
1362   }
1363     
1364   case Instruction::And:
1365   case Instruction::Or:
1366   case Instruction::Xor:
1367   case Instruction::Add:
1368   case Instruction::Sub:
1369   case Instruction::Mul:
1370     // div/rem demand all inputs, because they don't want divide by zero.
1371     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1372                                       UndefElts, Depth+1);
1373     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1374     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1375                                       UndefElts2, Depth+1);
1376     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1377       
1378     // Output elements are undefined if both are undefined.  Consider things
1379     // like undef&0.  The result is known zero, not undef.
1380     UndefElts &= UndefElts2;
1381     break;
1382     
1383   case Instruction::Call: {
1384     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1385     if (!II) break;
1386     switch (II->getIntrinsicID()) {
1387     default: break;
1388       
1389     // Binary vector operations that work column-wise.  A dest element is a
1390     // function of the corresponding input elements from the two inputs.
1391     case Intrinsic::x86_sse_sub_ss:
1392     case Intrinsic::x86_sse_mul_ss:
1393     case Intrinsic::x86_sse_min_ss:
1394     case Intrinsic::x86_sse_max_ss:
1395     case Intrinsic::x86_sse2_sub_sd:
1396     case Intrinsic::x86_sse2_mul_sd:
1397     case Intrinsic::x86_sse2_min_sd:
1398     case Intrinsic::x86_sse2_max_sd:
1399       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1400                                         UndefElts, Depth+1);
1401       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1402       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1403                                         UndefElts2, Depth+1);
1404       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1405
1406       // If only the low elt is demanded and this is a scalarizable intrinsic,
1407       // scalarize it now.
1408       if (DemandedElts == 1) {
1409         switch (II->getIntrinsicID()) {
1410         default: break;
1411         case Intrinsic::x86_sse_sub_ss:
1412         case Intrinsic::x86_sse_mul_ss:
1413         case Intrinsic::x86_sse2_sub_sd:
1414         case Intrinsic::x86_sse2_mul_sd:
1415           // TODO: Lower MIN/MAX/ABS/etc
1416           Value *LHS = II->getOperand(1);
1417           Value *RHS = II->getOperand(2);
1418           // Extract the element as scalars.
1419           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1420           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1421           
1422           switch (II->getIntrinsicID()) {
1423           default: assert(0 && "Case stmts out of sync!");
1424           case Intrinsic::x86_sse_sub_ss:
1425           case Intrinsic::x86_sse2_sub_sd:
1426             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1427                                                         II->getName()), *II);
1428             break;
1429           case Intrinsic::x86_sse_mul_ss:
1430           case Intrinsic::x86_sse2_mul_sd:
1431             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1432                                                          II->getName()), *II);
1433             break;
1434           }
1435           
1436           Instruction *New =
1437             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1438                                   II->getName());
1439           InsertNewInstBefore(New, *II);
1440           AddSoonDeadInstToWorklist(*II, 0);
1441           return New;
1442         }            
1443       }
1444         
1445       // Output elements are undefined if both are undefined.  Consider things
1446       // like undef&0.  The result is known zero, not undef.
1447       UndefElts &= UndefElts2;
1448       break;
1449     }
1450     break;
1451   }
1452   }
1453   return MadeChange ? I : 0;
1454 }
1455
1456 /// @returns true if the specified compare instruction is
1457 /// true when both operands are equal...
1458 /// @brief Determine if the ICmpInst returns true if both operands are equal
1459 static bool isTrueWhenEqual(ICmpInst &ICI) {
1460   ICmpInst::Predicate pred = ICI.getPredicate();
1461   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1462          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1463          pred == ICmpInst::ICMP_SLE;
1464 }
1465
1466 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1467 /// function is designed to check a chain of associative operators for a
1468 /// potential to apply a certain optimization.  Since the optimization may be
1469 /// applicable if the expression was reassociated, this checks the chain, then
1470 /// reassociates the expression as necessary to expose the optimization
1471 /// opportunity.  This makes use of a special Functor, which must define
1472 /// 'shouldApply' and 'apply' methods.
1473 ///
1474 template<typename Functor>
1475 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1476   unsigned Opcode = Root.getOpcode();
1477   Value *LHS = Root.getOperand(0);
1478
1479   // Quick check, see if the immediate LHS matches...
1480   if (F.shouldApply(LHS))
1481     return F.apply(Root);
1482
1483   // Otherwise, if the LHS is not of the same opcode as the root, return.
1484   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1485   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1486     // Should we apply this transform to the RHS?
1487     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1488
1489     // If not to the RHS, check to see if we should apply to the LHS...
1490     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1491       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1492       ShouldApply = true;
1493     }
1494
1495     // If the functor wants to apply the optimization to the RHS of LHSI,
1496     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1497     if (ShouldApply) {
1498       BasicBlock *BB = Root.getParent();
1499
1500       // Now all of the instructions are in the current basic block, go ahead
1501       // and perform the reassociation.
1502       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1503
1504       // First move the selected RHS to the LHS of the root...
1505       Root.setOperand(0, LHSI->getOperand(1));
1506
1507       // Make what used to be the LHS of the root be the user of the root...
1508       Value *ExtraOperand = TmpLHSI->getOperand(1);
1509       if (&Root == TmpLHSI) {
1510         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1511         return 0;
1512       }
1513       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1514       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1515       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1516       BasicBlock::iterator ARI = &Root; ++ARI;
1517       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1518       ARI = Root;
1519
1520       // Now propagate the ExtraOperand down the chain of instructions until we
1521       // get to LHSI.
1522       while (TmpLHSI != LHSI) {
1523         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1524         // Move the instruction to immediately before the chain we are
1525         // constructing to avoid breaking dominance properties.
1526         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1527         BB->getInstList().insert(ARI, NextLHSI);
1528         ARI = NextLHSI;
1529
1530         Value *NextOp = NextLHSI->getOperand(1);
1531         NextLHSI->setOperand(1, ExtraOperand);
1532         TmpLHSI = NextLHSI;
1533         ExtraOperand = NextOp;
1534       }
1535
1536       // Now that the instructions are reassociated, have the functor perform
1537       // the transformation...
1538       return F.apply(Root);
1539     }
1540
1541     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1542   }
1543   return 0;
1544 }
1545
1546
1547 // AddRHS - Implements: X + X --> X << 1
1548 struct AddRHS {
1549   Value *RHS;
1550   AddRHS(Value *rhs) : RHS(rhs) {}
1551   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1552   Instruction *apply(BinaryOperator &Add) const {
1553     return BinaryOperator::createShl(Add.getOperand(0),
1554                                   ConstantInt::get(Add.getType(), 1));
1555   }
1556 };
1557
1558 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1559 //                 iff C1&C2 == 0
1560 struct AddMaskingAnd {
1561   Constant *C2;
1562   AddMaskingAnd(Constant *c) : C2(c) {}
1563   bool shouldApply(Value *LHS) const {
1564     ConstantInt *C1;
1565     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1566            ConstantExpr::getAnd(C1, C2)->isNullValue();
1567   }
1568   Instruction *apply(BinaryOperator &Add) const {
1569     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1570   }
1571 };
1572
1573 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1574                                              InstCombiner *IC) {
1575   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1576     if (Constant *SOC = dyn_cast<Constant>(SO))
1577       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1578
1579     return IC->InsertNewInstBefore(CastInst::create(
1580           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1581   }
1582
1583   // Figure out if the constant is the left or the right argument.
1584   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1585   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1586
1587   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1588     if (ConstIsRHS)
1589       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1590     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1591   }
1592
1593   Value *Op0 = SO, *Op1 = ConstOperand;
1594   if (!ConstIsRHS)
1595     std::swap(Op0, Op1);
1596   Instruction *New;
1597   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1598     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1599   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1600     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1601                           SO->getName()+".cmp");
1602   else {
1603     assert(0 && "Unknown binary instruction type!");
1604     abort();
1605   }
1606   return IC->InsertNewInstBefore(New, I);
1607 }
1608
1609 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1610 // constant as the other operand, try to fold the binary operator into the
1611 // select arguments.  This also works for Cast instructions, which obviously do
1612 // not have a second operand.
1613 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1614                                      InstCombiner *IC) {
1615   // Don't modify shared select instructions
1616   if (!SI->hasOneUse()) return 0;
1617   Value *TV = SI->getOperand(1);
1618   Value *FV = SI->getOperand(2);
1619
1620   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1621     // Bool selects with constant operands can be folded to logical ops.
1622     if (SI->getType() == Type::Int1Ty) return 0;
1623
1624     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1625     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1626
1627     return new SelectInst(SI->getCondition(), SelectTrueVal,
1628                           SelectFalseVal);
1629   }
1630   return 0;
1631 }
1632
1633
1634 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1635 /// node as operand #0, see if we can fold the instruction into the PHI (which
1636 /// is only possible if all operands to the PHI are constants).
1637 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1638   PHINode *PN = cast<PHINode>(I.getOperand(0));
1639   unsigned NumPHIValues = PN->getNumIncomingValues();
1640   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1641
1642   // Check to see if all of the operands of the PHI are constants.  If there is
1643   // one non-constant value, remember the BB it is.  If there is more than one
1644   // or if *it* is a PHI, bail out.
1645   BasicBlock *NonConstBB = 0;
1646   for (unsigned i = 0; i != NumPHIValues; ++i)
1647     if (!isa<Constant>(PN->getIncomingValue(i))) {
1648       if (NonConstBB) return 0;  // More than one non-const value.
1649       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1650       NonConstBB = PN->getIncomingBlock(i);
1651       
1652       // If the incoming non-constant value is in I's block, we have an infinite
1653       // loop.
1654       if (NonConstBB == I.getParent())
1655         return 0;
1656     }
1657   
1658   // If there is exactly one non-constant value, we can insert a copy of the
1659   // operation in that block.  However, if this is a critical edge, we would be
1660   // inserting the computation one some other paths (e.g. inside a loop).  Only
1661   // do this if the pred block is unconditionally branching into the phi block.
1662   if (NonConstBB) {
1663     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1664     if (!BI || !BI->isUnconditional()) return 0;
1665   }
1666
1667   // Okay, we can do the transformation: create the new PHI node.
1668   PHINode *NewPN = new PHINode(I.getType(), "");
1669   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1670   InsertNewInstBefore(NewPN, *PN);
1671   NewPN->takeName(PN);
1672
1673   // Next, add all of the operands to the PHI.
1674   if (I.getNumOperands() == 2) {
1675     Constant *C = cast<Constant>(I.getOperand(1));
1676     for (unsigned i = 0; i != NumPHIValues; ++i) {
1677       Value *InV;
1678       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1679         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1680           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1681         else
1682           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1683       } else {
1684         assert(PN->getIncomingBlock(i) == NonConstBB);
1685         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1686           InV = BinaryOperator::create(BO->getOpcode(),
1687                                        PN->getIncomingValue(i), C, "phitmp",
1688                                        NonConstBB->getTerminator());
1689         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1690           InV = CmpInst::create(CI->getOpcode(), 
1691                                 CI->getPredicate(),
1692                                 PN->getIncomingValue(i), C, "phitmp",
1693                                 NonConstBB->getTerminator());
1694         else
1695           assert(0 && "Unknown binop!");
1696         
1697         WorkList.push_back(cast<Instruction>(InV));
1698       }
1699       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1700     }
1701   } else { 
1702     CastInst *CI = cast<CastInst>(&I);
1703     const Type *RetTy = CI->getType();
1704     for (unsigned i = 0; i != NumPHIValues; ++i) {
1705       Value *InV;
1706       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1707         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1708       } else {
1709         assert(PN->getIncomingBlock(i) == NonConstBB);
1710         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1711                                I.getType(), "phitmp", 
1712                                NonConstBB->getTerminator());
1713         WorkList.push_back(cast<Instruction>(InV));
1714       }
1715       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1716     }
1717   }
1718   return ReplaceInstUsesWith(I, NewPN);
1719 }
1720
1721 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1722   bool Changed = SimplifyCommutative(I);
1723   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1724
1725   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1726     // X + undef -> undef
1727     if (isa<UndefValue>(RHS))
1728       return ReplaceInstUsesWith(I, RHS);
1729
1730     // X + 0 --> X
1731     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1732       if (RHSC->isNullValue())
1733         return ReplaceInstUsesWith(I, LHS);
1734     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1735       if (CFP->isExactlyValue(-0.0))
1736         return ReplaceInstUsesWith(I, LHS);
1737     }
1738
1739     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1740       // X + (signbit) --> X ^ signbit
1741       uint64_t Val = CI->getZExtValue();
1742       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1743         return BinaryOperator::createXor(LHS, RHS);
1744       
1745       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1746       // (X & 254)+1 -> (X&254)|1
1747       uint64_t KnownZero, KnownOne;
1748       if (!isa<VectorType>(I.getType()) &&
1749           SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
1750                                KnownZero, KnownOne))
1751         return &I;
1752     }
1753
1754     if (isa<PHINode>(LHS))
1755       if (Instruction *NV = FoldOpIntoPhi(I))
1756         return NV;
1757     
1758     ConstantInt *XorRHS = 0;
1759     Value *XorLHS = 0;
1760     if (isa<ConstantInt>(RHSC) &&
1761         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1762       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1763       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1764       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1765       
1766       uint64_t C0080Val = 1ULL << 31;
1767       int64_t CFF80Val = -C0080Val;
1768       unsigned Size = 32;
1769       do {
1770         if (TySizeBits > Size) {
1771           bool Found = false;
1772           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1773           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1774           if (RHSSExt == CFF80Val) {
1775             if (XorRHS->getZExtValue() == C0080Val)
1776               Found = true;
1777           } else if (RHSZExt == C0080Val) {
1778             if (XorRHS->getSExtValue() == CFF80Val)
1779               Found = true;
1780           }
1781           if (Found) {
1782             // This is a sign extend if the top bits are known zero.
1783             uint64_t Mask = ~0ULL;
1784             Mask <<= 64-(TySizeBits-Size);
1785             Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
1786             if (!MaskedValueIsZero(XorLHS, Mask))
1787               Size = 0;  // Not a sign ext, but can't be any others either.
1788             goto FoundSExt;
1789           }
1790         }
1791         Size >>= 1;
1792         C0080Val >>= Size;
1793         CFF80Val >>= Size;
1794       } while (Size >= 8);
1795       
1796 FoundSExt:
1797       const Type *MiddleType = 0;
1798       switch (Size) {
1799       default: break;
1800       case 32: MiddleType = Type::Int32Ty; break;
1801       case 16: MiddleType = Type::Int16Ty; break;
1802       case 8:  MiddleType = Type::Int8Ty; break;
1803       }
1804       if (MiddleType) {
1805         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1806         InsertNewInstBefore(NewTrunc, I);
1807         return new SExtInst(NewTrunc, I.getType());
1808       }
1809     }
1810   }
1811
1812   // X + X --> X << 1
1813   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
1814     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1815
1816     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1817       if (RHSI->getOpcode() == Instruction::Sub)
1818         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1819           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1820     }
1821     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1822       if (LHSI->getOpcode() == Instruction::Sub)
1823         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1824           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1825     }
1826   }
1827
1828   // -A + B  -->  B - A
1829   if (Value *V = dyn_castNegVal(LHS))
1830     return BinaryOperator::createSub(RHS, V);
1831
1832   // A + -B  -->  A - B
1833   if (!isa<Constant>(RHS))
1834     if (Value *V = dyn_castNegVal(RHS))
1835       return BinaryOperator::createSub(LHS, V);
1836
1837
1838   ConstantInt *C2;
1839   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1840     if (X == RHS)   // X*C + X --> X * (C+1)
1841       return BinaryOperator::createMul(RHS, AddOne(C2));
1842
1843     // X*C1 + X*C2 --> X * (C1+C2)
1844     ConstantInt *C1;
1845     if (X == dyn_castFoldableMul(RHS, C1))
1846       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1847   }
1848
1849   // X + X*C --> X * (C+1)
1850   if (dyn_castFoldableMul(RHS, C2) == LHS)
1851     return BinaryOperator::createMul(LHS, AddOne(C2));
1852
1853   // X + ~X --> -1   since   ~X = -X-1
1854   if (dyn_castNotVal(LHS) == RHS ||
1855       dyn_castNotVal(RHS) == LHS)
1856     return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1857   
1858
1859   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1860   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1861     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1862       return R;
1863
1864   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1865     Value *X = 0;
1866     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
1867       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1868       return BinaryOperator::createSub(C, X);
1869     }
1870
1871     // (X & FF00) + xx00  -> (X+xx00) & FF00
1872     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1873       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1874       if (Anded == CRHS) {
1875         // See if all bits from the first bit set in the Add RHS up are included
1876         // in the mask.  First, get the rightmost bit.
1877         uint64_t AddRHSV = CRHS->getZExtValue();
1878
1879         // Form a mask of all bits from the lowest bit added through the top.
1880         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1881         AddRHSHighBits &= C2->getType()->getBitMask();
1882
1883         // See if the and mask includes all of these bits.
1884         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1885
1886         if (AddRHSHighBits == AddRHSHighBitsAnd) {
1887           // Okay, the xform is safe.  Insert the new add pronto.
1888           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1889                                                             LHS->getName()), I);
1890           return BinaryOperator::createAnd(NewAdd, C2);
1891         }
1892       }
1893     }
1894
1895     // Try to fold constant add into select arguments.
1896     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1897       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1898         return R;
1899   }
1900
1901   // add (cast *A to intptrtype) B -> 
1902   //   cast (GEP (cast *A to sbyte*) B) -> 
1903   //     intptrtype
1904   {
1905     CastInst *CI = dyn_cast<CastInst>(LHS);
1906     Value *Other = RHS;
1907     if (!CI) {
1908       CI = dyn_cast<CastInst>(RHS);
1909       Other = LHS;
1910     }
1911     if (CI && CI->getType()->isSized() && 
1912         (CI->getType()->getPrimitiveSizeInBits() == 
1913          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
1914         && isa<PointerType>(CI->getOperand(0)->getType())) {
1915       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
1916                                    PointerType::get(Type::Int8Ty), I);
1917       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1918       return new PtrToIntInst(I2, CI->getType());
1919     }
1920   }
1921
1922   return Changed ? &I : 0;
1923 }
1924
1925 // isSignBit - Return true if the value represented by the constant only has the
1926 // highest order bit set.
1927 static bool isSignBit(ConstantInt *CI) {
1928   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1929   return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1930 }
1931
1932 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1933   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1934
1935   if (Op0 == Op1)         // sub X, X  -> 0
1936     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1937
1938   // If this is a 'B = x-(-A)', change to B = x+A...
1939   if (Value *V = dyn_castNegVal(Op1))
1940     return BinaryOperator::createAdd(Op0, V);
1941
1942   if (isa<UndefValue>(Op0))
1943     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
1944   if (isa<UndefValue>(Op1))
1945     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
1946
1947   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1948     // Replace (-1 - A) with (~A)...
1949     if (C->isAllOnesValue())
1950       return BinaryOperator::createNot(Op1);
1951
1952     // C - ~X == X + (1+C)
1953     Value *X = 0;
1954     if (match(Op1, m_Not(m_Value(X))))
1955       return BinaryOperator::createAdd(X,
1956                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1957     // -(X >>u 31) -> (X >>s 31)
1958     // -(X >>s 31) -> (X >>u 31)
1959     if (C->isNullValue()) {
1960       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
1961         if (SI->getOpcode() == Instruction::LShr) {
1962           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1963             // Check to see if we are shifting out everything but the sign bit.
1964             if (CU->getZExtValue() == 
1965                 SI->getType()->getPrimitiveSizeInBits()-1) {
1966               // Ok, the transformation is safe.  Insert AShr.
1967               return BinaryOperator::create(Instruction::AShr, 
1968                                           SI->getOperand(0), CU, SI->getName());
1969             }
1970           }
1971         }
1972         else if (SI->getOpcode() == Instruction::AShr) {
1973           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1974             // Check to see if we are shifting out everything but the sign bit.
1975             if (CU->getZExtValue() == 
1976                 SI->getType()->getPrimitiveSizeInBits()-1) {
1977               // Ok, the transformation is safe.  Insert LShr. 
1978               return BinaryOperator::createLShr(
1979                                           SI->getOperand(0), CU, SI->getName());
1980             }
1981           }
1982         } 
1983     }
1984
1985     // Try to fold constant sub into select arguments.
1986     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1987       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1988         return R;
1989
1990     if (isa<PHINode>(Op0))
1991       if (Instruction *NV = FoldOpIntoPhi(I))
1992         return NV;
1993   }
1994
1995   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1996     if (Op1I->getOpcode() == Instruction::Add &&
1997         !Op0->getType()->isFPOrFPVector()) {
1998       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
1999         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2000       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2001         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2002       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2003         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2004           // C1-(X+C2) --> (C1-C2)-X
2005           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2006                                            Op1I->getOperand(0));
2007       }
2008     }
2009
2010     if (Op1I->hasOneUse()) {
2011       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2012       // is not used by anyone else...
2013       //
2014       if (Op1I->getOpcode() == Instruction::Sub &&
2015           !Op1I->getType()->isFPOrFPVector()) {
2016         // Swap the two operands of the subexpr...
2017         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2018         Op1I->setOperand(0, IIOp1);
2019         Op1I->setOperand(1, IIOp0);
2020
2021         // Create the new top level add instruction...
2022         return BinaryOperator::createAdd(Op0, Op1);
2023       }
2024
2025       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2026       //
2027       if (Op1I->getOpcode() == Instruction::And &&
2028           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2029         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2030
2031         Value *NewNot =
2032           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2033         return BinaryOperator::createAnd(Op0, NewNot);
2034       }
2035
2036       // 0 - (X sdiv C)  -> (X sdiv -C)
2037       if (Op1I->getOpcode() == Instruction::SDiv)
2038         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2039           if (CSI->isNullValue())
2040             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2041               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2042                                                ConstantExpr::getNeg(DivRHS));
2043
2044       // X - X*C --> X * (1-C)
2045       ConstantInt *C2 = 0;
2046       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2047         Constant *CP1 =
2048           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2049         return BinaryOperator::createMul(Op0, CP1);
2050       }
2051     }
2052   }
2053
2054   if (!Op0->getType()->isFPOrFPVector())
2055     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2056       if (Op0I->getOpcode() == Instruction::Add) {
2057         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2058           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2059         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2060           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2061       } else if (Op0I->getOpcode() == Instruction::Sub) {
2062         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2063           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2064       }
2065
2066   ConstantInt *C1;
2067   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2068     if (X == Op1) { // X*C - X --> X * (C-1)
2069       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2070       return BinaryOperator::createMul(Op1, CP1);
2071     }
2072
2073     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2074     if (X == dyn_castFoldableMul(Op1, C2))
2075       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2076   }
2077   return 0;
2078 }
2079
2080 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2081 /// really just returns true if the most significant (sign) bit is set.
2082 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2083   switch (pred) {
2084     case ICmpInst::ICMP_SLT: 
2085       // True if LHS s< RHS and RHS == 0
2086       return RHS->isNullValue();
2087     case ICmpInst::ICMP_SLE: 
2088       // True if LHS s<= RHS and RHS == -1
2089       return RHS->isAllOnesValue();
2090     case ICmpInst::ICMP_UGE: 
2091       // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2092       return RHS->getZExtValue() == (1ULL << 
2093         (RHS->getType()->getPrimitiveSizeInBits()-1));
2094     case ICmpInst::ICMP_UGT:
2095       // True if LHS u> RHS and RHS == high-bit-mask - 1
2096       return RHS->getZExtValue() ==
2097         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2098     default:
2099       return false;
2100   }
2101 }
2102
2103 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2104   bool Changed = SimplifyCommutative(I);
2105   Value *Op0 = I.getOperand(0);
2106
2107   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2108     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2109
2110   // Simplify mul instructions with a constant RHS...
2111   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2112     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2113
2114       // ((X << C1)*C2) == (X * (C2 << C1))
2115       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2116         if (SI->getOpcode() == Instruction::Shl)
2117           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2118             return BinaryOperator::createMul(SI->getOperand(0),
2119                                              ConstantExpr::getShl(CI, ShOp));
2120
2121       if (CI->isNullValue())
2122         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2123       if (CI->equalsInt(1))                  // X * 1  == X
2124         return ReplaceInstUsesWith(I, Op0);
2125       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2126         return BinaryOperator::createNeg(Op0, I.getName());
2127
2128       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2129       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2130         uint64_t C = Log2_64(Val);
2131         return BinaryOperator::createShl(Op0,
2132                                       ConstantInt::get(Op0->getType(), C));
2133       }
2134     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2135       if (Op1F->isNullValue())
2136         return ReplaceInstUsesWith(I, Op1);
2137
2138       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2139       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2140       if (Op1F->getValue() == 1.0)
2141         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2142     }
2143     
2144     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2145       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2146           isa<ConstantInt>(Op0I->getOperand(1))) {
2147         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2148         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2149                                                      Op1, "tmp");
2150         InsertNewInstBefore(Add, I);
2151         Value *C1C2 = ConstantExpr::getMul(Op1, 
2152                                            cast<Constant>(Op0I->getOperand(1)));
2153         return BinaryOperator::createAdd(Add, C1C2);
2154         
2155       }
2156
2157     // Try to fold constant mul into select arguments.
2158     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2159       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2160         return R;
2161
2162     if (isa<PHINode>(Op0))
2163       if (Instruction *NV = FoldOpIntoPhi(I))
2164         return NV;
2165   }
2166
2167   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2168     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2169       return BinaryOperator::createMul(Op0v, Op1v);
2170
2171   // If one of the operands of the multiply is a cast from a boolean value, then
2172   // we know the bool is either zero or one, so this is a 'masking' multiply.
2173   // See if we can simplify things based on how the boolean was originally
2174   // formed.
2175   CastInst *BoolCast = 0;
2176   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2177     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2178       BoolCast = CI;
2179   if (!BoolCast)
2180     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2181       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2182         BoolCast = CI;
2183   if (BoolCast) {
2184     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2185       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2186       const Type *SCOpTy = SCIOp0->getType();
2187
2188       // If the icmp is true iff the sign bit of X is set, then convert this
2189       // multiply into a shift/and combination.
2190       if (isa<ConstantInt>(SCIOp1) &&
2191           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
2192         // Shift the X value right to turn it into "all signbits".
2193         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2194                                           SCOpTy->getPrimitiveSizeInBits()-1);
2195         Value *V =
2196           InsertNewInstBefore(
2197             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2198                                             BoolCast->getOperand(0)->getName()+
2199                                             ".mask"), I);
2200
2201         // If the multiply type is not the same as the source type, sign extend
2202         // or truncate to the multiply type.
2203         if (I.getType() != V->getType()) {
2204           unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2205           unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2206           Instruction::CastOps opcode = 
2207             (SrcBits == DstBits ? Instruction::BitCast : 
2208              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2209           V = InsertCastBefore(opcode, V, I.getType(), I);
2210         }
2211
2212         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2213         return BinaryOperator::createAnd(V, OtherOp);
2214       }
2215     }
2216   }
2217
2218   return Changed ? &I : 0;
2219 }
2220
2221 /// This function implements the transforms on div instructions that work
2222 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2223 /// used by the visitors to those instructions.
2224 /// @brief Transforms common to all three div instructions
2225 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2226   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2227
2228   // undef / X -> 0
2229   if (isa<UndefValue>(Op0))
2230     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2231
2232   // X / undef -> undef
2233   if (isa<UndefValue>(Op1))
2234     return ReplaceInstUsesWith(I, Op1);
2235
2236   // Handle cases involving: div X, (select Cond, Y, Z)
2237   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2238     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2239     // same basic block, then we replace the select with Y, and the condition 
2240     // of the select with false (if the cond value is in the same BB).  If the
2241     // select has uses other than the div, this allows them to be simplified
2242     // also. Note that div X, Y is just as good as div X, 0 (undef)
2243     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2244       if (ST->isNullValue()) {
2245         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2246         if (CondI && CondI->getParent() == I.getParent())
2247           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2248         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2249           I.setOperand(1, SI->getOperand(2));
2250         else
2251           UpdateValueUsesWith(SI, SI->getOperand(2));
2252         return &I;
2253       }
2254
2255     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2256     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2257       if (ST->isNullValue()) {
2258         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2259         if (CondI && CondI->getParent() == I.getParent())
2260           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2261         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2262           I.setOperand(1, SI->getOperand(1));
2263         else
2264           UpdateValueUsesWith(SI, SI->getOperand(1));
2265         return &I;
2266       }
2267   }
2268
2269   return 0;
2270 }
2271
2272 /// This function implements the transforms common to both integer division
2273 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2274 /// division instructions.
2275 /// @brief Common integer divide transforms
2276 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2277   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2278
2279   if (Instruction *Common = commonDivTransforms(I))
2280     return Common;
2281
2282   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2283     // div X, 1 == X
2284     if (RHS->equalsInt(1))
2285       return ReplaceInstUsesWith(I, Op0);
2286
2287     // (X / C1) / C2  -> X / (C1*C2)
2288     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2289       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2290         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2291           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2292                                         ConstantExpr::getMul(RHS, LHSRHS));
2293         }
2294
2295     if (!RHS->isNullValue()) { // avoid X udiv 0
2296       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2297         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2298           return R;
2299       if (isa<PHINode>(Op0))
2300         if (Instruction *NV = FoldOpIntoPhi(I))
2301           return NV;
2302     }
2303   }
2304
2305   // 0 / X == 0, we don't need to preserve faults!
2306   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2307     if (LHS->equalsInt(0))
2308       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2309
2310   return 0;
2311 }
2312
2313 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2314   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2315
2316   // Handle the integer div common cases
2317   if (Instruction *Common = commonIDivTransforms(I))
2318     return Common;
2319
2320   // X udiv C^2 -> X >> C
2321   // Check to see if this is an unsigned division with an exact power of 2,
2322   // if so, convert to a right shift.
2323   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2324     if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
2325       if (isPowerOf2_64(Val)) {
2326         uint64_t ShiftAmt = Log2_64(Val);
2327         return BinaryOperator::createLShr(Op0, 
2328                                     ConstantInt::get(Op0->getType(), ShiftAmt));
2329       }
2330   }
2331
2332   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2333   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2334     if (RHSI->getOpcode() == Instruction::Shl &&
2335         isa<ConstantInt>(RHSI->getOperand(0))) {
2336       uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2337       if (isPowerOf2_64(C1)) {
2338         Value *N = RHSI->getOperand(1);
2339         const Type *NTy = N->getType();
2340         if (uint64_t C2 = Log2_64(C1)) {
2341           Constant *C2V = ConstantInt::get(NTy, C2);
2342           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2343         }
2344         return BinaryOperator::createLShr(Op0, N);
2345       }
2346     }
2347   }
2348   
2349   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2350   // where C1&C2 are powers of two.
2351   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2352     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2353       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) 
2354         if (!STO->isNullValue() && !STO->isNullValue()) {
2355           uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2356           if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2357             // Compute the shift amounts
2358             unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2359             // Construct the "on true" case of the select
2360             Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2361             Instruction *TSI = BinaryOperator::createLShr(
2362                                                    Op0, TC, SI->getName()+".t");
2363             TSI = InsertNewInstBefore(TSI, I);
2364     
2365             // Construct the "on false" case of the select
2366             Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2367             Instruction *FSI = BinaryOperator::createLShr(
2368                                                    Op0, FC, SI->getName()+".f");
2369             FSI = InsertNewInstBefore(FSI, I);
2370
2371             // construct the select instruction and return it.
2372             return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2373           }
2374         }
2375   }
2376   return 0;
2377 }
2378
2379 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2380   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2381
2382   // Handle the integer div common cases
2383   if (Instruction *Common = commonIDivTransforms(I))
2384     return Common;
2385
2386   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2387     // sdiv X, -1 == -X
2388     if (RHS->isAllOnesValue())
2389       return BinaryOperator::createNeg(Op0);
2390
2391     // -X/C -> X/-C
2392     if (Value *LHSNeg = dyn_castNegVal(Op0))
2393       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2394   }
2395
2396   // If the sign bits of both operands are zero (i.e. we can prove they are
2397   // unsigned inputs), turn this into a udiv.
2398   if (I.getType()->isInteger()) {
2399     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2400     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2401       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2402     }
2403   }      
2404   
2405   return 0;
2406 }
2407
2408 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2409   return commonDivTransforms(I);
2410 }
2411
2412 /// GetFactor - If we can prove that the specified value is at least a multiple
2413 /// of some factor, return that factor.
2414 static Constant *GetFactor(Value *V) {
2415   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2416     return CI;
2417   
2418   // Unless we can be tricky, we know this is a multiple of 1.
2419   Constant *Result = ConstantInt::get(V->getType(), 1);
2420   
2421   Instruction *I = dyn_cast<Instruction>(V);
2422   if (!I) return Result;
2423   
2424   if (I->getOpcode() == Instruction::Mul) {
2425     // Handle multiplies by a constant, etc.
2426     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2427                                 GetFactor(I->getOperand(1)));
2428   } else if (I->getOpcode() == Instruction::Shl) {
2429     // (X<<C) -> X * (1 << C)
2430     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2431       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2432       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2433     }
2434   } else if (I->getOpcode() == Instruction::And) {
2435     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2436       // X & 0xFFF0 is known to be a multiple of 16.
2437       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2438       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2439         return ConstantExpr::getShl(Result, 
2440                                     ConstantInt::get(Result->getType(), Zeros));
2441     }
2442   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2443     // Only handle int->int casts.
2444     if (!CI->isIntegerCast())
2445       return Result;
2446     Value *Op = CI->getOperand(0);
2447     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2448   }    
2449   return Result;
2450 }
2451
2452 /// This function implements the transforms on rem instructions that work
2453 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2454 /// is used by the visitors to those instructions.
2455 /// @brief Transforms common to all three rem instructions
2456 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2457   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2458
2459   // 0 % X == 0, we don't need to preserve faults!
2460   if (Constant *LHS = dyn_cast<Constant>(Op0))
2461     if (LHS->isNullValue())
2462       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2463
2464   if (isa<UndefValue>(Op0))              // undef % X -> 0
2465     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2466   if (isa<UndefValue>(Op1))
2467     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2468
2469   // Handle cases involving: rem X, (select Cond, Y, Z)
2470   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2471     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2472     // the same basic block, then we replace the select with Y, and the
2473     // condition of the select with false (if the cond value is in the same
2474     // BB).  If the select has uses other than the div, this allows them to be
2475     // simplified also.
2476     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2477       if (ST->isNullValue()) {
2478         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2479         if (CondI && CondI->getParent() == I.getParent())
2480           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2481         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2482           I.setOperand(1, SI->getOperand(2));
2483         else
2484           UpdateValueUsesWith(SI, SI->getOperand(2));
2485         return &I;
2486       }
2487     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2488     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2489       if (ST->isNullValue()) {
2490         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2491         if (CondI && CondI->getParent() == I.getParent())
2492           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2493         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2494           I.setOperand(1, SI->getOperand(1));
2495         else
2496           UpdateValueUsesWith(SI, SI->getOperand(1));
2497         return &I;
2498       }
2499   }
2500
2501   return 0;
2502 }
2503
2504 /// This function implements the transforms common to both integer remainder
2505 /// instructions (urem and srem). It is called by the visitors to those integer
2506 /// remainder instructions.
2507 /// @brief Common integer remainder transforms
2508 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2509   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2510
2511   if (Instruction *common = commonRemTransforms(I))
2512     return common;
2513
2514   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2515     // X % 0 == undef, we don't need to preserve faults!
2516     if (RHS->equalsInt(0))
2517       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2518     
2519     if (RHS->equalsInt(1))  // X % 1 == 0
2520       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2521
2522     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2523       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2524         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2525           return R;
2526       } else if (isa<PHINode>(Op0I)) {
2527         if (Instruction *NV = FoldOpIntoPhi(I))
2528           return NV;
2529       }
2530       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2531       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2532         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2533     }
2534   }
2535
2536   return 0;
2537 }
2538
2539 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2540   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2541
2542   if (Instruction *common = commonIRemTransforms(I))
2543     return common;
2544   
2545   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2546     // X urem C^2 -> X and C
2547     // Check to see if this is an unsigned remainder with an exact power of 2,
2548     // if so, convert to a bitwise and.
2549     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2550       if (isPowerOf2_64(C->getZExtValue()))
2551         return BinaryOperator::createAnd(Op0, SubOne(C));
2552   }
2553
2554   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2555     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2556     if (RHSI->getOpcode() == Instruction::Shl &&
2557         isa<ConstantInt>(RHSI->getOperand(0))) {
2558       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2559       if (isPowerOf2_64(C1)) {
2560         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2561         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2562                                                                    "tmp"), I);
2563         return BinaryOperator::createAnd(Op0, Add);
2564       }
2565     }
2566   }
2567
2568   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2569   // where C1&C2 are powers of two.
2570   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2571     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2572       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2573         // STO == 0 and SFO == 0 handled above.
2574         if (isPowerOf2_64(STO->getZExtValue()) && 
2575             isPowerOf2_64(SFO->getZExtValue())) {
2576           Value *TrueAnd = InsertNewInstBefore(
2577             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2578           Value *FalseAnd = InsertNewInstBefore(
2579             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2580           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2581         }
2582       }
2583   }
2584   
2585   return 0;
2586 }
2587
2588 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2589   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2590
2591   if (Instruction *common = commonIRemTransforms(I))
2592     return common;
2593   
2594   if (Value *RHSNeg = dyn_castNegVal(Op1))
2595     if (!isa<ConstantInt>(RHSNeg) || 
2596         cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2597       // X % -Y -> X % Y
2598       AddUsesToWorkList(I);
2599       I.setOperand(1, RHSNeg);
2600       return &I;
2601     }
2602  
2603   // If the top bits of both operands are zero (i.e. we can prove they are
2604   // unsigned inputs), turn this into a urem.
2605   uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2606   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2607     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2608     return BinaryOperator::createURem(Op0, Op1, I.getName());
2609   }
2610
2611   return 0;
2612 }
2613
2614 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2615   return commonRemTransforms(I);
2616 }
2617
2618 // isMaxValueMinusOne - return true if this is Max-1
2619 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2620   if (isSigned) {
2621     // Calculate 0111111111..11111
2622     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2623     int64_t Val = INT64_MAX;             // All ones
2624     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
2625     return C->getSExtValue() == Val-1;
2626   }
2627   return C->getZExtValue() == C->getType()->getBitMask()-1;
2628 }
2629
2630 // isMinValuePlusOne - return true if this is Min+1
2631 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2632   if (isSigned) {
2633     // Calculate 1111111111000000000000
2634     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2635     int64_t Val = -1;                    // All ones
2636     Val <<= TypeBits-1;                  // Shift over to the right spot
2637     return C->getSExtValue() == Val+1;
2638   }
2639   return C->getZExtValue() == 1; // unsigned
2640 }
2641
2642 // isOneBitSet - Return true if there is exactly one bit set in the specified
2643 // constant.
2644 static bool isOneBitSet(const ConstantInt *CI) {
2645   uint64_t V = CI->getZExtValue();
2646   return V && (V & (V-1)) == 0;
2647 }
2648
2649 #if 0   // Currently unused
2650 // isLowOnes - Return true if the constant is of the form 0+1+.
2651 static bool isLowOnes(const ConstantInt *CI) {
2652   uint64_t V = CI->getZExtValue();
2653
2654   // There won't be bits set in parts that the type doesn't contain.
2655   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2656
2657   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2658   return U && V && (U & V) == 0;
2659 }
2660 #endif
2661
2662 // isHighOnes - Return true if the constant is of the form 1+0+.
2663 // This is the same as lowones(~X).
2664 static bool isHighOnes(const ConstantInt *CI) {
2665   uint64_t V = ~CI->getZExtValue();
2666   if (~V == 0) return false;  // 0's does not match "1+"
2667
2668   // There won't be bits set in parts that the type doesn't contain.
2669   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2670
2671   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2672   return U && V && (U & V) == 0;
2673 }
2674
2675 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2676 /// are carefully arranged to allow folding of expressions such as:
2677 ///
2678 ///      (A < B) | (A > B) --> (A != B)
2679 ///
2680 /// Note that this is only valid if the first and second predicates have the
2681 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2682 ///
2683 /// Three bits are used to represent the condition, as follows:
2684 ///   0  A > B
2685 ///   1  A == B
2686 ///   2  A < B
2687 ///
2688 /// <=>  Value  Definition
2689 /// 000     0   Always false
2690 /// 001     1   A >  B
2691 /// 010     2   A == B
2692 /// 011     3   A >= B
2693 /// 100     4   A <  B
2694 /// 101     5   A != B
2695 /// 110     6   A <= B
2696 /// 111     7   Always true
2697 ///  
2698 static unsigned getICmpCode(const ICmpInst *ICI) {
2699   switch (ICI->getPredicate()) {
2700     // False -> 0
2701   case ICmpInst::ICMP_UGT: return 1;  // 001
2702   case ICmpInst::ICMP_SGT: return 1;  // 001
2703   case ICmpInst::ICMP_EQ:  return 2;  // 010
2704   case ICmpInst::ICMP_UGE: return 3;  // 011
2705   case ICmpInst::ICMP_SGE: return 3;  // 011
2706   case ICmpInst::ICMP_ULT: return 4;  // 100
2707   case ICmpInst::ICMP_SLT: return 4;  // 100
2708   case ICmpInst::ICMP_NE:  return 5;  // 101
2709   case ICmpInst::ICMP_ULE: return 6;  // 110
2710   case ICmpInst::ICMP_SLE: return 6;  // 110
2711     // True -> 7
2712   default:
2713     assert(0 && "Invalid ICmp predicate!");
2714     return 0;
2715   }
2716 }
2717
2718 /// getICmpValue - This is the complement of getICmpCode, which turns an
2719 /// opcode and two operands into either a constant true or false, or a brand 
2720 /// new /// ICmp instruction. The sign is passed in to determine which kind
2721 /// of predicate to use in new icmp instructions.
2722 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2723   switch (code) {
2724   default: assert(0 && "Illegal ICmp code!");
2725   case  0: return ConstantInt::getFalse();
2726   case  1: 
2727     if (sign)
2728       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2729     else
2730       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2731   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
2732   case  3: 
2733     if (sign)
2734       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2735     else
2736       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2737   case  4: 
2738     if (sign)
2739       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2740     else
2741       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2742   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
2743   case  6: 
2744     if (sign)
2745       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2746     else
2747       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2748   case  7: return ConstantInt::getTrue();
2749   }
2750 }
2751
2752 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2753   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2754     (ICmpInst::isSignedPredicate(p1) && 
2755      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2756     (ICmpInst::isSignedPredicate(p2) && 
2757      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2758 }
2759
2760 namespace { 
2761 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2762 struct FoldICmpLogical {
2763   InstCombiner &IC;
2764   Value *LHS, *RHS;
2765   ICmpInst::Predicate pred;
2766   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2767     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2768       pred(ICI->getPredicate()) {}
2769   bool shouldApply(Value *V) const {
2770     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2771       if (PredicatesFoldable(pred, ICI->getPredicate()))
2772         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2773                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2774     return false;
2775   }
2776   Instruction *apply(Instruction &Log) const {
2777     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2778     if (ICI->getOperand(0) != LHS) {
2779       assert(ICI->getOperand(1) == LHS);
2780       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
2781     }
2782
2783     unsigned LHSCode = getICmpCode(ICI);
2784     unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
2785     unsigned Code;
2786     switch (Log.getOpcode()) {
2787     case Instruction::And: Code = LHSCode & RHSCode; break;
2788     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2789     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2790     default: assert(0 && "Illegal logical opcode!"); return 0;
2791     }
2792
2793     Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
2794     if (Instruction *I = dyn_cast<Instruction>(RV))
2795       return I;
2796     // Otherwise, it's a constant boolean value...
2797     return IC.ReplaceInstUsesWith(Log, RV);
2798   }
2799 };
2800 } // end anonymous namespace
2801
2802 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2803 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2804 // guaranteed to be a binary operator.
2805 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2806                                     ConstantInt *OpRHS,
2807                                     ConstantInt *AndRHS,
2808                                     BinaryOperator &TheAnd) {
2809   Value *X = Op->getOperand(0);
2810   Constant *Together = 0;
2811   if (!Op->isShift())
2812     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2813
2814   switch (Op->getOpcode()) {
2815   case Instruction::Xor:
2816     if (Op->hasOneUse()) {
2817       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2818       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
2819       InsertNewInstBefore(And, TheAnd);
2820       And->takeName(Op);
2821       return BinaryOperator::createXor(And, Together);
2822     }
2823     break;
2824   case Instruction::Or:
2825     if (Together == AndRHS) // (X | C) & C --> C
2826       return ReplaceInstUsesWith(TheAnd, AndRHS);
2827
2828     if (Op->hasOneUse() && Together != OpRHS) {
2829       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2830       Instruction *Or = BinaryOperator::createOr(X, Together);
2831       InsertNewInstBefore(Or, TheAnd);
2832       Or->takeName(Op);
2833       return BinaryOperator::createAnd(Or, AndRHS);
2834     }
2835     break;
2836   case Instruction::Add:
2837     if (Op->hasOneUse()) {
2838       // Adding a one to a single bit bit-field should be turned into an XOR
2839       // of the bit.  First thing to check is to see if this AND is with a
2840       // single bit constant.
2841       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2842
2843       // Clear bits that are not part of the constant.
2844       AndRHSV &= AndRHS->getType()->getBitMask();
2845
2846       // If there is only one bit set...
2847       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2848         // Ok, at this point, we know that we are masking the result of the
2849         // ADD down to exactly one bit.  If the constant we are adding has
2850         // no bits set below this bit, then we can eliminate the ADD.
2851         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2852
2853         // Check to see if any bits below the one bit set in AndRHSV are set.
2854         if ((AddRHS & (AndRHSV-1)) == 0) {
2855           // If not, the only thing that can effect the output of the AND is
2856           // the bit specified by AndRHSV.  If that bit is set, the effect of
2857           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2858           // no effect.
2859           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2860             TheAnd.setOperand(0, X);
2861             return &TheAnd;
2862           } else {
2863             // Pull the XOR out of the AND.
2864             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
2865             InsertNewInstBefore(NewAnd, TheAnd);
2866             NewAnd->takeName(Op);
2867             return BinaryOperator::createXor(NewAnd, AndRHS);
2868           }
2869         }
2870       }
2871     }
2872     break;
2873
2874   case Instruction::Shl: {
2875     // We know that the AND will not produce any of the bits shifted in, so if
2876     // the anded constant includes them, clear them now!
2877     //
2878     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2879     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2880     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2881
2882     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2883       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2884     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2885       TheAnd.setOperand(1, CI);
2886       return &TheAnd;
2887     }
2888     break;
2889   }
2890   case Instruction::LShr:
2891   {
2892     // We know that the AND will not produce any of the bits shifted in, so if
2893     // the anded constant includes them, clear them now!  This only applies to
2894     // unsigned shifts, because a signed shr may bring in set bits!
2895     //
2896     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2897     Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2898     Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2899
2900     if (CI == ShrMask) {   // Masking out bits that the shift already masks.
2901       return ReplaceInstUsesWith(TheAnd, Op);
2902     } else if (CI != AndRHS) {
2903       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
2904       return &TheAnd;
2905     }
2906     break;
2907   }
2908   case Instruction::AShr:
2909     // Signed shr.
2910     // See if this is shifting in some sign extension, then masking it out
2911     // with an and.
2912     if (Op->hasOneUse()) {
2913       Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2914       Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2915       Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2916       if (C == AndRHS) {          // Masking out bits shifted in.
2917         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
2918         // Make the argument unsigned.
2919         Value *ShVal = Op->getOperand(0);
2920         ShVal = InsertNewInstBefore(
2921             BinaryOperator::createLShr(ShVal, OpRHS, 
2922                                    Op->getName()), TheAnd);
2923         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
2924       }
2925     }
2926     break;
2927   }
2928   return 0;
2929 }
2930
2931
2932 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2933 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
2934 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
2935 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
2936 /// insert new instructions.
2937 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2938                                            bool isSigned, bool Inside, 
2939                                            Instruction &IB) {
2940   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
2941             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
2942          "Lo is not <= Hi in range emission code!");
2943     
2944   if (Inside) {
2945     if (Lo == Hi)  // Trivially false.
2946       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
2947
2948     // V >= Min && V < Hi --> V < Hi
2949     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2950     ICmpInst::Predicate pred = (isSigned ? 
2951         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2952       return new ICmpInst(pred, V, Hi);
2953     }
2954
2955     // Emit V-Lo <u Hi-Lo
2956     Constant *NegLo = ConstantExpr::getNeg(Lo);
2957     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2958     InsertNewInstBefore(Add, IB);
2959     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2960     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
2961   }
2962
2963   if (Lo == Hi)  // Trivially true.
2964     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
2965
2966   // V < Min || V >= Hi ->'V > Hi-1'
2967   Hi = SubOne(cast<ConstantInt>(Hi));
2968   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2969     ICmpInst::Predicate pred = (isSigned ? 
2970         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
2971     return new ICmpInst(pred, V, Hi);
2972   }
2973
2974   // Emit V-Lo > Hi-1-Lo
2975   Constant *NegLo = ConstantExpr::getNeg(Lo);
2976   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2977   InsertNewInstBefore(Add, IB);
2978   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
2979   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
2980 }
2981
2982 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2983 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
2984 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
2985 // not, since all 1s are not contiguous.
2986 static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
2987   uint64_t V = Val->getZExtValue();
2988   if (!isShiftedMask_64(V)) return false;
2989
2990   // look for the first zero bit after the run of ones
2991   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2992   // look for the first non-zero bit
2993   ME = 64-CountLeadingZeros_64(V);
2994   return true;
2995 }
2996
2997
2998
2999 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3000 /// where isSub determines whether the operator is a sub.  If we can fold one of
3001 /// the following xforms:
3002 /// 
3003 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3004 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3005 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3006 ///
3007 /// return (A +/- B).
3008 ///
3009 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3010                                         ConstantInt *Mask, bool isSub,
3011                                         Instruction &I) {
3012   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3013   if (!LHSI || LHSI->getNumOperands() != 2 ||
3014       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3015
3016   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3017
3018   switch (LHSI->getOpcode()) {
3019   default: return 0;
3020   case Instruction::And:
3021     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3022       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3023       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3024         break;
3025
3026       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3027       // part, we don't need any explicit masks to take them out of A.  If that
3028       // is all N is, ignore it.
3029       unsigned MB, ME;
3030       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3031         uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
3032         Mask >>= 64-MB+1;
3033         if (MaskedValueIsZero(RHS, Mask))
3034           break;
3035       }
3036     }
3037     return 0;
3038   case Instruction::Or:
3039   case Instruction::Xor:
3040     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3041     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3042         ConstantExpr::getAnd(N, Mask)->isNullValue())
3043       break;
3044     return 0;
3045   }
3046   
3047   Instruction *New;
3048   if (isSub)
3049     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3050   else
3051     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3052   return InsertNewInstBefore(New, I);
3053 }
3054
3055 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3056   bool Changed = SimplifyCommutative(I);
3057   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3058
3059   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3060     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3061
3062   // and X, X = X
3063   if (Op0 == Op1)
3064     return ReplaceInstUsesWith(I, Op1);
3065
3066   // See if we can simplify any instructions used by the instruction whose sole 
3067   // purpose is to compute bits we don't care about.
3068   uint64_t KnownZero, KnownOne;
3069   if (!isa<VectorType>(I.getType())) {
3070     if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3071                              KnownZero, KnownOne))
3072     return &I;
3073   } else {
3074     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3075       if (CP->isAllOnesValue())
3076         return ReplaceInstUsesWith(I, I.getOperand(0));
3077     }
3078   }
3079   
3080   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3081     uint64_t AndRHSMask = AndRHS->getZExtValue();
3082     uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
3083     uint64_t NotAndRHS = AndRHSMask^TypeMask;
3084
3085     // Optimize a variety of ((val OP C1) & C2) combinations...
3086     if (isa<BinaryOperator>(Op0)) {
3087       Instruction *Op0I = cast<Instruction>(Op0);
3088       Value *Op0LHS = Op0I->getOperand(0);
3089       Value *Op0RHS = Op0I->getOperand(1);
3090       switch (Op0I->getOpcode()) {
3091       case Instruction::Xor:
3092       case Instruction::Or:
3093         // If the mask is only needed on one incoming arm, push it up.
3094         if (Op0I->hasOneUse()) {
3095           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3096             // Not masking anything out for the LHS, move to RHS.
3097             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3098                                                    Op0RHS->getName()+".masked");
3099             InsertNewInstBefore(NewRHS, I);
3100             return BinaryOperator::create(
3101                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3102           }
3103           if (!isa<Constant>(Op0RHS) &&
3104               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3105             // Not masking anything out for the RHS, move to LHS.
3106             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3107                                                    Op0LHS->getName()+".masked");
3108             InsertNewInstBefore(NewLHS, I);
3109             return BinaryOperator::create(
3110                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3111           }
3112         }
3113
3114         break;
3115       case Instruction::Add:
3116         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3117         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3118         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3119         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3120           return BinaryOperator::createAnd(V, AndRHS);
3121         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3122           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3123         break;
3124
3125       case Instruction::Sub:
3126         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3127         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3128         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3129         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3130           return BinaryOperator::createAnd(V, AndRHS);
3131         break;
3132       }
3133
3134       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3135         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3136           return Res;
3137     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3138       // If this is an integer truncation or change from signed-to-unsigned, and
3139       // if the source is an and/or with immediate, transform it.  This
3140       // frequently occurs for bitfield accesses.
3141       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3142         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3143             CastOp->getNumOperands() == 2)
3144           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3145             if (CastOp->getOpcode() == Instruction::And) {
3146               // Change: and (cast (and X, C1) to T), C2
3147               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3148               // This will fold the two constants together, which may allow 
3149               // other simplifications.
3150               Instruction *NewCast = CastInst::createTruncOrBitCast(
3151                 CastOp->getOperand(0), I.getType(), 
3152                 CastOp->getName()+".shrunk");
3153               NewCast = InsertNewInstBefore(NewCast, I);
3154               // trunc_or_bitcast(C1)&C2
3155               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3156               C3 = ConstantExpr::getAnd(C3, AndRHS);
3157               return BinaryOperator::createAnd(NewCast, C3);
3158             } else if (CastOp->getOpcode() == Instruction::Or) {
3159               // Change: and (cast (or X, C1) to T), C2
3160               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3161               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3162               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3163                 return ReplaceInstUsesWith(I, AndRHS);
3164             }
3165       }
3166     }
3167
3168     // Try to fold constant and into select arguments.
3169     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3170       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3171         return R;
3172     if (isa<PHINode>(Op0))
3173       if (Instruction *NV = FoldOpIntoPhi(I))
3174         return NV;
3175   }
3176
3177   Value *Op0NotVal = dyn_castNotVal(Op0);
3178   Value *Op1NotVal = dyn_castNotVal(Op1);
3179
3180   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3181     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3182
3183   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3184   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3185     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3186                                                I.getName()+".demorgan");
3187     InsertNewInstBefore(Or, I);
3188     return BinaryOperator::createNot(Or);
3189   }
3190   
3191   {
3192     Value *A = 0, *B = 0;
3193     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3194       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3195         return ReplaceInstUsesWith(I, Op1);
3196     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3197       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3198         return ReplaceInstUsesWith(I, Op0);
3199     
3200     if (Op0->hasOneUse() &&
3201         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3202       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3203         I.swapOperands();     // Simplify below
3204         std::swap(Op0, Op1);
3205       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3206         cast<BinaryOperator>(Op0)->swapOperands();
3207         I.swapOperands();     // Simplify below
3208         std::swap(Op0, Op1);
3209       }
3210     }
3211     if (Op1->hasOneUse() &&
3212         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3213       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3214         cast<BinaryOperator>(Op1)->swapOperands();
3215         std::swap(A, B);
3216       }
3217       if (A == Op0) {                                // A&(A^B) -> A & ~B
3218         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3219         InsertNewInstBefore(NotB, I);
3220         return BinaryOperator::createAnd(A, NotB);
3221       }
3222     }
3223   }
3224   
3225   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3226     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3227     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3228       return R;
3229
3230     Value *LHSVal, *RHSVal;
3231     ConstantInt *LHSCst, *RHSCst;
3232     ICmpInst::Predicate LHSCC, RHSCC;
3233     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3234       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3235         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3236             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3237             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3238             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3239             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3240             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3241           // Ensure that the larger constant is on the RHS.
3242           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3243             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3244           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3245           ICmpInst *LHS = cast<ICmpInst>(Op0);
3246           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3247             std::swap(LHS, RHS);
3248             std::swap(LHSCst, RHSCst);
3249             std::swap(LHSCC, RHSCC);
3250           }
3251
3252           // At this point, we know we have have two icmp instructions
3253           // comparing a value against two constants and and'ing the result
3254           // together.  Because of the above check, we know that we only have
3255           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3256           // (from the FoldICmpLogical check above), that the two constants 
3257           // are not equal and that the larger constant is on the RHS
3258           assert(LHSCst != RHSCst && "Compares not folded above?");
3259
3260           switch (LHSCC) {
3261           default: assert(0 && "Unknown integer condition code!");
3262           case ICmpInst::ICMP_EQ:
3263             switch (RHSCC) {
3264             default: assert(0 && "Unknown integer condition code!");
3265             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3266             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3267             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3268               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3269             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3270             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3271             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3272               return ReplaceInstUsesWith(I, LHS);
3273             }
3274           case ICmpInst::ICMP_NE:
3275             switch (RHSCC) {
3276             default: assert(0 && "Unknown integer condition code!");
3277             case ICmpInst::ICMP_ULT:
3278               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3279                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3280               break;                        // (X != 13 & X u< 15) -> no change
3281             case ICmpInst::ICMP_SLT:
3282               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3283                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3284               break;                        // (X != 13 & X s< 15) -> no change
3285             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3286             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3287             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3288               return ReplaceInstUsesWith(I, RHS);
3289             case ICmpInst::ICMP_NE:
3290               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3291                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3292                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3293                                                       LHSVal->getName()+".off");
3294                 InsertNewInstBefore(Add, I);
3295                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3296                                     ConstantInt::get(Add->getType(), 1));
3297               }
3298               break;                        // (X != 13 & X != 15) -> no change
3299             }
3300             break;
3301           case ICmpInst::ICMP_ULT:
3302             switch (RHSCC) {
3303             default: assert(0 && "Unknown integer condition code!");
3304             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3305             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3306               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3307             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3308               break;
3309             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3310             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3311               return ReplaceInstUsesWith(I, LHS);
3312             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3313               break;
3314             }
3315             break;
3316           case ICmpInst::ICMP_SLT:
3317             switch (RHSCC) {
3318             default: assert(0 && "Unknown integer condition code!");
3319             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3320             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3321               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3322             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3323               break;
3324             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3325             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3326               return ReplaceInstUsesWith(I, LHS);
3327             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3328               break;
3329             }
3330             break;
3331           case ICmpInst::ICMP_UGT:
3332             switch (RHSCC) {
3333             default: assert(0 && "Unknown integer condition code!");
3334             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3335               return ReplaceInstUsesWith(I, LHS);
3336             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3337               return ReplaceInstUsesWith(I, RHS);
3338             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3339               break;
3340             case ICmpInst::ICMP_NE:
3341               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3342                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3343               break;                        // (X u> 13 & X != 15) -> no change
3344             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3345               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3346                                      true, I);
3347             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3348               break;
3349             }
3350             break;
3351           case ICmpInst::ICMP_SGT:
3352             switch (RHSCC) {
3353             default: assert(0 && "Unknown integer condition code!");
3354             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
3355               return ReplaceInstUsesWith(I, LHS);
3356             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3357               return ReplaceInstUsesWith(I, RHS);
3358             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3359               break;
3360             case ICmpInst::ICMP_NE:
3361               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3362                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3363               break;                        // (X s> 13 & X != 15) -> no change
3364             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3365               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3366                                      true, I);
3367             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3368               break;
3369             }
3370             break;
3371           }
3372         }
3373   }
3374
3375   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3376   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3377     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3378       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3379         const Type *SrcTy = Op0C->getOperand(0)->getType();
3380         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3381             // Only do this if the casts both really cause code to be generated.
3382             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3383                               I.getType(), TD) &&
3384             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3385                               I.getType(), TD)) {
3386           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3387                                                          Op1C->getOperand(0),
3388                                                          I.getName());
3389           InsertNewInstBefore(NewOp, I);
3390           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3391         }
3392       }
3393     
3394   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3395   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3396     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3397       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3398           SI0->getOperand(1) == SI1->getOperand(1) &&
3399           (SI0->hasOneUse() || SI1->hasOneUse())) {
3400         Instruction *NewOp =
3401           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3402                                                         SI1->getOperand(0),
3403                                                         SI0->getName()), I);
3404         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3405                                       SI1->getOperand(1));
3406       }
3407   }
3408
3409   return Changed ? &I : 0;
3410 }
3411
3412 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3413 /// in the result.  If it does, and if the specified byte hasn't been filled in
3414 /// yet, fill it in and return false.
3415 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3416   Instruction *I = dyn_cast<Instruction>(V);
3417   if (I == 0) return true;
3418
3419   // If this is an or instruction, it is an inner node of the bswap.
3420   if (I->getOpcode() == Instruction::Or)
3421     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3422            CollectBSwapParts(I->getOperand(1), ByteValues);
3423   
3424   // If this is a shift by a constant int, and it is "24", then its operand
3425   // defines a byte.  We only handle unsigned types here.
3426   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3427     // Not shifting the entire input by N-1 bytes?
3428     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3429         8*(ByteValues.size()-1))
3430       return true;
3431     
3432     unsigned DestNo;
3433     if (I->getOpcode() == Instruction::Shl) {
3434       // X << 24 defines the top byte with the lowest of the input bytes.
3435       DestNo = ByteValues.size()-1;
3436     } else {
3437       // X >>u 24 defines the low byte with the highest of the input bytes.
3438       DestNo = 0;
3439     }
3440     
3441     // If the destination byte value is already defined, the values are or'd
3442     // together, which isn't a bswap (unless it's an or of the same bits).
3443     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3444       return true;
3445     ByteValues[DestNo] = I->getOperand(0);
3446     return false;
3447   }
3448   
3449   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3450   // don't have this.
3451   Value *Shift = 0, *ShiftLHS = 0;
3452   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3453   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3454       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3455     return true;
3456   Instruction *SI = cast<Instruction>(Shift);
3457
3458   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3459   if (ShiftAmt->getZExtValue() & 7 ||
3460       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3461     return true;
3462   
3463   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3464   unsigned DestByte;
3465   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3466     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3467       break;
3468   // Unknown mask for bswap.
3469   if (DestByte == ByteValues.size()) return true;
3470   
3471   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3472   unsigned SrcByte;
3473   if (SI->getOpcode() == Instruction::Shl)
3474     SrcByte = DestByte - ShiftBytes;
3475   else
3476     SrcByte = DestByte + ShiftBytes;
3477   
3478   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3479   if (SrcByte != ByteValues.size()-DestByte-1)
3480     return true;
3481   
3482   // If the destination byte value is already defined, the values are or'd
3483   // together, which isn't a bswap (unless it's an or of the same bits).
3484   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3485     return true;
3486   ByteValues[DestByte] = SI->getOperand(0);
3487   return false;
3488 }
3489
3490 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3491 /// If so, insert the new bswap intrinsic and return it.
3492 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3493   // We cannot bswap one byte.
3494   if (I.getType() == Type::Int8Ty)
3495     return 0;
3496   
3497   /// ByteValues - For each byte of the result, we keep track of which value
3498   /// defines each byte.
3499   SmallVector<Value*, 8> ByteValues;
3500   ByteValues.resize(TD->getTypeSize(I.getType()));
3501     
3502   // Try to find all the pieces corresponding to the bswap.
3503   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3504       CollectBSwapParts(I.getOperand(1), ByteValues))
3505     return 0;
3506   
3507   // Check to see if all of the bytes come from the same value.
3508   Value *V = ByteValues[0];
3509   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3510   
3511   // Check to make sure that all of the bytes come from the same value.
3512   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3513     if (ByteValues[i] != V)
3514       return 0;
3515     
3516   // If they do then *success* we can turn this into a bswap.  Figure out what
3517   // bswap to make it into.
3518   Module *M = I.getParent()->getParent()->getParent();
3519   const char *FnName = 0;
3520   if (I.getType() == Type::Int16Ty)
3521     FnName = "llvm.bswap.i16";
3522   else if (I.getType() == Type::Int32Ty)
3523     FnName = "llvm.bswap.i32";
3524   else if (I.getType() == Type::Int64Ty)
3525     FnName = "llvm.bswap.i64";
3526   else
3527     assert(0 && "Unknown integer type!");
3528   Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3529   return new CallInst(F, V);
3530 }
3531
3532
3533 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3534   bool Changed = SimplifyCommutative(I);
3535   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3536
3537   if (isa<UndefValue>(Op1))
3538     return ReplaceInstUsesWith(I,                         // X | undef -> -1
3539                                ConstantInt::getAllOnesValue(I.getType()));
3540
3541   // or X, X = X
3542   if (Op0 == Op1)
3543     return ReplaceInstUsesWith(I, Op0);
3544
3545   // See if we can simplify any instructions used by the instruction whose sole 
3546   // purpose is to compute bits we don't care about.
3547   uint64_t KnownZero, KnownOne;
3548   if (!isa<VectorType>(I.getType()) &&
3549       SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3550                            KnownZero, KnownOne))
3551     return &I;
3552   
3553   // or X, -1 == -1
3554   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3555     ConstantInt *C1 = 0; Value *X = 0;
3556     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3557     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3558       Instruction *Or = BinaryOperator::createOr(X, RHS);
3559       InsertNewInstBefore(Or, I);
3560       Or->takeName(Op0);
3561       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3562     }
3563
3564     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3565     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3566       Instruction *Or = BinaryOperator::createOr(X, RHS);
3567       InsertNewInstBefore(Or, I);
3568       Or->takeName(Op0);
3569       return BinaryOperator::createXor(Or,
3570                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3571     }
3572
3573     // Try to fold constant and into select arguments.
3574     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3575       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3576         return R;
3577     if (isa<PHINode>(Op0))
3578       if (Instruction *NV = FoldOpIntoPhi(I))
3579         return NV;
3580   }
3581
3582   Value *A = 0, *B = 0;
3583   ConstantInt *C1 = 0, *C2 = 0;
3584
3585   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3586     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3587       return ReplaceInstUsesWith(I, Op1);
3588   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3589     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3590       return ReplaceInstUsesWith(I, Op0);
3591
3592   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3593   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3594   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3595       match(Op1, m_Or(m_Value(), m_Value())) ||
3596       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3597        match(Op1, m_Shift(m_Value(), m_Value())))) {
3598     if (Instruction *BSwap = MatchBSwap(I))
3599       return BSwap;
3600   }
3601   
3602   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3603   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3604       MaskedValueIsZero(Op1, C1->getZExtValue())) {
3605     Instruction *NOr = BinaryOperator::createOr(A, Op1);
3606     InsertNewInstBefore(NOr, I);
3607     NOr->takeName(Op0);
3608     return BinaryOperator::createXor(NOr, C1);
3609   }
3610
3611   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3612   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3613       MaskedValueIsZero(Op0, C1->getZExtValue())) {
3614     Instruction *NOr = BinaryOperator::createOr(A, Op0);
3615     InsertNewInstBefore(NOr, I);
3616     NOr->takeName(Op0);
3617     return BinaryOperator::createXor(NOr, C1);
3618   }
3619
3620   // (A & C1)|(B & C2)
3621   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3622       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3623
3624     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3625       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3626
3627
3628     // If we have: ((V + N) & C1) | (V & C2)
3629     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3630     // replace with V+N.
3631     if (C1 == ConstantExpr::getNot(C2)) {
3632       Value *V1 = 0, *V2 = 0;
3633       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3634           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3635         // Add commutes, try both ways.
3636         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3637           return ReplaceInstUsesWith(I, A);
3638         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3639           return ReplaceInstUsesWith(I, A);
3640       }
3641       // Or commutes, try both ways.
3642       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3643           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3644         // Add commutes, try both ways.
3645         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3646           return ReplaceInstUsesWith(I, B);
3647         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3648           return ReplaceInstUsesWith(I, B);
3649       }
3650     }
3651   }
3652   
3653   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3654   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3655     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3656       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3657           SI0->getOperand(1) == SI1->getOperand(1) &&
3658           (SI0->hasOneUse() || SI1->hasOneUse())) {
3659         Instruction *NewOp =
3660         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3661                                                      SI1->getOperand(0),
3662                                                      SI0->getName()), I);
3663         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3664                                       SI1->getOperand(1));
3665       }
3666   }
3667
3668   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3669     if (A == Op1)   // ~A | A == -1
3670       return ReplaceInstUsesWith(I,
3671                                 ConstantInt::getAllOnesValue(I.getType()));
3672   } else {
3673     A = 0;
3674   }
3675   // Note, A is still live here!
3676   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3677     if (Op0 == B)
3678       return ReplaceInstUsesWith(I,
3679                                 ConstantInt::getAllOnesValue(I.getType()));
3680
3681     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3682     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3683       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3684                                               I.getName()+".demorgan"), I);
3685       return BinaryOperator::createNot(And);
3686     }
3687   }
3688
3689   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3690   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3691     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3692       return R;
3693
3694     Value *LHSVal, *RHSVal;
3695     ConstantInt *LHSCst, *RHSCst;
3696     ICmpInst::Predicate LHSCC, RHSCC;
3697     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3698       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3699         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
3700             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3701             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3702             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3703             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3704             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3705           // Ensure that the larger constant is on the RHS.
3706           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3707             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3708           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3709           ICmpInst *LHS = cast<ICmpInst>(Op0);
3710           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3711             std::swap(LHS, RHS);
3712             std::swap(LHSCst, RHSCst);
3713             std::swap(LHSCC, RHSCC);
3714           }
3715
3716           // At this point, we know we have have two icmp instructions
3717           // comparing a value against two constants and or'ing the result
3718           // together.  Because of the above check, we know that we only have
3719           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3720           // FoldICmpLogical check above), that the two constants are not
3721           // equal.
3722           assert(LHSCst != RHSCst && "Compares not folded above?");
3723
3724           switch (LHSCC) {
3725           default: assert(0 && "Unknown integer condition code!");
3726           case ICmpInst::ICMP_EQ:
3727             switch (RHSCC) {
3728             default: assert(0 && "Unknown integer condition code!");
3729             case ICmpInst::ICMP_EQ:
3730               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3731                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3732                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3733                                                       LHSVal->getName()+".off");
3734                 InsertNewInstBefore(Add, I);
3735                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3736                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3737               }
3738               break;                         // (X == 13 | X == 15) -> no change
3739             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
3740             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
3741               break;
3742             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
3743             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
3744             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
3745               return ReplaceInstUsesWith(I, RHS);
3746             }
3747             break;
3748           case ICmpInst::ICMP_NE:
3749             switch (RHSCC) {
3750             default: assert(0 && "Unknown integer condition code!");
3751             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
3752             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
3753             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
3754               return ReplaceInstUsesWith(I, LHS);
3755             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
3756             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
3757             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
3758               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3759             }
3760             break;
3761           case ICmpInst::ICMP_ULT:
3762             switch (RHSCC) {
3763             default: assert(0 && "Unknown integer condition code!");
3764             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
3765               break;
3766             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
3767               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
3768                                      false, I);
3769             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
3770               break;
3771             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
3772             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
3773               return ReplaceInstUsesWith(I, RHS);
3774             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
3775               break;
3776             }
3777             break;
3778           case ICmpInst::ICMP_SLT:
3779             switch (RHSCC) {
3780             default: assert(0 && "Unknown integer condition code!");
3781             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
3782               break;
3783             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
3784               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
3785                                      false, I);
3786             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
3787               break;
3788             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
3789             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
3790               return ReplaceInstUsesWith(I, RHS);
3791             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
3792               break;
3793             }
3794             break;
3795           case ICmpInst::ICMP_UGT:
3796             switch (RHSCC) {
3797             default: assert(0 && "Unknown integer condition code!");
3798             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
3799             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
3800               return ReplaceInstUsesWith(I, LHS);
3801             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
3802               break;
3803             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
3804             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
3805               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3806             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
3807               break;
3808             }
3809             break;
3810           case ICmpInst::ICMP_SGT:
3811             switch (RHSCC) {
3812             default: assert(0 && "Unknown integer condition code!");
3813             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
3814             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
3815               return ReplaceInstUsesWith(I, LHS);
3816             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
3817               break;
3818             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
3819             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
3820               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3821             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
3822               break;
3823             }
3824             break;
3825           }
3826         }
3827   }
3828     
3829   // fold (or (cast A), (cast B)) -> (cast (or A, B))
3830   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3831     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3832       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3833         const Type *SrcTy = Op0C->getOperand(0)->getType();
3834         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3835             // Only do this if the casts both really cause code to be generated.
3836             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3837                               I.getType(), TD) &&
3838             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3839                               I.getType(), TD)) {
3840           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3841                                                         Op1C->getOperand(0),
3842                                                         I.getName());
3843           InsertNewInstBefore(NewOp, I);
3844           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3845         }
3846       }
3847       
3848
3849   return Changed ? &I : 0;
3850 }
3851
3852 // XorSelf - Implements: X ^ X --> 0
3853 struct XorSelf {
3854   Value *RHS;
3855   XorSelf(Value *rhs) : RHS(rhs) {}
3856   bool shouldApply(Value *LHS) const { return LHS == RHS; }
3857   Instruction *apply(BinaryOperator &Xor) const {
3858     return &Xor;
3859   }
3860 };
3861
3862
3863 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3864   bool Changed = SimplifyCommutative(I);
3865   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3866
3867   if (isa<UndefValue>(Op1))
3868     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
3869
3870   // xor X, X = 0, even if X is nested in a sequence of Xor's.
3871   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3872     assert(Result == &I && "AssociativeOpt didn't work?");
3873     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3874   }
3875   
3876   // See if we can simplify any instructions used by the instruction whose sole 
3877   // purpose is to compute bits we don't care about.
3878   uint64_t KnownZero, KnownOne;
3879   if (!isa<VectorType>(I.getType()) &&
3880       SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3881                            KnownZero, KnownOne))
3882     return &I;
3883
3884   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3885     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3886     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3887       if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
3888         return new ICmpInst(ICI->getInversePredicate(),
3889                             ICI->getOperand(0), ICI->getOperand(1));
3890
3891     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3892       // ~(c-X) == X-c-1 == X+(-c-1)
3893       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3894         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3895           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3896           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3897                                               ConstantInt::get(I.getType(), 1));
3898           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3899         }
3900
3901       // ~(~X & Y) --> (X | ~Y)
3902       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3903         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3904         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3905           Instruction *NotY =
3906             BinaryOperator::createNot(Op0I->getOperand(1),
3907                                       Op0I->getOperand(1)->getName()+".not");
3908           InsertNewInstBefore(NotY, I);
3909           return BinaryOperator::createOr(Op0NotVal, NotY);
3910         }
3911       }
3912
3913       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3914         if (Op0I->getOpcode() == Instruction::Add) {
3915           // ~(X-c) --> (-c-1)-X
3916           if (RHS->isAllOnesValue()) {
3917             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3918             return BinaryOperator::createSub(
3919                            ConstantExpr::getSub(NegOp0CI,
3920                                              ConstantInt::get(I.getType(), 1)),
3921                                           Op0I->getOperand(0));
3922           }
3923         } else if (Op0I->getOpcode() == Instruction::Or) {
3924           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3925           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3926             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3927             // Anything in both C1 and C2 is known to be zero, remove it from
3928             // NewRHS.
3929             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3930             NewRHS = ConstantExpr::getAnd(NewRHS, 
3931                                           ConstantExpr::getNot(CommonBits));
3932             WorkList.push_back(Op0I);
3933             I.setOperand(0, Op0I->getOperand(0));
3934             I.setOperand(1, NewRHS);
3935             return &I;
3936           }
3937         }
3938     }
3939
3940     // Try to fold constant and into select arguments.
3941     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3942       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3943         return R;
3944     if (isa<PHINode>(Op0))
3945       if (Instruction *NV = FoldOpIntoPhi(I))
3946         return NV;
3947   }
3948
3949   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
3950     if (X == Op1)
3951       return ReplaceInstUsesWith(I,
3952                                 ConstantInt::getAllOnesValue(I.getType()));
3953
3954   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
3955     if (X == Op0)
3956       return ReplaceInstUsesWith(I,
3957                                 ConstantInt::getAllOnesValue(I.getType()));
3958
3959   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3960     if (Op1I->getOpcode() == Instruction::Or) {
3961       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
3962         Op1I->swapOperands();
3963         I.swapOperands();
3964         std::swap(Op0, Op1);
3965       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
3966         I.swapOperands();     // Simplified below.
3967         std::swap(Op0, Op1);
3968       }
3969     } else if (Op1I->getOpcode() == Instruction::Xor) {
3970       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
3971         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3972       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
3973         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3974     } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3975       if (Op1I->getOperand(0) == Op0)                      // A^(A&B) -> A^(B&A)
3976         Op1I->swapOperands();
3977       if (Op0 == Op1I->getOperand(1)) {                    // A^(B&A) -> (B&A)^A
3978         I.swapOperands();     // Simplified below.
3979         std::swap(Op0, Op1);
3980       }
3981     }
3982
3983   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3984     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3985       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
3986         Op0I->swapOperands();
3987       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
3988         Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3989         InsertNewInstBefore(NotB, I);
3990         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3991       }
3992     } else if (Op0I->getOpcode() == Instruction::Xor) {
3993       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
3994         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3995       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
3996         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3997     } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3998       if (Op0I->getOperand(0) == Op1)                      // (A&B)^A -> (B&A)^A
3999         Op0I->swapOperands();
4000       if (Op0I->getOperand(1) == Op1 &&                    // (B&A)^A == ~B & A
4001           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4002         Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4003         InsertNewInstBefore(N, I);
4004         return BinaryOperator::createAnd(N, Op1);
4005       }
4006     }
4007
4008   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4009   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4010     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4011       return R;
4012
4013   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4014   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4015     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4016       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4017         const Type *SrcTy = Op0C->getOperand(0)->getType();
4018         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4019             // Only do this if the casts both really cause code to be generated.
4020             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4021                               I.getType(), TD) &&
4022             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4023                               I.getType(), TD)) {
4024           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4025                                                          Op1C->getOperand(0),
4026                                                          I.getName());
4027           InsertNewInstBefore(NewOp, I);
4028           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4029         }
4030       }
4031
4032   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4033   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4034     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4035       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4036           SI0->getOperand(1) == SI1->getOperand(1) &&
4037           (SI0->hasOneUse() || SI1->hasOneUse())) {
4038         Instruction *NewOp =
4039         InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4040                                                       SI1->getOperand(0),
4041                                                       SI0->getName()), I);
4042         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
4043                                       SI1->getOperand(1));
4044       }
4045   }
4046     
4047   return Changed ? &I : 0;
4048 }
4049
4050 static bool isPositive(ConstantInt *C) {
4051   return C->getSExtValue() >= 0;
4052 }
4053
4054 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4055 /// overflowed for this type.
4056 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4057                             ConstantInt *In2) {
4058   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4059
4060   return cast<ConstantInt>(Result)->getZExtValue() <
4061          cast<ConstantInt>(In1)->getZExtValue();
4062 }
4063
4064 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4065 /// code necessary to compute the offset from the base pointer (without adding
4066 /// in the base pointer).  Return the result as a signed integer of intptr size.
4067 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4068   TargetData &TD = IC.getTargetData();
4069   gep_type_iterator GTI = gep_type_begin(GEP);
4070   const Type *IntPtrTy = TD.getIntPtrType();
4071   Value *Result = Constant::getNullValue(IntPtrTy);
4072
4073   // Build a mask for high order bits.
4074   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4075
4076   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4077     Value *Op = GEP->getOperand(i);
4078     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4079     Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4080     if (Constant *OpC = dyn_cast<Constant>(Op)) {
4081       if (!OpC->isNullValue()) {
4082         OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4083         Scale = ConstantExpr::getMul(OpC, Scale);
4084         if (Constant *RC = dyn_cast<Constant>(Result))
4085           Result = ConstantExpr::getAdd(RC, Scale);
4086         else {
4087           // Emit an add instruction.
4088           Result = IC.InsertNewInstBefore(
4089              BinaryOperator::createAdd(Result, Scale,
4090                                        GEP->getName()+".offs"), I);
4091         }
4092       }
4093     } else {
4094       // Convert to correct type.
4095       Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4096                                                Op->getName()+".c"), I);
4097       if (Size != 1)
4098         // We'll let instcombine(mul) convert this to a shl if possible.
4099         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4100                                                     GEP->getName()+".idx"), I);
4101
4102       // Emit an add instruction.
4103       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4104                                                     GEP->getName()+".offs"), I);
4105     }
4106   }
4107   return Result;
4108 }
4109
4110 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4111 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4112 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4113                                        ICmpInst::Predicate Cond,
4114                                        Instruction &I) {
4115   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4116
4117   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4118     if (isa<PointerType>(CI->getOperand(0)->getType()))
4119       RHS = CI->getOperand(0);
4120
4121   Value *PtrBase = GEPLHS->getOperand(0);
4122   if (PtrBase == RHS) {
4123     // As an optimization, we don't actually have to compute the actual value of
4124     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4125     // each index is zero or not.
4126     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4127       Instruction *InVal = 0;
4128       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4129       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4130         bool EmitIt = true;
4131         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4132           if (isa<UndefValue>(C))  // undef index -> undef.
4133             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4134           if (C->isNullValue())
4135             EmitIt = false;
4136           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4137             EmitIt = false;  // This is indexing into a zero sized array?
4138           } else if (isa<ConstantInt>(C))
4139             return ReplaceInstUsesWith(I, // No comparison is needed here.
4140                                  ConstantInt::get(Type::Int1Ty, 
4141                                                   Cond == ICmpInst::ICMP_NE));
4142         }
4143
4144         if (EmitIt) {
4145           Instruction *Comp =
4146             new ICmpInst(Cond, GEPLHS->getOperand(i),
4147                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4148           if (InVal == 0)
4149             InVal = Comp;
4150           else {
4151             InVal = InsertNewInstBefore(InVal, I);
4152             InsertNewInstBefore(Comp, I);
4153             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4154               InVal = BinaryOperator::createOr(InVal, Comp);
4155             else                              // True if all are equal
4156               InVal = BinaryOperator::createAnd(InVal, Comp);
4157           }
4158         }
4159       }
4160
4161       if (InVal)
4162         return InVal;
4163       else
4164         // No comparison is needed here, all indexes = 0
4165         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4166                                                 Cond == ICmpInst::ICMP_EQ));
4167     }
4168
4169     // Only lower this if the icmp is the only user of the GEP or if we expect
4170     // the result to fold to a constant!
4171     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4172       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4173       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4174       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4175                           Constant::getNullValue(Offset->getType()));
4176     }
4177   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4178     // If the base pointers are different, but the indices are the same, just
4179     // compare the base pointer.
4180     if (PtrBase != GEPRHS->getOperand(0)) {
4181       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4182       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4183                         GEPRHS->getOperand(0)->getType();
4184       if (IndicesTheSame)
4185         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4186           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4187             IndicesTheSame = false;
4188             break;
4189           }
4190
4191       // If all indices are the same, just compare the base pointers.
4192       if (IndicesTheSame)
4193         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4194                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4195
4196       // Otherwise, the base pointers are different and the indices are
4197       // different, bail out.
4198       return 0;
4199     }
4200
4201     // If one of the GEPs has all zero indices, recurse.
4202     bool AllZeros = true;
4203     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4204       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4205           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4206         AllZeros = false;
4207         break;
4208       }
4209     if (AllZeros)
4210       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4211                           ICmpInst::getSwappedPredicate(Cond), I);
4212
4213     // If the other GEP has all zero indices, recurse.
4214     AllZeros = true;
4215     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4216       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4217           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4218         AllZeros = false;
4219         break;
4220       }
4221     if (AllZeros)
4222       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4223
4224     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4225       // If the GEPs only differ by one index, compare it.
4226       unsigned NumDifferences = 0;  // Keep track of # differences.
4227       unsigned DiffOperand = 0;     // The operand that differs.
4228       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4229         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4230           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4231                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4232             // Irreconcilable differences.
4233             NumDifferences = 2;
4234             break;
4235           } else {
4236             if (NumDifferences++) break;
4237             DiffOperand = i;
4238           }
4239         }
4240
4241       if (NumDifferences == 0)   // SAME GEP?
4242         return ReplaceInstUsesWith(I, // No comparison is needed here.
4243                                    ConstantInt::get(Type::Int1Ty, 
4244                                                     Cond == ICmpInst::ICMP_EQ));
4245       else if (NumDifferences == 1) {
4246         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4247         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4248         // Make sure we do a signed comparison here.
4249         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4250       }
4251     }
4252
4253     // Only lower this if the icmp is the only user of the GEP or if we expect
4254     // the result to fold to a constant!
4255     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4256         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4257       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4258       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4259       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4260       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4261     }
4262   }
4263   return 0;
4264 }
4265
4266 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4267   bool Changed = SimplifyCompare(I);
4268   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4269
4270   // Fold trivial predicates.
4271   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4272     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4273   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4274     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4275   
4276   // Simplify 'fcmp pred X, X'
4277   if (Op0 == Op1) {
4278     switch (I.getPredicate()) {
4279     default: assert(0 && "Unknown predicate!");
4280     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4281     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4282     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4283       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4284     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4285     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4286     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4287       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4288       
4289     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4290     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4291     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4292     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4293       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4294       I.setPredicate(FCmpInst::FCMP_UNO);
4295       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4296       return &I;
4297       
4298     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4299     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4300     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4301     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4302       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4303       I.setPredicate(FCmpInst::FCMP_ORD);
4304       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4305       return &I;
4306     }
4307   }
4308     
4309   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4310     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4311
4312   // Handle fcmp with constant RHS
4313   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4314     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4315       switch (LHSI->getOpcode()) {
4316       case Instruction::PHI:
4317         if (Instruction *NV = FoldOpIntoPhi(I))
4318           return NV;
4319         break;
4320       case Instruction::Select:
4321         // If either operand of the select is a constant, we can fold the
4322         // comparison into the select arms, which will cause one to be
4323         // constant folded and the select turned into a bitwise or.
4324         Value *Op1 = 0, *Op2 = 0;
4325         if (LHSI->hasOneUse()) {
4326           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4327             // Fold the known value into the constant operand.
4328             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4329             // Insert a new FCmp of the other select operand.
4330             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4331                                                       LHSI->getOperand(2), RHSC,
4332                                                       I.getName()), I);
4333           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4334             // Fold the known value into the constant operand.
4335             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4336             // Insert a new FCmp of the other select operand.
4337             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4338                                                       LHSI->getOperand(1), RHSC,
4339                                                       I.getName()), I);
4340           }
4341         }
4342
4343         if (Op1)
4344           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4345         break;
4346       }
4347   }
4348
4349   return Changed ? &I : 0;
4350 }
4351
4352 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4353   bool Changed = SimplifyCompare(I);
4354   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4355   const Type *Ty = Op0->getType();
4356
4357   // icmp X, X
4358   if (Op0 == Op1)
4359     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4360                                                    isTrueWhenEqual(I)));
4361
4362   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4363     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4364
4365   // icmp of GlobalValues can never equal each other as long as they aren't
4366   // external weak linkage type.
4367   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4368     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4369       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4370         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4371                                                        !isTrueWhenEqual(I)));
4372
4373   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4374   // addresses never equal each other!  We already know that Op0 != Op1.
4375   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4376        isa<ConstantPointerNull>(Op0)) &&
4377       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4378        isa<ConstantPointerNull>(Op1)))
4379     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4380                                                    !isTrueWhenEqual(I)));
4381
4382   // icmp's with boolean values can always be turned into bitwise operations
4383   if (Ty == Type::Int1Ty) {
4384     switch (I.getPredicate()) {
4385     default: assert(0 && "Invalid icmp instruction!");
4386     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4387       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4388       InsertNewInstBefore(Xor, I);
4389       return BinaryOperator::createNot(Xor);
4390     }
4391     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4392       return BinaryOperator::createXor(Op0, Op1);
4393
4394     case ICmpInst::ICMP_UGT:
4395     case ICmpInst::ICMP_SGT:
4396       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4397       // FALL THROUGH
4398     case ICmpInst::ICMP_ULT:
4399     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4400       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4401       InsertNewInstBefore(Not, I);
4402       return BinaryOperator::createAnd(Not, Op1);
4403     }
4404     case ICmpInst::ICMP_UGE:
4405     case ICmpInst::ICMP_SGE:
4406       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4407       // FALL THROUGH
4408     case ICmpInst::ICMP_ULE:
4409     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4410       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4411       InsertNewInstBefore(Not, I);
4412       return BinaryOperator::createOr(Not, Op1);
4413     }
4414     }
4415   }
4416
4417   // See if we are doing a comparison between a constant and an instruction that
4418   // can be folded into the comparison.
4419   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4420     switch (I.getPredicate()) {
4421     default: break;
4422     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4423       if (CI->isMinValue(false))
4424         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4425       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4426         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4427       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4428         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4429       break;
4430
4431     case ICmpInst::ICMP_SLT:
4432       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4433         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4434       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4435         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4436       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4437         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4438       break;
4439
4440     case ICmpInst::ICMP_UGT:
4441       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4442         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4443       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4444         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4445       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4446         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4447       break;
4448
4449     case ICmpInst::ICMP_SGT:
4450       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4451         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4452       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4453         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4454       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4455         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4456       break;
4457
4458     case ICmpInst::ICMP_ULE:
4459       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4460         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4461       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4462         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4463       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4464         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4465       break;
4466
4467     case ICmpInst::ICMP_SLE:
4468       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4469         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4470       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4471         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4472       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4473         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4474       break;
4475
4476     case ICmpInst::ICMP_UGE:
4477       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4478         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4479       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4480         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4481       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4482         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4483       break;
4484
4485     case ICmpInst::ICMP_SGE:
4486       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4487         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4488       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4489         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4490       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4491         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4492       break;
4493     }
4494
4495     // If we still have a icmp le or icmp ge instruction, turn it into the
4496     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4497     // already been handled above, this requires little checking.
4498     //
4499     if (I.getPredicate() == ICmpInst::ICMP_ULE)
4500       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4501     if (I.getPredicate() == ICmpInst::ICMP_SLE)
4502       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4503     if (I.getPredicate() == ICmpInst::ICMP_UGE)
4504       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4505     if (I.getPredicate() == ICmpInst::ICMP_SGE)
4506       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4507     
4508     // See if we can fold the comparison based on bits known to be zero or one
4509     // in the input.
4510     uint64_t KnownZero, KnownOne;
4511     if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
4512                              KnownZero, KnownOne, 0))
4513       return &I;
4514         
4515     // Given the known and unknown bits, compute a range that the LHS could be
4516     // in.
4517     if (KnownOne | KnownZero) {
4518       // Compute the Min, Max and RHS values based on the known bits. For the
4519       // EQ and NE we use unsigned values.
4520       uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4521       int64_t SMin = 0, SMax = 0, SRHSVal = 0;
4522       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4523         SRHSVal = CI->getSExtValue();
4524         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin, 
4525                                                SMax);
4526       } else {
4527         URHSVal = CI->getZExtValue();
4528         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin, 
4529                                                  UMax);
4530       }
4531       switch (I.getPredicate()) {  // LE/GE have been folded already.
4532       default: assert(0 && "Unknown icmp opcode!");
4533       case ICmpInst::ICMP_EQ:
4534         if (UMax < URHSVal || UMin > URHSVal)
4535           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4536         break;
4537       case ICmpInst::ICMP_NE:
4538         if (UMax < URHSVal || UMin > URHSVal)
4539           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4540         break;
4541       case ICmpInst::ICMP_ULT:
4542         if (UMax < URHSVal)
4543           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4544         if (UMin > URHSVal)
4545           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4546         break;
4547       case ICmpInst::ICMP_UGT:
4548         if (UMin > URHSVal)
4549           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4550         if (UMax < URHSVal)
4551           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4552         break;
4553       case ICmpInst::ICMP_SLT:
4554         if (SMax < SRHSVal)
4555           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4556         if (SMin > SRHSVal)
4557           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4558         break;
4559       case ICmpInst::ICMP_SGT: 
4560         if (SMin > SRHSVal)
4561           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4562         if (SMax < SRHSVal)
4563           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4564         break;
4565       }
4566     }
4567           
4568     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
4569     // instruction, see if that instruction also has constants so that the 
4570     // instruction can be folded into the icmp 
4571     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4572       switch (LHSI->getOpcode()) {
4573       case Instruction::And:
4574         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4575             LHSI->getOperand(0)->hasOneUse()) {
4576           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4577
4578           // If the LHS is an AND of a truncating cast, we can widen the
4579           // and/compare to be the input width without changing the value
4580           // produced, eliminating a cast.
4581           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4582             // We can do this transformation if either the AND constant does not
4583             // have its sign bit set or if it is an equality comparison. 
4584             // Extending a relational comparison when we're checking the sign
4585             // bit would not work.
4586             if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4587                 (I.isEquality() ||
4588                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4589                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4590               ConstantInt *NewCST;
4591               ConstantInt *NewCI;
4592               NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4593                                          AndCST->getZExtValue());
4594               NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4595                                         CI->getZExtValue());
4596               Instruction *NewAnd = 
4597                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4598                                           LHSI->getName());
4599               InsertNewInstBefore(NewAnd, I);
4600               return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
4601             }
4602           }
4603           
4604           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4605           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4606           // happens a LOT in code produced by the C front-end, for bitfield
4607           // access.
4608           BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4609           if (Shift && !Shift->isShift())
4610             Shift = 0;
4611
4612           ConstantInt *ShAmt;
4613           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4614           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4615           const Type *AndTy = AndCST->getType();          // Type of the and.
4616
4617           // We can fold this as long as we can't shift unknown bits
4618           // into the mask.  This can only happen with signed shift
4619           // rights, as they sign-extend.
4620           if (ShAmt) {
4621             bool CanFold = Shift->isLogicalShift();
4622             if (!CanFold) {
4623               // To test for the bad case of the signed shr, see if any
4624               // of the bits shifted in could be tested after the mask.
4625               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4626               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4627
4628               Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
4629               Constant *ShVal =
4630                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4631                                      OShAmt);
4632               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4633                 CanFold = true;
4634             }
4635
4636             if (CanFold) {
4637               Constant *NewCst;
4638               if (Shift->getOpcode() == Instruction::Shl)
4639                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4640               else
4641                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4642
4643               // Check to see if we are shifting out any of the bits being
4644               // compared.
4645               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4646                 // If we shifted bits out, the fold is not going to work out.
4647                 // As a special case, check to see if this means that the
4648                 // result is always true or false now.
4649                 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4650                   return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4651                 if (I.getPredicate() == ICmpInst::ICMP_NE)
4652                   return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4653               } else {
4654                 I.setOperand(1, NewCst);
4655                 Constant *NewAndCST;
4656                 if (Shift->getOpcode() == Instruction::Shl)
4657                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4658                 else
4659                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4660                 LHSI->setOperand(1, NewAndCST);
4661                 LHSI->setOperand(0, Shift->getOperand(0));
4662                 WorkList.push_back(Shift); // Shift is dead.
4663                 AddUsesToWorkList(I);
4664                 return &I;
4665               }
4666             }
4667           }
4668           
4669           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4670           // preferable because it allows the C<<Y expression to be hoisted out
4671           // of a loop if Y is invariant and X is not.
4672           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4673               I.isEquality() && !Shift->isArithmeticShift() &&
4674               isa<Instruction>(Shift->getOperand(0))) {
4675             // Compute C << Y.
4676             Value *NS;
4677             if (Shift->getOpcode() == Instruction::LShr) {
4678               NS = BinaryOperator::createShl(AndCST, 
4679                                           Shift->getOperand(1), "tmp");
4680             } else {
4681               // Insert a logical shift.
4682               NS = BinaryOperator::createLShr(AndCST,
4683                                           Shift->getOperand(1), "tmp");
4684             }
4685             InsertNewInstBefore(cast<Instruction>(NS), I);
4686
4687             // Compute X & (C << Y).
4688             Instruction *NewAnd = BinaryOperator::createAnd(
4689                 Shift->getOperand(0), NS, LHSI->getName());
4690             InsertNewInstBefore(NewAnd, I);
4691             
4692             I.setOperand(0, NewAnd);
4693             return &I;
4694           }
4695         }
4696         break;
4697
4698       case Instruction::Shl:         // (icmp pred (shl X, ShAmt), CI)
4699         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4700           if (I.isEquality()) {
4701             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4702
4703             // Check that the shift amount is in range.  If not, don't perform
4704             // undefined shifts.  When the shift is visited it will be
4705             // simplified.
4706             if (ShAmt->getZExtValue() >= TypeBits)
4707               break;
4708
4709             // If we are comparing against bits always shifted out, the
4710             // comparison cannot succeed.
4711             Constant *Comp =
4712               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4713             if (Comp != CI) {// Comparing against a bit that we know is zero.
4714               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4715               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4716               return ReplaceInstUsesWith(I, Cst);
4717             }
4718
4719             if (LHSI->hasOneUse()) {
4720               // Otherwise strength reduce the shift into an and.
4721               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4722               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4723               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4724
4725               Instruction *AndI =
4726                 BinaryOperator::createAnd(LHSI->getOperand(0),
4727                                           Mask, LHSI->getName()+".mask");
4728               Value *And = InsertNewInstBefore(AndI, I);
4729               return new ICmpInst(I.getPredicate(), And,
4730                                      ConstantExpr::getLShr(CI, ShAmt));
4731             }
4732           }
4733         }
4734         break;
4735
4736       case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
4737       case Instruction::AShr:
4738         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4739           if (I.isEquality()) {
4740             // Check that the shift amount is in range.  If not, don't perform
4741             // undefined shifts.  When the shift is visited it will be
4742             // simplified.
4743             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4744             if (ShAmt->getZExtValue() >= TypeBits)
4745               break;
4746
4747             // If we are comparing against bits always shifted out, the
4748             // comparison cannot succeed.
4749             Constant *Comp;
4750             if (LHSI->getOpcode() == Instruction::LShr) 
4751               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
4752                                            ShAmt);
4753             else
4754               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
4755                                            ShAmt);
4756
4757             if (Comp != CI) {// Comparing against a bit that we know is zero.
4758               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4759               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4760               return ReplaceInstUsesWith(I, Cst);
4761             }
4762
4763             if (LHSI->hasOneUse() || CI->isNullValue()) {
4764               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4765
4766               // Otherwise strength reduce the shift into an and.
4767               uint64_t Val = ~0ULL;          // All ones.
4768               Val <<= ShAmtVal;              // Shift over to the right spot.
4769               Val &= ~0ULL >> (64-TypeBits);
4770               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4771
4772               Instruction *AndI =
4773                 BinaryOperator::createAnd(LHSI->getOperand(0),
4774                                           Mask, LHSI->getName()+".mask");
4775               Value *And = InsertNewInstBefore(AndI, I);
4776               return new ICmpInst(I.getPredicate(), And,
4777                                      ConstantExpr::getShl(CI, ShAmt));
4778             }
4779           }
4780         }
4781         break;
4782
4783       case Instruction::SDiv:
4784       case Instruction::UDiv:
4785         // Fold: icmp pred ([us]div X, C1), C2 -> range test
4786         // Fold this div into the comparison, producing a range check. 
4787         // Determine, based on the divide type, what the range is being 
4788         // checked.  If there is an overflow on the low or high side, remember 
4789         // it, otherwise compute the range [low, hi) bounding the new value.
4790         // See: InsertRangeTest above for the kinds of replacements possible.
4791         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4792           // FIXME: If the operand types don't match the type of the divide 
4793           // then don't attempt this transform. The code below doesn't have the
4794           // logic to deal with a signed divide and an unsigned compare (and
4795           // vice versa). This is because (x /s C1) <s C2  produces different 
4796           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4797           // (x /u C1) <u C2.  Simply casting the operands and result won't 
4798           // work. :(  The if statement below tests that condition and bails 
4799           // if it finds it. 
4800           bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4801           if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
4802             break;
4803
4804           // Initialize the variables that will indicate the nature of the
4805           // range check.
4806           bool LoOverflow = false, HiOverflow = false;
4807           ConstantInt *LoBound = 0, *HiBound = 0;
4808
4809           // Compute Prod = CI * DivRHS. We are essentially solving an equation
4810           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
4811           // C2 (CI). By solving for X we can turn this into a range check 
4812           // instead of computing a divide. 
4813           ConstantInt *Prod = 
4814             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4815
4816           // Determine if the product overflows by seeing if the product is
4817           // not equal to the divide. Make sure we do the same kind of divide
4818           // as in the LHS instruction that we're folding. 
4819           bool ProdOV = !DivRHS->isNullValue() && 
4820             (DivIsSigned ?  ConstantExpr::getSDiv(Prod, DivRHS) :
4821               ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4822
4823           // Get the ICmp opcode
4824           ICmpInst::Predicate predicate = I.getPredicate();
4825
4826           if (DivRHS->isNullValue()) {  
4827             // Don't hack on divide by zeros!
4828           } else if (!DivIsSigned) {  // udiv
4829             LoBound = Prod;
4830             LoOverflow = ProdOV;
4831             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4832           } else if (isPositive(DivRHS)) { // Divisor is > 0.
4833             if (CI->isNullValue()) {       // (X / pos) op 0
4834               // Can't overflow.
4835               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4836               HiBound = DivRHS;
4837             } else if (isPositive(CI)) {   // (X / pos) op pos
4838               LoBound = Prod;
4839               LoOverflow = ProdOV;
4840               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4841             } else {                       // (X / pos) op neg
4842               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4843               LoOverflow = AddWithOverflow(LoBound, Prod,
4844                                            cast<ConstantInt>(DivRHSH));
4845               HiBound = Prod;
4846               HiOverflow = ProdOV;
4847             }
4848           } else {                         // Divisor is < 0.
4849             if (CI->isNullValue()) {       // (X / neg) op 0
4850               LoBound = AddOne(DivRHS);
4851               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4852               if (HiBound == DivRHS)
4853                 LoBound = 0;               // - INTMIN = INTMIN
4854             } else if (isPositive(CI)) {   // (X / neg) op pos
4855               HiOverflow = LoOverflow = ProdOV;
4856               if (!LoOverflow)
4857                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4858               HiBound = AddOne(Prod);
4859             } else {                       // (X / neg) op neg
4860               LoBound = Prod;
4861               LoOverflow = HiOverflow = ProdOV;
4862               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4863             }
4864
4865             // Dividing by a negate swaps the condition.
4866             predicate = ICmpInst::getSwappedPredicate(predicate);
4867           }
4868
4869           if (LoBound) {
4870             Value *X = LHSI->getOperand(0);
4871             switch (predicate) {
4872             default: assert(0 && "Unhandled icmp opcode!");
4873             case ICmpInst::ICMP_EQ:
4874               if (LoOverflow && HiOverflow)
4875                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4876               else if (HiOverflow)
4877                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SGE : 
4878                                     ICmpInst::ICMP_UGE, X, LoBound);
4879               else if (LoOverflow)
4880                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
4881                                     ICmpInst::ICMP_ULT, X, HiBound);
4882               else
4883                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4884                                        true, I);
4885             case ICmpInst::ICMP_NE:
4886               if (LoOverflow && HiOverflow)
4887                 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4888               else if (HiOverflow)
4889                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SLT : 
4890                                     ICmpInst::ICMP_ULT, X, LoBound);
4891               else if (LoOverflow)
4892                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
4893                                     ICmpInst::ICMP_UGE, X, HiBound);
4894               else
4895                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4896                                        false, I);
4897             case ICmpInst::ICMP_ULT:
4898             case ICmpInst::ICMP_SLT:
4899               if (LoOverflow)
4900                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4901               return new ICmpInst(predicate, X, LoBound);
4902             case ICmpInst::ICMP_UGT:
4903             case ICmpInst::ICMP_SGT:
4904               if (HiOverflow)
4905                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4906               if (predicate == ICmpInst::ICMP_UGT)
4907                 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4908               else
4909                 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
4910             }
4911           }
4912         }
4913         break;
4914       }
4915
4916     // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
4917     if (I.isEquality()) {
4918       bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4919
4920       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
4921       // the second operand is a constant, simplify a bit.
4922       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4923         switch (BO->getOpcode()) {
4924         case Instruction::SRem:
4925           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4926           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4927               BO->hasOneUse()) {
4928             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4929             if (V > 1 && isPowerOf2_64(V)) {
4930               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4931                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4932               return new ICmpInst(I.getPredicate(), NewRem, 
4933                                   Constant::getNullValue(BO->getType()));
4934             }
4935           }
4936           break;
4937         case Instruction::Add:
4938           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4939           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4940             if (BO->hasOneUse())
4941               return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4942                                   ConstantExpr::getSub(CI, BOp1C));
4943           } else if (CI->isNullValue()) {
4944             // Replace ((add A, B) != 0) with (A != -B) if A or B is
4945             // efficiently invertible, or if the add has just this one use.
4946             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4947
4948             if (Value *NegVal = dyn_castNegVal(BOp1))
4949               return new ICmpInst(I.getPredicate(), BOp0, NegVal);
4950             else if (Value *NegVal = dyn_castNegVal(BOp0))
4951               return new ICmpInst(I.getPredicate(), NegVal, BOp1);
4952             else if (BO->hasOneUse()) {
4953               Instruction *Neg = BinaryOperator::createNeg(BOp1);
4954               InsertNewInstBefore(Neg, I);
4955               Neg->takeName(BO);
4956               return new ICmpInst(I.getPredicate(), BOp0, Neg);
4957             }
4958           }
4959           break;
4960         case Instruction::Xor:
4961           // For the xor case, we can xor two constants together, eliminating
4962           // the explicit xor.
4963           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4964             return new ICmpInst(I.getPredicate(), BO->getOperand(0), 
4965                                 ConstantExpr::getXor(CI, BOC));
4966
4967           // FALLTHROUGH
4968         case Instruction::Sub:
4969           // Replace (([sub|xor] A, B) != 0) with (A != B)
4970           if (CI->isNullValue())
4971             return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4972                                 BO->getOperand(1));
4973           break;
4974
4975         case Instruction::Or:
4976           // If bits are being or'd in that are not present in the constant we
4977           // are comparing against, then the comparison could never succeed!
4978           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4979             Constant *NotCI = ConstantExpr::getNot(CI);
4980             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4981               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4982                                                              isICMP_NE));
4983           }
4984           break;
4985
4986         case Instruction::And:
4987           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4988             // If bits are being compared against that are and'd out, then the
4989             // comparison can never succeed!
4990             if (!ConstantExpr::getAnd(CI,
4991                                       ConstantExpr::getNot(BOC))->isNullValue())
4992               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4993                                                              isICMP_NE));
4994
4995             // If we have ((X & C) == C), turn it into ((X & C) != 0).
4996             if (CI == BOC && isOneBitSet(CI))
4997               return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4998                                   ICmpInst::ICMP_NE, Op0,
4999                                   Constant::getNullValue(CI->getType()));
5000
5001             // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5002             if (isSignBit(BOC)) {
5003               Value *X = BO->getOperand(0);
5004               Constant *Zero = Constant::getNullValue(X->getType());
5005               ICmpInst::Predicate pred = isICMP_NE ? 
5006                 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5007               return new ICmpInst(pred, X, Zero);
5008             }
5009
5010             // ((X & ~7) == 0) --> X < 8
5011             if (CI->isNullValue() && isHighOnes(BOC)) {
5012               Value *X = BO->getOperand(0);
5013               Constant *NegX = ConstantExpr::getNeg(BOC);
5014               ICmpInst::Predicate pred = isICMP_NE ? 
5015                 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5016               return new ICmpInst(pred, X, NegX);
5017             }
5018
5019           }
5020         default: break;
5021         }
5022       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5023         // Handle set{eq|ne} <intrinsic>, intcst.
5024         switch (II->getIntrinsicID()) {
5025         default: break;
5026         case Intrinsic::bswap_i16: 
5027           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5028           WorkList.push_back(II);  // Dead?
5029           I.setOperand(0, II->getOperand(1));
5030           I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5031                                            ByteSwap_16(CI->getZExtValue())));
5032           return &I;
5033         case Intrinsic::bswap_i32:   
5034           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5035           WorkList.push_back(II);  // Dead?
5036           I.setOperand(0, II->getOperand(1));
5037           I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5038                                            ByteSwap_32(CI->getZExtValue())));
5039           return &I;
5040         case Intrinsic::bswap_i64:   
5041           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5042           WorkList.push_back(II);  // Dead?
5043           I.setOperand(0, II->getOperand(1));
5044           I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5045                                            ByteSwap_64(CI->getZExtValue())));
5046           return &I;
5047         }
5048       }
5049     } else {  // Not a ICMP_EQ/ICMP_NE
5050       // If the LHS is a cast from an integral value of the same size, then 
5051       // since we know the RHS is a constant, try to simlify.
5052       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5053         Value *CastOp = Cast->getOperand(0);
5054         const Type *SrcTy = CastOp->getType();
5055         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5056         if (SrcTy->isInteger() && 
5057             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5058           // If this is an unsigned comparison, try to make the comparison use
5059           // smaller constant values.
5060           switch (I.getPredicate()) {
5061             default: break;
5062             case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5063               ConstantInt *CUI = cast<ConstantInt>(CI);
5064               if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5065                 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5066                                     ConstantInt::get(SrcTy, -1ULL));
5067               break;
5068             }
5069             case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5070               ConstantInt *CUI = cast<ConstantInt>(CI);
5071               if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5072                 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5073                                     Constant::getNullValue(SrcTy));
5074               break;
5075             }
5076           }
5077
5078         }
5079       }
5080     }
5081   }
5082
5083   // Handle icmp with constant RHS
5084   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5085     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5086       switch (LHSI->getOpcode()) {
5087       case Instruction::GetElementPtr:
5088         if (RHSC->isNullValue()) {
5089           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5090           bool isAllZeros = true;
5091           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5092             if (!isa<Constant>(LHSI->getOperand(i)) ||
5093                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5094               isAllZeros = false;
5095               break;
5096             }
5097           if (isAllZeros)
5098             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5099                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5100         }
5101         break;
5102
5103       case Instruction::PHI:
5104         if (Instruction *NV = FoldOpIntoPhi(I))
5105           return NV;
5106         break;
5107       case Instruction::Select:
5108         // If either operand of the select is a constant, we can fold the
5109         // comparison into the select arms, which will cause one to be
5110         // constant folded and the select turned into a bitwise or.
5111         Value *Op1 = 0, *Op2 = 0;
5112         if (LHSI->hasOneUse()) {
5113           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5114             // Fold the known value into the constant operand.
5115             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5116             // Insert a new ICmp of the other select operand.
5117             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5118                                                    LHSI->getOperand(2), RHSC,
5119                                                    I.getName()), I);
5120           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5121             // Fold the known value into the constant operand.
5122             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5123             // Insert a new ICmp of the other select operand.
5124             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5125                                                    LHSI->getOperand(1), RHSC,
5126                                                    I.getName()), I);
5127           }
5128         }
5129
5130         if (Op1)
5131           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5132         break;
5133       }
5134   }
5135
5136   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5137   if (User *GEP = dyn_castGetElementPtr(Op0))
5138     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5139       return NI;
5140   if (User *GEP = dyn_castGetElementPtr(Op1))
5141     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5142                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5143       return NI;
5144
5145   // Test to see if the operands of the icmp are casted versions of other
5146   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5147   // now.
5148   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5149     if (isa<PointerType>(Op0->getType()) && 
5150         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5151       // We keep moving the cast from the left operand over to the right
5152       // operand, where it can often be eliminated completely.
5153       Op0 = CI->getOperand(0);
5154
5155       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5156       // so eliminate it as well.
5157       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5158         Op1 = CI2->getOperand(0);
5159
5160       // If Op1 is a constant, we can fold the cast into the constant.
5161       if (Op0->getType() != Op1->getType())
5162         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5163           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5164         } else {
5165           // Otherwise, cast the RHS right before the icmp
5166           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5167         }
5168       return new ICmpInst(I.getPredicate(), Op0, Op1);
5169     }
5170   }
5171   
5172   if (isa<CastInst>(Op0)) {
5173     // Handle the special case of: icmp (cast bool to X), <cst>
5174     // This comes up when you have code like
5175     //   int X = A < B;
5176     //   if (X) ...
5177     // For generality, we handle any zero-extension of any operand comparison
5178     // with a constant or another cast from the same type.
5179     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5180       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5181         return R;
5182   }
5183   
5184   if (I.isEquality()) {
5185     Value *A, *B, *C, *D;
5186     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5187       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5188         Value *OtherVal = A == Op1 ? B : A;
5189         return new ICmpInst(I.getPredicate(), OtherVal,
5190                             Constant::getNullValue(A->getType()));
5191       }
5192
5193       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5194         // A^c1 == C^c2 --> A == C^(c1^c2)
5195         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5196           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5197             if (Op1->hasOneUse()) {
5198               Constant *NC = ConstantExpr::getXor(C1, C2);
5199               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5200               return new ICmpInst(I.getPredicate(), A,
5201                                   InsertNewInstBefore(Xor, I));
5202             }
5203         
5204         // A^B == A^D -> B == D
5205         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5206         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5207         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5208         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5209       }
5210     }
5211     
5212     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5213         (A == Op0 || B == Op0)) {
5214       // A == (A^B)  ->  B == 0
5215       Value *OtherVal = A == Op0 ? B : A;
5216       return new ICmpInst(I.getPredicate(), OtherVal,
5217                           Constant::getNullValue(A->getType()));
5218     }
5219     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5220       // (A-B) == A  ->  B == 0
5221       return new ICmpInst(I.getPredicate(), B,
5222                           Constant::getNullValue(B->getType()));
5223     }
5224     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5225       // A == (A-B)  ->  B == 0
5226       return new ICmpInst(I.getPredicate(), B,
5227                           Constant::getNullValue(B->getType()));
5228     }
5229     
5230     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5231     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5232         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5233         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5234       Value *X = 0, *Y = 0, *Z = 0;
5235       
5236       if (A == C) {
5237         X = B; Y = D; Z = A;
5238       } else if (A == D) {
5239         X = B; Y = C; Z = A;
5240       } else if (B == C) {
5241         X = A; Y = D; Z = B;
5242       } else if (B == D) {
5243         X = A; Y = C; Z = B;
5244       }
5245       
5246       if (X) {   // Build (X^Y) & Z
5247         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5248         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5249         I.setOperand(0, Op1);
5250         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5251         return &I;
5252       }
5253     }
5254   }
5255   return Changed ? &I : 0;
5256 }
5257
5258 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5259 // We only handle extending casts so far.
5260 //
5261 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5262   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5263   Value *LHSCIOp        = LHSCI->getOperand(0);
5264   const Type *SrcTy     = LHSCIOp->getType();
5265   const Type *DestTy    = LHSCI->getType();
5266   Value *RHSCIOp;
5267
5268   // We only handle extension cast instructions, so far. Enforce this.
5269   if (LHSCI->getOpcode() != Instruction::ZExt &&
5270       LHSCI->getOpcode() != Instruction::SExt)
5271     return 0;
5272
5273   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5274   bool isSignedCmp = ICI.isSignedPredicate();
5275
5276   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5277     // Not an extension from the same type?
5278     RHSCIOp = CI->getOperand(0);
5279     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5280       return 0;
5281     
5282     // If the signedness of the two compares doesn't agree (i.e. one is a sext
5283     // and the other is a zext), then we can't handle this.
5284     if (CI->getOpcode() != LHSCI->getOpcode())
5285       return 0;
5286
5287     // Likewise, if the signedness of the [sz]exts and the compare don't match, 
5288     // then we can't handle this.
5289     if (isSignedExt != isSignedCmp && !ICI.isEquality())
5290       return 0;
5291     
5292     // Okay, just insert a compare of the reduced operands now!
5293     return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5294   }
5295
5296   // If we aren't dealing with a constant on the RHS, exit early
5297   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5298   if (!CI)
5299     return 0;
5300
5301   // Compute the constant that would happen if we truncated to SrcTy then
5302   // reextended to DestTy.
5303   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5304   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5305
5306   // If the re-extended constant didn't change...
5307   if (Res2 == CI) {
5308     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5309     // For example, we might have:
5310     //    %A = sext short %X to uint
5311     //    %B = icmp ugt uint %A, 1330
5312     // It is incorrect to transform this into 
5313     //    %B = icmp ugt short %X, 1330 
5314     // because %A may have negative value. 
5315     //
5316     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5317     // OR operation is EQ/NE.
5318     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5319       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5320     else
5321       return 0;
5322   }
5323
5324   // The re-extended constant changed so the constant cannot be represented 
5325   // in the shorter type. Consequently, we cannot emit a simple comparison.
5326
5327   // First, handle some easy cases. We know the result cannot be equal at this
5328   // point so handle the ICI.isEquality() cases
5329   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5330     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5331   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5332     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5333
5334   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5335   // should have been folded away previously and not enter in here.
5336   Value *Result;
5337   if (isSignedCmp) {
5338     // We're performing a signed comparison.
5339     if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5340       Result = ConstantInt::getFalse();          // X < (small) --> false
5341     else
5342       Result = ConstantInt::getTrue();           // X < (large) --> true
5343   } else {
5344     // We're performing an unsigned comparison.
5345     if (isSignedExt) {
5346       // We're performing an unsigned comp with a sign extended value.
5347       // This is true if the input is >= 0. [aka >s -1]
5348       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5349       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5350                                    NegOne, ICI.getName()), ICI);
5351     } else {
5352       // Unsigned extend & unsigned compare -> always true.
5353       Result = ConstantInt::getTrue();
5354     }
5355   }
5356
5357   // Finally, return the value computed.
5358   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5359       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5360     return ReplaceInstUsesWith(ICI, Result);
5361   } else {
5362     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5363             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5364            "ICmp should be folded!");
5365     if (Constant *CI = dyn_cast<Constant>(Result))
5366       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5367     else
5368       return BinaryOperator::createNot(Result);
5369   }
5370 }
5371
5372 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5373   return commonShiftTransforms(I);
5374 }
5375
5376 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5377   return commonShiftTransforms(I);
5378 }
5379
5380 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5381   return commonShiftTransforms(I);
5382 }
5383
5384 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5385   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
5386   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5387
5388   // shl X, 0 == X and shr X, 0 == X
5389   // shl 0, X == 0 and shr 0, X == 0
5390   if (Op1 == Constant::getNullValue(Op1->getType()) ||
5391       Op0 == Constant::getNullValue(Op0->getType()))
5392     return ReplaceInstUsesWith(I, Op0);
5393   
5394   if (isa<UndefValue>(Op0)) {            
5395     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5396       return ReplaceInstUsesWith(I, Op0);
5397     else                                    // undef << X -> 0, undef >>u X -> 0
5398       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5399   }
5400   if (isa<UndefValue>(Op1)) {
5401     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5402       return ReplaceInstUsesWith(I, Op0);          
5403     else                                     // X << undef, X >>u undef -> 0
5404       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5405   }
5406
5407   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5408   if (I.getOpcode() == Instruction::AShr)
5409     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5410       if (CSI->isAllOnesValue())
5411         return ReplaceInstUsesWith(I, CSI);
5412
5413   // Try to fold constant and into select arguments.
5414   if (isa<Constant>(Op0))
5415     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5416       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5417         return R;
5418
5419   // See if we can turn a signed shr into an unsigned shr.
5420   if (I.isArithmeticShift()) {
5421     if (MaskedValueIsZero(Op0,
5422                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5423       return BinaryOperator::createLShr(Op0, Op1, I.getName());
5424     }
5425   }
5426
5427   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5428     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5429       return Res;
5430   return 0;
5431 }
5432
5433 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5434                                                BinaryOperator &I) {
5435   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5436
5437   // See if we can simplify any instructions used by the instruction whose sole 
5438   // purpose is to compute bits we don't care about.
5439   uint64_t KnownZero, KnownOne;
5440   if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
5441                            KnownZero, KnownOne))
5442     return &I;
5443   
5444   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5445   // of a signed value.
5446   //
5447   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5448   if (Op1->getZExtValue() >= TypeBits) {
5449     if (I.getOpcode() != Instruction::AShr)
5450       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5451     else {
5452       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
5453       return &I;
5454     }
5455   }
5456   
5457   // ((X*C1) << C2) == (X * (C1 << C2))
5458   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5459     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5460       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5461         return BinaryOperator::createMul(BO->getOperand(0),
5462                                          ConstantExpr::getShl(BOOp, Op1));
5463   
5464   // Try to fold constant and into select arguments.
5465   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5466     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5467       return R;
5468   if (isa<PHINode>(Op0))
5469     if (Instruction *NV = FoldOpIntoPhi(I))
5470       return NV;
5471   
5472   if (Op0->hasOneUse()) {
5473     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5474       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5475       Value *V1, *V2;
5476       ConstantInt *CC;
5477       switch (Op0BO->getOpcode()) {
5478         default: break;
5479         case Instruction::Add:
5480         case Instruction::And:
5481         case Instruction::Or:
5482         case Instruction::Xor: {
5483           // These operators commute.
5484           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5485           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5486               match(Op0BO->getOperand(1),
5487                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5488             Instruction *YS = BinaryOperator::createShl(
5489                                             Op0BO->getOperand(0), Op1,
5490                                             Op0BO->getName());
5491             InsertNewInstBefore(YS, I); // (Y << C)
5492             Instruction *X = 
5493               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5494                                      Op0BO->getOperand(1)->getName());
5495             InsertNewInstBefore(X, I);  // (X + (Y << C))
5496             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5497             C2 = ConstantExpr::getShl(C2, Op1);
5498             return BinaryOperator::createAnd(X, C2);
5499           }
5500           
5501           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5502           Value *Op0BOOp1 = Op0BO->getOperand(1);
5503           if (isLeftShift && Op0BOOp1->hasOneUse() && V2 == Op1 &&
5504               match(Op0BOOp1, 
5505                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
5506               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)-> hasOneUse()) {
5507             Instruction *YS = BinaryOperator::createShl(
5508                                                      Op0BO->getOperand(0), Op1,
5509                                                      Op0BO->getName());
5510             InsertNewInstBefore(YS, I); // (Y << C)
5511             Instruction *XM =
5512               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5513                                         V1->getName()+".mask");
5514             InsertNewInstBefore(XM, I); // X & (CC << C)
5515             
5516             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5517           }
5518         }
5519           
5520         // FALL THROUGH.
5521         case Instruction::Sub: {
5522           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5523           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5524               match(Op0BO->getOperand(0),
5525                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5526             Instruction *YS = BinaryOperator::createShl(
5527                                                      Op0BO->getOperand(1), Op1,
5528                                                      Op0BO->getName());
5529             InsertNewInstBefore(YS, I); // (Y << C)
5530             Instruction *X =
5531               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5532                                      Op0BO->getOperand(0)->getName());
5533             InsertNewInstBefore(X, I);  // (X + (Y << C))
5534             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5535             C2 = ConstantExpr::getShl(C2, Op1);
5536             return BinaryOperator::createAnd(X, C2);
5537           }
5538           
5539           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5540           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5541               match(Op0BO->getOperand(0),
5542                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5543                           m_ConstantInt(CC))) && V2 == Op1 &&
5544               cast<BinaryOperator>(Op0BO->getOperand(0))
5545                   ->getOperand(0)->hasOneUse()) {
5546             Instruction *YS = BinaryOperator::createShl(
5547                                                      Op0BO->getOperand(1), Op1,
5548                                                      Op0BO->getName());
5549             InsertNewInstBefore(YS, I); // (Y << C)
5550             Instruction *XM =
5551               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5552                                         V1->getName()+".mask");
5553             InsertNewInstBefore(XM, I); // X & (CC << C)
5554             
5555             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5556           }
5557           
5558           break;
5559         }
5560       }
5561       
5562       
5563       // If the operand is an bitwise operator with a constant RHS, and the
5564       // shift is the only use, we can pull it out of the shift.
5565       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5566         bool isValid = true;     // Valid only for And, Or, Xor
5567         bool highBitSet = false; // Transform if high bit of constant set?
5568         
5569         switch (Op0BO->getOpcode()) {
5570           default: isValid = false; break;   // Do not perform transform!
5571           case Instruction::Add:
5572             isValid = isLeftShift;
5573             break;
5574           case Instruction::Or:
5575           case Instruction::Xor:
5576             highBitSet = false;
5577             break;
5578           case Instruction::And:
5579             highBitSet = true;
5580             break;
5581         }
5582         
5583         // If this is a signed shift right, and the high bit is modified
5584         // by the logical operation, do not perform the transformation.
5585         // The highBitSet boolean indicates the value of the high bit of
5586         // the constant which would cause it to be modified for this
5587         // operation.
5588         //
5589         if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
5590           uint64_t Val = Op0C->getZExtValue();
5591           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5592         }
5593         
5594         if (isValid) {
5595           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5596           
5597           Instruction *NewShift =
5598             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
5599           InsertNewInstBefore(NewShift, I);
5600           NewShift->takeName(Op0BO);
5601           
5602           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5603                                         NewRHS);
5604         }
5605       }
5606     }
5607   }
5608   
5609   // Find out if this is a shift of a shift by a constant.
5610   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5611   if (ShiftOp && !ShiftOp->isShift())
5612     ShiftOp = 0;
5613   
5614   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5615     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5616     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5617     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5618     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5619     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
5620     Value *X = ShiftOp->getOperand(0);
5621     
5622     unsigned AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5623     if (AmtSum > I.getType()->getPrimitiveSizeInBits())
5624       AmtSum = I.getType()->getPrimitiveSizeInBits();
5625     
5626     const IntegerType *Ty = cast<IntegerType>(I.getType());
5627     
5628     // Check for (X << c1) << c2  and  (X >> c1) >> c2
5629     if (I.getOpcode() == ShiftOp->getOpcode()) {
5630       return BinaryOperator::create(I.getOpcode(), X,
5631                                     ConstantInt::get(Ty, AmtSum));
5632     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5633                I.getOpcode() == Instruction::AShr) {
5634       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
5635       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5636     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5637                I.getOpcode() == Instruction::LShr) {
5638       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5639       Instruction *Shift =
5640         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5641       InsertNewInstBefore(Shift, I);
5642
5643       uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5644       return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5645     }
5646     
5647     // Okay, if we get here, one shift must be left, and the other shift must be
5648     // right.  See if the amounts are equal.
5649     if (ShiftAmt1 == ShiftAmt2) {
5650       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5651       if (I.getOpcode() == Instruction::Shl) {
5652         uint64_t Mask = Ty->getBitMask() << ShiftAmt1;
5653         return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5654       }
5655       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5656       if (I.getOpcode() == Instruction::LShr) {
5657         uint64_t Mask = Ty->getBitMask() >> ShiftAmt1;
5658         return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5659       }
5660       // We can simplify ((X << C) >>s C) into a trunc + sext.
5661       // NOTE: we could do this for any C, but that would make 'unusual' integer
5662       // types.  For now, just stick to ones well-supported by the code
5663       // generators.
5664       const Type *SExtType = 0;
5665       switch (Ty->getBitWidth() - ShiftAmt1) {
5666       case 8 : SExtType = Type::Int8Ty; break;
5667       case 16: SExtType = Type::Int16Ty; break;
5668       case 32: SExtType = Type::Int32Ty; break;
5669       default: break;
5670       }
5671       if (SExtType) {
5672         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5673         InsertNewInstBefore(NewTrunc, I);
5674         return new SExtInst(NewTrunc, Ty);
5675       }
5676       // Otherwise, we can't handle it yet.
5677     } else if (ShiftAmt1 < ShiftAmt2) {
5678       unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
5679       
5680       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
5681       if (I.getOpcode() == Instruction::Shl) {
5682         assert(ShiftOp->getOpcode() == Instruction::LShr ||
5683                ShiftOp->getOpcode() == Instruction::AShr);
5684         Instruction *Shift =
5685           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5686         InsertNewInstBefore(Shift, I);
5687         
5688         uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
5689         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5690       }
5691       
5692       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
5693       if (I.getOpcode() == Instruction::LShr) {
5694         assert(ShiftOp->getOpcode() == Instruction::Shl);
5695         Instruction *Shift =
5696           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5697         InsertNewInstBefore(Shift, I);
5698         
5699         uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5700         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5701       }
5702       
5703       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5704     } else {
5705       assert(ShiftAmt2 < ShiftAmt1);
5706       unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
5707
5708       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
5709       if (I.getOpcode() == Instruction::Shl) {
5710         assert(ShiftOp->getOpcode() == Instruction::LShr ||
5711                ShiftOp->getOpcode() == Instruction::AShr);
5712         Instruction *Shift =
5713           BinaryOperator::create(ShiftOp->getOpcode(), X,
5714                                  ConstantInt::get(Ty, ShiftDiff));
5715         InsertNewInstBefore(Shift, I);
5716         
5717         uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
5718         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5719       }
5720       
5721       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
5722       if (I.getOpcode() == Instruction::LShr) {
5723         assert(ShiftOp->getOpcode() == Instruction::Shl);
5724         Instruction *Shift =
5725           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5726         InsertNewInstBefore(Shift, I);
5727         
5728         uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5729         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5730       }
5731       
5732       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
5733     }
5734   }
5735   return 0;
5736 }
5737
5738
5739 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5740 /// expression.  If so, decompose it, returning some value X, such that Val is
5741 /// X*Scale+Offset.
5742 ///
5743 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5744                                         unsigned &Offset) {
5745   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
5746   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5747     Offset = CI->getZExtValue();
5748     Scale  = 1;
5749     return ConstantInt::get(Type::Int32Ty, 0);
5750   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5751     if (I->getNumOperands() == 2) {
5752       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5753         if (I->getOpcode() == Instruction::Shl) {
5754           // This is a value scaled by '1 << the shift amt'.
5755           Scale = 1U << CUI->getZExtValue();
5756           Offset = 0;
5757           return I->getOperand(0);
5758         } else if (I->getOpcode() == Instruction::Mul) {
5759           // This value is scaled by 'CUI'.
5760           Scale = CUI->getZExtValue();
5761           Offset = 0;
5762           return I->getOperand(0);
5763         } else if (I->getOpcode() == Instruction::Add) {
5764           // We have X+C.  Check to see if we really have (X*C2)+C1, 
5765           // where C1 is divisible by C2.
5766           unsigned SubScale;
5767           Value *SubVal = 
5768             DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5769           Offset += CUI->getZExtValue();
5770           if (SubScale > 1 && (Offset % SubScale == 0)) {
5771             Scale = SubScale;
5772             return SubVal;
5773           }
5774         }
5775       }
5776     }
5777   }
5778
5779   // Otherwise, we can't look past this.
5780   Scale = 1;
5781   Offset = 0;
5782   return Val;
5783 }
5784
5785
5786 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5787 /// try to eliminate the cast by moving the type information into the alloc.
5788 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5789                                                    AllocationInst &AI) {
5790   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5791   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
5792   
5793   // Remove any uses of AI that are dead.
5794   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5795   
5796   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5797     Instruction *User = cast<Instruction>(*UI++);
5798     if (isInstructionTriviallyDead(User)) {
5799       while (UI != E && *UI == User)
5800         ++UI; // If this instruction uses AI more than once, don't break UI.
5801       
5802       ++NumDeadInst;
5803       DOUT << "IC: DCE: " << *User;
5804       EraseInstFromFunction(*User);
5805     }
5806   }
5807   
5808   // Get the type really allocated and the type casted to.
5809   const Type *AllocElTy = AI.getAllocatedType();
5810   const Type *CastElTy = PTy->getElementType();
5811   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5812
5813   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
5814   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
5815   if (CastElTyAlign < AllocElTyAlign) return 0;
5816
5817   // If the allocation has multiple uses, only promote it if we are strictly
5818   // increasing the alignment of the resultant allocation.  If we keep it the
5819   // same, we open the door to infinite loops of various kinds.
5820   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5821
5822   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5823   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5824   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5825
5826   // See if we can satisfy the modulus by pulling a scale out of the array
5827   // size argument.
5828   unsigned ArraySizeScale, ArrayOffset;
5829   Value *NumElements = // See if the array size is a decomposable linear expr.
5830     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5831  
5832   // If we can now satisfy the modulus, by using a non-1 scale, we really can
5833   // do the xform.
5834   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5835       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
5836
5837   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5838   Value *Amt = 0;
5839   if (Scale == 1) {
5840     Amt = NumElements;
5841   } else {
5842     // If the allocation size is constant, form a constant mul expression
5843     Amt = ConstantInt::get(Type::Int32Ty, Scale);
5844     if (isa<ConstantInt>(NumElements))
5845       Amt = ConstantExpr::getMul(
5846               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5847     // otherwise multiply the amount and the number of elements
5848     else if (Scale != 1) {
5849       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5850       Amt = InsertNewInstBefore(Tmp, AI);
5851     }
5852   }
5853   
5854   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5855     Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
5856     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5857     Amt = InsertNewInstBefore(Tmp, AI);
5858   }
5859   
5860   AllocationInst *New;
5861   if (isa<MallocInst>(AI))
5862     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
5863   else
5864     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
5865   InsertNewInstBefore(New, AI);
5866   New->takeName(&AI);
5867   
5868   // If the allocation has multiple uses, insert a cast and change all things
5869   // that used it to use the new cast.  This will also hack on CI, but it will
5870   // die soon.
5871   if (!AI.hasOneUse()) {
5872     AddUsesToWorkList(AI);
5873     // New is the allocation instruction, pointer typed. AI is the original
5874     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5875     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
5876     InsertNewInstBefore(NewCast, AI);
5877     AI.replaceAllUsesWith(NewCast);
5878   }
5879   return ReplaceInstUsesWith(CI, New);
5880 }
5881
5882 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5883 /// and return it without inserting any new casts.  This is used by code that
5884 /// tries to decide whether promoting or shrinking integer operations to wider
5885 /// or smaller types will allow us to eliminate a truncate or extend.
5886 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5887                                        int &NumCastsRemoved) {
5888   if (isa<Constant>(V)) return true;
5889   
5890   Instruction *I = dyn_cast<Instruction>(V);
5891   if (!I || !I->hasOneUse()) return false;
5892   
5893   switch (I->getOpcode()) {
5894   case Instruction::And:
5895   case Instruction::Or:
5896   case Instruction::Xor:
5897     // These operators can all arbitrarily be extended or truncated.
5898     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5899            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5900   case Instruction::AShr:
5901   case Instruction::LShr:
5902   case Instruction::Shl:
5903     // If this is just a bitcast changing the sign of the operation, we can
5904     // convert if the operand can be converted.
5905     if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5906       return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5907     break;
5908   case Instruction::Trunc:
5909   case Instruction::ZExt:
5910   case Instruction::SExt:
5911   case Instruction::BitCast:
5912     // If this is a cast from the destination type, we can trivially eliminate
5913     // it, and this will remove a cast overall.
5914     if (I->getOperand(0)->getType() == Ty) {
5915       // If the first operand is itself a cast, and is eliminable, do not count
5916       // this as an eliminable cast.  We would prefer to eliminate those two
5917       // casts first.
5918       if (isa<CastInst>(I->getOperand(0)))
5919         return true;
5920       
5921       ++NumCastsRemoved;
5922       return true;
5923     }
5924     break;
5925   default:
5926     // TODO: Can handle more cases here.
5927     break;
5928   }
5929   
5930   return false;
5931 }
5932
5933 /// EvaluateInDifferentType - Given an expression that 
5934 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5935 /// evaluate the expression.
5936 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
5937                                              bool isSigned ) {
5938   if (Constant *C = dyn_cast<Constant>(V))
5939     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
5940
5941   // Otherwise, it must be an instruction.
5942   Instruction *I = cast<Instruction>(V);
5943   Instruction *Res = 0;
5944   switch (I->getOpcode()) {
5945   case Instruction::And:
5946   case Instruction::Or:
5947   case Instruction::Xor: {
5948     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5949     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
5950     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5951                                  LHS, RHS, I->getName());
5952     break;
5953   }
5954   case Instruction::AShr:
5955   case Instruction::LShr:
5956   case Instruction::Shl: {
5957     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5958     Res = BinaryOperator::create(Instruction::BinaryOps(I->getOpcode()), LHS, 
5959                                  I->getOperand(1), I->getName());
5960     break;
5961   }    
5962   case Instruction::Trunc:
5963   case Instruction::ZExt:
5964   case Instruction::SExt:
5965   case Instruction::BitCast:
5966     // If the source type of the cast is the type we're trying for then we can
5967     // just return the source. There's no need to insert it because its not new.
5968     if (I->getOperand(0)->getType() == Ty)
5969       return I->getOperand(0);
5970     
5971     // Some other kind of cast, which shouldn't happen, so just ..
5972     // FALL THROUGH
5973   default: 
5974     // TODO: Can handle more cases here.
5975     assert(0 && "Unreachable!");
5976     break;
5977   }
5978   
5979   return InsertNewInstBefore(Res, *I);
5980 }
5981
5982 /// @brief Implement the transforms common to all CastInst visitors.
5983 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
5984   Value *Src = CI.getOperand(0);
5985
5986   // Casting undef to anything results in undef so might as just replace it and
5987   // get rid of the cast.
5988   if (isa<UndefValue>(Src))   // cast undef -> undef
5989     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5990
5991   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5992   // eliminate it now.
5993   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
5994     if (Instruction::CastOps opc = 
5995         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5996       // The first cast (CSrc) is eliminable so we need to fix up or replace
5997       // the second cast (CI). CSrc will then have a good chance of being dead.
5998       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
5999     }
6000   }
6001
6002   // If casting the result of a getelementptr instruction with no offset, turn
6003   // this into a cast of the original pointer!
6004   //
6005   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6006     bool AllZeroOperands = true;
6007     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6008       if (!isa<Constant>(GEP->getOperand(i)) ||
6009           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6010         AllZeroOperands = false;
6011         break;
6012       }
6013     if (AllZeroOperands) {
6014       // Changing the cast operand is usually not a good idea but it is safe
6015       // here because the pointer operand is being replaced with another 
6016       // pointer operand so the opcode doesn't need to change.
6017       CI.setOperand(0, GEP->getOperand(0));
6018       return &CI;
6019     }
6020   }
6021     
6022   // If we are casting a malloc or alloca to a pointer to a type of the same
6023   // size, rewrite the allocation instruction to allocate the "right" type.
6024   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
6025     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6026       return V;
6027
6028   // If we are casting a select then fold the cast into the select
6029   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6030     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6031       return NV;
6032
6033   // If we are casting a PHI then fold the cast into the PHI
6034   if (isa<PHINode>(Src))
6035     if (Instruction *NV = FoldOpIntoPhi(CI))
6036       return NV;
6037   
6038   return 0;
6039 }
6040
6041 /// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
6042 /// integers. This function implements the common transforms for all those
6043 /// cases.
6044 /// @brief Implement the transforms common to CastInst with integer operands
6045 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6046   if (Instruction *Result = commonCastTransforms(CI))
6047     return Result;
6048
6049   Value *Src = CI.getOperand(0);
6050   const Type *SrcTy = Src->getType();
6051   const Type *DestTy = CI.getType();
6052   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6053   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6054
6055   // See if we can simplify any instructions used by the LHS whose sole 
6056   // purpose is to compute bits we don't care about.
6057   uint64_t KnownZero = 0, KnownOne = 0;
6058   if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
6059                            KnownZero, KnownOne))
6060     return &CI;
6061
6062   // If the source isn't an instruction or has more than one use then we
6063   // can't do anything more. 
6064   Instruction *SrcI = dyn_cast<Instruction>(Src);
6065   if (!SrcI || !Src->hasOneUse())
6066     return 0;
6067
6068   // Attempt to propagate the cast into the instruction.
6069   int NumCastsRemoved = 0;
6070   if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6071     // If this cast is a truncate, evaluting in a different type always
6072     // eliminates the cast, so it is always a win.  If this is a noop-cast
6073     // this just removes a noop cast which isn't pointful, but simplifies
6074     // the code.  If this is a zero-extension, we need to do an AND to
6075     // maintain the clear top-part of the computation, so we require that
6076     // the input have eliminated at least one cast.  If this is a sign
6077     // extension, we insert two new casts (to do the extension) so we
6078     // require that two casts have been eliminated.
6079     bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6080     if (!DoXForm) {
6081       switch (CI.getOpcode()) {
6082         case Instruction::Trunc:
6083           DoXForm = true;
6084           break;
6085         case Instruction::ZExt:
6086           DoXForm = NumCastsRemoved >= 1;
6087           break;
6088         case Instruction::SExt:
6089           DoXForm = NumCastsRemoved >= 2;
6090           break;
6091         case Instruction::BitCast:
6092           DoXForm = false;
6093           break;
6094         default:
6095           // All the others use floating point so we shouldn't actually 
6096           // get here because of the check above.
6097           assert(!"Unknown cast type .. unreachable");
6098           break;
6099       }
6100     }
6101     
6102     if (DoXForm) {
6103       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6104                                            CI.getOpcode() == Instruction::SExt);
6105       assert(Res->getType() == DestTy);
6106       switch (CI.getOpcode()) {
6107       default: assert(0 && "Unknown cast type!");
6108       case Instruction::Trunc:
6109       case Instruction::BitCast:
6110         // Just replace this cast with the result.
6111         return ReplaceInstUsesWith(CI, Res);
6112       case Instruction::ZExt: {
6113         // We need to emit an AND to clear the high bits.
6114         assert(SrcBitSize < DestBitSize && "Not a zext?");
6115         Constant *C = 
6116           ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
6117         if (DestBitSize < 64)
6118           C = ConstantExpr::getTrunc(C, DestTy);
6119         return BinaryOperator::createAnd(Res, C);
6120       }
6121       case Instruction::SExt:
6122         // We need to emit a cast to truncate, then a cast to sext.
6123         return CastInst::create(Instruction::SExt,
6124             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6125                              CI), DestTy);
6126       }
6127     }
6128   }
6129   
6130   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6131   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6132
6133   switch (SrcI->getOpcode()) {
6134   case Instruction::Add:
6135   case Instruction::Mul:
6136   case Instruction::And:
6137   case Instruction::Or:
6138   case Instruction::Xor:
6139     // If we are discarding information, or just changing the sign, 
6140     // rewrite.
6141     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6142       // Don't insert two casts if they cannot be eliminated.  We allow 
6143       // two casts to be inserted if the sizes are the same.  This could 
6144       // only be converting signedness, which is a noop.
6145       if (DestBitSize == SrcBitSize || 
6146           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6147           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6148         Instruction::CastOps opcode = CI.getOpcode();
6149         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6150         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6151         return BinaryOperator::create(
6152             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6153       }
6154     }
6155
6156     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6157     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6158         SrcI->getOpcode() == Instruction::Xor &&
6159         Op1 == ConstantInt::getTrue() &&
6160         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6161       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6162       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6163     }
6164     break;
6165   case Instruction::SDiv:
6166   case Instruction::UDiv:
6167   case Instruction::SRem:
6168   case Instruction::URem:
6169     // If we are just changing the sign, rewrite.
6170     if (DestBitSize == SrcBitSize) {
6171       // Don't insert two casts if they cannot be eliminated.  We allow 
6172       // two casts to be inserted if the sizes are the same.  This could 
6173       // only be converting signedness, which is a noop.
6174       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6175           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6176         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6177                                               Op0, DestTy, SrcI);
6178         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6179                                               Op1, DestTy, SrcI);
6180         return BinaryOperator::create(
6181           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6182       }
6183     }
6184     break;
6185
6186   case Instruction::Shl:
6187     // Allow changing the sign of the source operand.  Do not allow 
6188     // changing the size of the shift, UNLESS the shift amount is a 
6189     // constant.  We must not change variable sized shifts to a smaller 
6190     // size, because it is undefined to shift more bits out than exist 
6191     // in the value.
6192     if (DestBitSize == SrcBitSize ||
6193         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6194       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6195           Instruction::BitCast : Instruction::Trunc);
6196       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6197       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6198       return BinaryOperator::createShl(Op0c, Op1c);
6199     }
6200     break;
6201   case Instruction::AShr:
6202     // If this is a signed shr, and if all bits shifted in are about to be
6203     // truncated off, turn it into an unsigned shr to allow greater
6204     // simplifications.
6205     if (DestBitSize < SrcBitSize &&
6206         isa<ConstantInt>(Op1)) {
6207       unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6208       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6209         // Insert the new logical shift right.
6210         return BinaryOperator::createLShr(Op0, Op1);
6211       }
6212     }
6213     break;
6214
6215   case Instruction::ICmp:
6216     // If we are just checking for a icmp eq of a single bit and casting it
6217     // to an integer, then shift the bit to the appropriate place and then
6218     // cast to integer to avoid the comparison.
6219     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6220       uint64_t Op1CV = Op1C->getZExtValue();
6221       // cast (X == 0) to int --> X^1      iff X has only the low bit set.
6222       // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6223       // cast (X == 1) to int --> X        iff X has only the low bit set.
6224       // cast (X == 2) to int --> X>>1     iff X has only the 2nd bit set.
6225       // cast (X != 0) to int --> X        iff X has only the low bit set.
6226       // cast (X != 0) to int --> X>>1     iff X has only the 2nd bit set.
6227       // cast (X != 1) to int --> X^1      iff X has only the low bit set.
6228       // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6229       if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6230         // If Op1C some other power of two, convert:
6231         uint64_t KnownZero, KnownOne;
6232         uint64_t TypeMask = Op1C->getType()->getBitMask();
6233         ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
6234
6235         // This only works for EQ and NE
6236         ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6237         if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6238           break;
6239         
6240         if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
6241           bool isNE = pred == ICmpInst::ICMP_NE;
6242           if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6243             // (X&4) == 2 --> false
6244             // (X&4) != 2 --> true
6245             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6246             Res = ConstantExpr::getZExt(Res, CI.getType());
6247             return ReplaceInstUsesWith(CI, Res);
6248           }
6249           
6250           unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6251           Value *In = Op0;
6252           if (ShiftAmt) {
6253             // Perform a logical shr by shiftamt.
6254             // Insert the shift to put the result in the low bit.
6255             In = InsertNewInstBefore(
6256               BinaryOperator::createLShr(In,
6257                                      ConstantInt::get(In->getType(), ShiftAmt),
6258                                      In->getName()+".lobit"), CI);
6259           }
6260           
6261           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6262             Constant *One = ConstantInt::get(In->getType(), 1);
6263             In = BinaryOperator::createXor(In, One, "tmp");
6264             InsertNewInstBefore(cast<Instruction>(In), CI);
6265           }
6266           
6267           if (CI.getType() == In->getType())
6268             return ReplaceInstUsesWith(CI, In);
6269           else
6270             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6271         }
6272       }
6273     }
6274     break;
6275   }
6276   return 0;
6277 }
6278
6279 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
6280   if (Instruction *Result = commonIntCastTransforms(CI))
6281     return Result;
6282   
6283   Value *Src = CI.getOperand(0);
6284   const Type *Ty = CI.getType();
6285   unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6286   
6287   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6288     switch (SrcI->getOpcode()) {
6289     default: break;
6290     case Instruction::LShr:
6291       // We can shrink lshr to something smaller if we know the bits shifted in
6292       // are already zeros.
6293       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6294         unsigned ShAmt = ShAmtV->getZExtValue();
6295         
6296         // Get a mask for the bits shifting in.
6297         uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
6298         Value* SrcIOp0 = SrcI->getOperand(0);
6299         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6300           if (ShAmt >= DestBitWidth)        // All zeros.
6301             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6302
6303           // Okay, we can shrink this.  Truncate the input, then return a new
6304           // shift.
6305           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6306           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6307                                        Ty, CI);
6308           return BinaryOperator::createLShr(V1, V2);
6309         }
6310       } else {     // This is a variable shr.
6311         
6312         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6313         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6314         // loop-invariant and CSE'd.
6315         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6316           Value *One = ConstantInt::get(SrcI->getType(), 1);
6317
6318           Value *V = InsertNewInstBefore(
6319               BinaryOperator::createShl(One, SrcI->getOperand(1),
6320                                      "tmp"), CI);
6321           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6322                                                             SrcI->getOperand(0),
6323                                                             "tmp"), CI);
6324           Value *Zero = Constant::getNullValue(V->getType());
6325           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6326         }
6327       }
6328       break;
6329     }
6330   }
6331   
6332   return 0;
6333 }
6334
6335 Instruction *InstCombiner::visitZExt(CastInst &CI) {
6336   // If one of the common conversion will work ..
6337   if (Instruction *Result = commonIntCastTransforms(CI))
6338     return Result;
6339
6340   Value *Src = CI.getOperand(0);
6341
6342   // If this is a cast of a cast
6343   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6344     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6345     // types and if the sizes are just right we can convert this into a logical
6346     // 'and' which will be much cheaper than the pair of casts.
6347     if (isa<TruncInst>(CSrc)) {
6348       // Get the sizes of the types involved
6349       Value *A = CSrc->getOperand(0);
6350       unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6351       unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6352       unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6353       // If we're actually extending zero bits and the trunc is a no-op
6354       if (MidSize < DstSize && SrcSize == DstSize) {
6355         // Replace both of the casts with an And of the type mask.
6356         uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
6357         Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6358         Instruction *And = 
6359           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6360         // Unfortunately, if the type changed, we need to cast it back.
6361         if (And->getType() != CI.getType()) {
6362           And->setName(CSrc->getName()+".mask");
6363           InsertNewInstBefore(And, CI);
6364           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6365         }
6366         return And;
6367       }
6368     }
6369   }
6370
6371   return 0;
6372 }
6373
6374 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6375   return commonIntCastTransforms(CI);
6376 }
6377
6378 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6379   return commonCastTransforms(CI);
6380 }
6381
6382 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6383   return commonCastTransforms(CI);
6384 }
6385
6386 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6387   return commonCastTransforms(CI);
6388 }
6389
6390 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6391   return commonCastTransforms(CI);
6392 }
6393
6394 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6395   return commonCastTransforms(CI);
6396 }
6397
6398 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6399   return commonCastTransforms(CI);
6400 }
6401
6402 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6403   return commonCastTransforms(CI);
6404 }
6405
6406 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6407   return commonCastTransforms(CI);
6408 }
6409
6410 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6411
6412   // If the operands are integer typed then apply the integer transforms,
6413   // otherwise just apply the common ones.
6414   Value *Src = CI.getOperand(0);
6415   const Type *SrcTy = Src->getType();
6416   const Type *DestTy = CI.getType();
6417
6418   if (SrcTy->isInteger() && DestTy->isInteger()) {
6419     if (Instruction *Result = commonIntCastTransforms(CI))
6420       return Result;
6421   } else {
6422     if (Instruction *Result = commonCastTransforms(CI))
6423       return Result;
6424   }
6425
6426
6427   // Get rid of casts from one type to the same type. These are useless and can
6428   // be replaced by the operand.
6429   if (DestTy == Src->getType())
6430     return ReplaceInstUsesWith(CI, Src);
6431
6432   // If the source and destination are pointers, and this cast is equivalent to
6433   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
6434   // This can enhance SROA and other transforms that want type-safe pointers.
6435   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6436     if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6437       const Type *DstElTy = DstPTy->getElementType();
6438       const Type *SrcElTy = SrcPTy->getElementType();
6439       
6440       Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6441       unsigned NumZeros = 0;
6442       while (SrcElTy != DstElTy && 
6443              isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6444              SrcElTy->getNumContainedTypes() /* not "{}" */) {
6445         SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6446         ++NumZeros;
6447       }
6448
6449       // If we found a path from the src to dest, create the getelementptr now.
6450       if (SrcElTy == DstElTy) {
6451         SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6452         return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
6453       }
6454     }
6455   }
6456
6457   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6458     if (SVI->hasOneUse()) {
6459       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
6460       // a bitconvert to a vector with the same # elts.
6461       if (isa<VectorType>(DestTy) && 
6462           cast<VectorType>(DestTy)->getNumElements() == 
6463                 SVI->getType()->getNumElements()) {
6464         CastInst *Tmp;
6465         // If either of the operands is a cast from CI.getType(), then
6466         // evaluating the shuffle in the casted destination's type will allow
6467         // us to eliminate at least one cast.
6468         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
6469              Tmp->getOperand(0)->getType() == DestTy) ||
6470             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
6471              Tmp->getOperand(0)->getType() == DestTy)) {
6472           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6473                                                SVI->getOperand(0), DestTy, &CI);
6474           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6475                                                SVI->getOperand(1), DestTy, &CI);
6476           // Return a new shuffle vector.  Use the same element ID's, as we
6477           // know the vector types match #elts.
6478           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6479         }
6480       }
6481     }
6482   }
6483   return 0;
6484 }
6485
6486 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6487 ///   %C = or %A, %B
6488 ///   %D = select %cond, %C, %A
6489 /// into:
6490 ///   %C = select %cond, %B, 0
6491 ///   %D = or %A, %C
6492 ///
6493 /// Assuming that the specified instruction is an operand to the select, return
6494 /// a bitmask indicating which operands of this instruction are foldable if they
6495 /// equal the other incoming value of the select.
6496 ///
6497 static unsigned GetSelectFoldableOperands(Instruction *I) {
6498   switch (I->getOpcode()) {
6499   case Instruction::Add:
6500   case Instruction::Mul:
6501   case Instruction::And:
6502   case Instruction::Or:
6503   case Instruction::Xor:
6504     return 3;              // Can fold through either operand.
6505   case Instruction::Sub:   // Can only fold on the amount subtracted.
6506   case Instruction::Shl:   // Can only fold on the shift amount.
6507   case Instruction::LShr:
6508   case Instruction::AShr:
6509     return 1;
6510   default:
6511     return 0;              // Cannot fold
6512   }
6513 }
6514
6515 /// GetSelectFoldableConstant - For the same transformation as the previous
6516 /// function, return the identity constant that goes into the select.
6517 static Constant *GetSelectFoldableConstant(Instruction *I) {
6518   switch (I->getOpcode()) {
6519   default: assert(0 && "This cannot happen!"); abort();
6520   case Instruction::Add:
6521   case Instruction::Sub:
6522   case Instruction::Or:
6523   case Instruction::Xor:
6524   case Instruction::Shl:
6525   case Instruction::LShr:
6526   case Instruction::AShr:
6527     return Constant::getNullValue(I->getType());
6528   case Instruction::And:
6529     return ConstantInt::getAllOnesValue(I->getType());
6530   case Instruction::Mul:
6531     return ConstantInt::get(I->getType(), 1);
6532   }
6533 }
6534
6535 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6536 /// have the same opcode and only one use each.  Try to simplify this.
6537 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6538                                           Instruction *FI) {
6539   if (TI->getNumOperands() == 1) {
6540     // If this is a non-volatile load or a cast from the same type,
6541     // merge.
6542     if (TI->isCast()) {
6543       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6544         return 0;
6545     } else {
6546       return 0;  // unknown unary op.
6547     }
6548
6549     // Fold this by inserting a select from the input values.
6550     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6551                                        FI->getOperand(0), SI.getName()+".v");
6552     InsertNewInstBefore(NewSI, SI);
6553     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
6554                             TI->getType());
6555   }
6556
6557   // Only handle binary operators here.
6558   if (!isa<BinaryOperator>(TI))
6559     return 0;
6560
6561   // Figure out if the operations have any operands in common.
6562   Value *MatchOp, *OtherOpT, *OtherOpF;
6563   bool MatchIsOpZero;
6564   if (TI->getOperand(0) == FI->getOperand(0)) {
6565     MatchOp  = TI->getOperand(0);
6566     OtherOpT = TI->getOperand(1);
6567     OtherOpF = FI->getOperand(1);
6568     MatchIsOpZero = true;
6569   } else if (TI->getOperand(1) == FI->getOperand(1)) {
6570     MatchOp  = TI->getOperand(1);
6571     OtherOpT = TI->getOperand(0);
6572     OtherOpF = FI->getOperand(0);
6573     MatchIsOpZero = false;
6574   } else if (!TI->isCommutative()) {
6575     return 0;
6576   } else if (TI->getOperand(0) == FI->getOperand(1)) {
6577     MatchOp  = TI->getOperand(0);
6578     OtherOpT = TI->getOperand(1);
6579     OtherOpF = FI->getOperand(0);
6580     MatchIsOpZero = true;
6581   } else if (TI->getOperand(1) == FI->getOperand(0)) {
6582     MatchOp  = TI->getOperand(1);
6583     OtherOpT = TI->getOperand(0);
6584     OtherOpF = FI->getOperand(1);
6585     MatchIsOpZero = true;
6586   } else {
6587     return 0;
6588   }
6589
6590   // If we reach here, they do have operations in common.
6591   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6592                                      OtherOpF, SI.getName()+".v");
6593   InsertNewInstBefore(NewSI, SI);
6594
6595   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6596     if (MatchIsOpZero)
6597       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6598     else
6599       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6600   }
6601   assert(0 && "Shouldn't get here");
6602   return 0;
6603 }
6604
6605 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6606   Value *CondVal = SI.getCondition();
6607   Value *TrueVal = SI.getTrueValue();
6608   Value *FalseVal = SI.getFalseValue();
6609
6610   // select true, X, Y  -> X
6611   // select false, X, Y -> Y
6612   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
6613     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
6614
6615   // select C, X, X -> X
6616   if (TrueVal == FalseVal)
6617     return ReplaceInstUsesWith(SI, TrueVal);
6618
6619   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
6620     return ReplaceInstUsesWith(SI, FalseVal);
6621   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
6622     return ReplaceInstUsesWith(SI, TrueVal);
6623   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
6624     if (isa<Constant>(TrueVal))
6625       return ReplaceInstUsesWith(SI, TrueVal);
6626     else
6627       return ReplaceInstUsesWith(SI, FalseVal);
6628   }
6629
6630   if (SI.getType() == Type::Int1Ty) {
6631     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
6632       if (C->getZExtValue()) {
6633         // Change: A = select B, true, C --> A = or B, C
6634         return BinaryOperator::createOr(CondVal, FalseVal);
6635       } else {
6636         // Change: A = select B, false, C --> A = and !B, C
6637         Value *NotCond =
6638           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6639                                              "not."+CondVal->getName()), SI);
6640         return BinaryOperator::createAnd(NotCond, FalseVal);
6641       }
6642     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
6643       if (C->getZExtValue() == false) {
6644         // Change: A = select B, C, false --> A = and B, C
6645         return BinaryOperator::createAnd(CondVal, TrueVal);
6646       } else {
6647         // Change: A = select B, C, true --> A = or !B, C
6648         Value *NotCond =
6649           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6650                                              "not."+CondVal->getName()), SI);
6651         return BinaryOperator::createOr(NotCond, TrueVal);
6652       }
6653     }
6654   }
6655
6656   // Selecting between two integer constants?
6657   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6658     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6659       // select C, 1, 0 -> cast C to int
6660       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6661         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6662       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6663         // select C, 0, 1 -> cast !C to int
6664         Value *NotCond =
6665           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6666                                                "not."+CondVal->getName()), SI);
6667         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6668       }
6669
6670       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
6671
6672         // (x <s 0) ? -1 : 0 -> ashr x, 31
6673         // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
6674         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6675           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6676             bool CanXForm = false;
6677             if (IC->isSignedPredicate())
6678               CanXForm = CmpCst->isNullValue() && 
6679                          IC->getPredicate() == ICmpInst::ICMP_SLT;
6680             else {
6681               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6682               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6683                          IC->getPredicate() == ICmpInst::ICMP_UGT;
6684             }
6685             
6686             if (CanXForm) {
6687               // The comparison constant and the result are not neccessarily the
6688               // same width. Make an all-ones value by inserting a AShr.
6689               Value *X = IC->getOperand(0);
6690               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6691               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6692               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6693                                                         ShAmt, "ones");
6694               InsertNewInstBefore(SRA, SI);
6695               
6696               // Finally, convert to the type of the select RHS.  We figure out
6697               // if this requires a SExt, Trunc or BitCast based on the sizes.
6698               Instruction::CastOps opc = Instruction::BitCast;
6699               unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6700               unsigned SISize  = SI.getType()->getPrimitiveSizeInBits();
6701               if (SRASize < SISize)
6702                 opc = Instruction::SExt;
6703               else if (SRASize > SISize)
6704                 opc = Instruction::Trunc;
6705               return CastInst::create(opc, SRA, SI.getType());
6706             }
6707           }
6708
6709
6710         // If one of the constants is zero (we know they can't both be) and we
6711         // have a fcmp instruction with zero, and we have an 'and' with the
6712         // non-constant value, eliminate this whole mess.  This corresponds to
6713         // cases like this: ((X & 27) ? 27 : 0)
6714         if (TrueValC->isNullValue() || FalseValC->isNullValue())
6715           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6716               cast<Constant>(IC->getOperand(1))->isNullValue())
6717             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6718               if (ICA->getOpcode() == Instruction::And &&
6719                   isa<ConstantInt>(ICA->getOperand(1)) &&
6720                   (ICA->getOperand(1) == TrueValC ||
6721                    ICA->getOperand(1) == FalseValC) &&
6722                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6723                 // Okay, now we know that everything is set up, we just don't
6724                 // know whether we have a icmp_ne or icmp_eq and whether the 
6725                 // true or false val is the zero.
6726                 bool ShouldNotVal = !TrueValC->isNullValue();
6727                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
6728                 Value *V = ICA;
6729                 if (ShouldNotVal)
6730                   V = InsertNewInstBefore(BinaryOperator::create(
6731                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
6732                 return ReplaceInstUsesWith(SI, V);
6733               }
6734       }
6735     }
6736
6737   // See if we are selecting two values based on a comparison of the two values.
6738   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6739     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
6740       // Transform (X == Y) ? X : Y  -> Y
6741       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6742         return ReplaceInstUsesWith(SI, FalseVal);
6743       // Transform (X != Y) ? X : Y  -> X
6744       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6745         return ReplaceInstUsesWith(SI, TrueVal);
6746       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6747
6748     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
6749       // Transform (X == Y) ? Y : X  -> X
6750       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6751         return ReplaceInstUsesWith(SI, FalseVal);
6752       // Transform (X != Y) ? Y : X  -> Y
6753       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6754         return ReplaceInstUsesWith(SI, TrueVal);
6755       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6756     }
6757   }
6758
6759   // See if we are selecting two values based on a comparison of the two values.
6760   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6761     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6762       // Transform (X == Y) ? X : Y  -> Y
6763       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6764         return ReplaceInstUsesWith(SI, FalseVal);
6765       // Transform (X != Y) ? X : Y  -> X
6766       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6767         return ReplaceInstUsesWith(SI, TrueVal);
6768       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6769
6770     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6771       // Transform (X == Y) ? Y : X  -> X
6772       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6773         return ReplaceInstUsesWith(SI, FalseVal);
6774       // Transform (X != Y) ? Y : X  -> Y
6775       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6776         return ReplaceInstUsesWith(SI, TrueVal);
6777       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6778     }
6779   }
6780
6781   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6782     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6783       if (TI->hasOneUse() && FI->hasOneUse()) {
6784         Instruction *AddOp = 0, *SubOp = 0;
6785
6786         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6787         if (TI->getOpcode() == FI->getOpcode())
6788           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6789             return IV;
6790
6791         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
6792         // even legal for FP.
6793         if (TI->getOpcode() == Instruction::Sub &&
6794             FI->getOpcode() == Instruction::Add) {
6795           AddOp = FI; SubOp = TI;
6796         } else if (FI->getOpcode() == Instruction::Sub &&
6797                    TI->getOpcode() == Instruction::Add) {
6798           AddOp = TI; SubOp = FI;
6799         }
6800
6801         if (AddOp) {
6802           Value *OtherAddOp = 0;
6803           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6804             OtherAddOp = AddOp->getOperand(1);
6805           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6806             OtherAddOp = AddOp->getOperand(0);
6807           }
6808
6809           if (OtherAddOp) {
6810             // So at this point we know we have (Y -> OtherAddOp):
6811             //        select C, (add X, Y), (sub X, Z)
6812             Value *NegVal;  // Compute -Z
6813             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6814               NegVal = ConstantExpr::getNeg(C);
6815             } else {
6816               NegVal = InsertNewInstBefore(
6817                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6818             }
6819
6820             Value *NewTrueOp = OtherAddOp;
6821             Value *NewFalseOp = NegVal;
6822             if (AddOp != TI)
6823               std::swap(NewTrueOp, NewFalseOp);
6824             Instruction *NewSel =
6825               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6826
6827             NewSel = InsertNewInstBefore(NewSel, SI);
6828             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6829           }
6830         }
6831       }
6832
6833   // See if we can fold the select into one of our operands.
6834   if (SI.getType()->isInteger()) {
6835     // See the comment above GetSelectFoldableOperands for a description of the
6836     // transformation we are doing here.
6837     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6838       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6839           !isa<Constant>(FalseVal))
6840         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6841           unsigned OpToFold = 0;
6842           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6843             OpToFold = 1;
6844           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6845             OpToFold = 2;
6846           }
6847
6848           if (OpToFold) {
6849             Constant *C = GetSelectFoldableConstant(TVI);
6850             Instruction *NewSel =
6851               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
6852             InsertNewInstBefore(NewSel, SI);
6853             NewSel->takeName(TVI);
6854             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6855               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6856             else {
6857               assert(0 && "Unknown instruction!!");
6858             }
6859           }
6860         }
6861
6862     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6863       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6864           !isa<Constant>(TrueVal))
6865         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6866           unsigned OpToFold = 0;
6867           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6868             OpToFold = 1;
6869           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6870             OpToFold = 2;
6871           }
6872
6873           if (OpToFold) {
6874             Constant *C = GetSelectFoldableConstant(FVI);
6875             Instruction *NewSel =
6876               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
6877             InsertNewInstBefore(NewSel, SI);
6878             NewSel->takeName(FVI);
6879             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6880               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6881             else
6882               assert(0 && "Unknown instruction!!");
6883           }
6884         }
6885   }
6886
6887   if (BinaryOperator::isNot(CondVal)) {
6888     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6889     SI.setOperand(1, FalseVal);
6890     SI.setOperand(2, TrueVal);
6891     return &SI;
6892   }
6893
6894   return 0;
6895 }
6896
6897 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6898 /// determine, return it, otherwise return 0.
6899 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6900   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6901     unsigned Align = GV->getAlignment();
6902     if (Align == 0 && TD) 
6903       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
6904     return Align;
6905   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6906     unsigned Align = AI->getAlignment();
6907     if (Align == 0 && TD) {
6908       if (isa<AllocaInst>(AI))
6909         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
6910       else if (isa<MallocInst>(AI)) {
6911         // Malloc returns maximally aligned memory.
6912         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
6913         Align =
6914           std::max(Align,
6915                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
6916         Align =
6917           std::max(Align,
6918                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
6919       }
6920     }
6921     return Align;
6922   } else if (isa<BitCastInst>(V) ||
6923              (isa<ConstantExpr>(V) && 
6924               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
6925     User *CI = cast<User>(V);
6926     if (isa<PointerType>(CI->getOperand(0)->getType()))
6927       return GetKnownAlignment(CI->getOperand(0), TD);
6928     return 0;
6929   } else if (isa<GetElementPtrInst>(V) ||
6930              (isa<ConstantExpr>(V) && 
6931               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6932     User *GEPI = cast<User>(V);
6933     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6934     if (BaseAlignment == 0) return 0;
6935     
6936     // If all indexes are zero, it is just the alignment of the base pointer.
6937     bool AllZeroOperands = true;
6938     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6939       if (!isa<Constant>(GEPI->getOperand(i)) ||
6940           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6941         AllZeroOperands = false;
6942         break;
6943       }
6944     if (AllZeroOperands)
6945       return BaseAlignment;
6946     
6947     // Otherwise, if the base alignment is >= the alignment we expect for the
6948     // base pointer type, then we know that the resultant pointer is aligned at
6949     // least as much as its type requires.
6950     if (!TD) return 0;
6951
6952     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6953     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
6954     if (TD->getABITypeAlignment(PtrTy->getElementType())
6955         <= BaseAlignment) {
6956       const Type *GEPTy = GEPI->getType();
6957       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
6958       return TD->getABITypeAlignment(GEPPtrTy->getElementType());
6959     }
6960     return 0;
6961   }
6962   return 0;
6963 }
6964
6965
6966 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
6967 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
6968 /// the heavy lifting.
6969 ///
6970 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6971   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6972   if (!II) return visitCallSite(&CI);
6973   
6974   // Intrinsics cannot occur in an invoke, so handle them here instead of in
6975   // visitCallSite.
6976   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6977     bool Changed = false;
6978
6979     // memmove/cpy/set of zero bytes is a noop.
6980     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6981       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6982
6983       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6984         if (CI->getZExtValue() == 1) {
6985           // Replace the instruction with just byte operations.  We would
6986           // transform other cases to loads/stores, but we don't know if
6987           // alignment is sufficient.
6988         }
6989     }
6990
6991     // If we have a memmove and the source operation is a constant global,
6992     // then the source and dest pointers can't alias, so we can change this
6993     // into a call to memcpy.
6994     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6995       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6996         if (GVSrc->isConstant()) {
6997           Module *M = CI.getParent()->getParent()->getParent();
6998           const char *Name;
6999           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
7000               Type::Int32Ty)
7001             Name = "llvm.memcpy.i32";
7002           else
7003             Name = "llvm.memcpy.i64";
7004           Constant *MemCpy = M->getOrInsertFunction(Name,
7005                                      CI.getCalledFunction()->getFunctionType());
7006           CI.setOperand(0, MemCpy);
7007           Changed = true;
7008         }
7009     }
7010
7011     // If we can determine a pointer alignment that is bigger than currently
7012     // set, update the alignment.
7013     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7014       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7015       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7016       unsigned Align = std::min(Alignment1, Alignment2);
7017       if (MI->getAlignment()->getZExtValue() < Align) {
7018         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7019         Changed = true;
7020       }
7021     } else if (isa<MemSetInst>(MI)) {
7022       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
7023       if (MI->getAlignment()->getZExtValue() < Alignment) {
7024         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7025         Changed = true;
7026       }
7027     }
7028           
7029     if (Changed) return II;
7030   } else {
7031     switch (II->getIntrinsicID()) {
7032     default: break;
7033     case Intrinsic::ppc_altivec_lvx:
7034     case Intrinsic::ppc_altivec_lvxl:
7035     case Intrinsic::x86_sse_loadu_ps:
7036     case Intrinsic::x86_sse2_loadu_pd:
7037     case Intrinsic::x86_sse2_loadu_dq:
7038       // Turn PPC lvx     -> load if the pointer is known aligned.
7039       // Turn X86 loadups -> load if the pointer is known aligned.
7040       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7041         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7042                                       PointerType::get(II->getType()), CI);
7043         return new LoadInst(Ptr);
7044       }
7045       break;
7046     case Intrinsic::ppc_altivec_stvx:
7047     case Intrinsic::ppc_altivec_stvxl:
7048       // Turn stvx -> store if the pointer is known aligned.
7049       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7050         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7051         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7052                                       OpPtrTy, CI);
7053         return new StoreInst(II->getOperand(1), Ptr);
7054       }
7055       break;
7056     case Intrinsic::x86_sse_storeu_ps:
7057     case Intrinsic::x86_sse2_storeu_pd:
7058     case Intrinsic::x86_sse2_storeu_dq:
7059     case Intrinsic::x86_sse2_storel_dq:
7060       // Turn X86 storeu -> store if the pointer is known aligned.
7061       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7062         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7063         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7064                                       OpPtrTy, CI);
7065         return new StoreInst(II->getOperand(2), Ptr);
7066       }
7067       break;
7068       
7069     case Intrinsic::x86_sse_cvttss2si: {
7070       // These intrinsics only demands the 0th element of its input vector.  If
7071       // we can simplify the input based on that, do so now.
7072       uint64_t UndefElts;
7073       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7074                                                 UndefElts)) {
7075         II->setOperand(1, V);
7076         return II;
7077       }
7078       break;
7079     }
7080       
7081     case Intrinsic::ppc_altivec_vperm:
7082       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7083       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
7084         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7085         
7086         // Check that all of the elements are integer constants or undefs.
7087         bool AllEltsOk = true;
7088         for (unsigned i = 0; i != 16; ++i) {
7089           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7090               !isa<UndefValue>(Mask->getOperand(i))) {
7091             AllEltsOk = false;
7092             break;
7093           }
7094         }
7095         
7096         if (AllEltsOk) {
7097           // Cast the input vectors to byte vectors.
7098           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7099                                         II->getOperand(1), Mask->getType(), CI);
7100           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7101                                         II->getOperand(2), Mask->getType(), CI);
7102           Value *Result = UndefValue::get(Op0->getType());
7103           
7104           // Only extract each element once.
7105           Value *ExtractedElts[32];
7106           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7107           
7108           for (unsigned i = 0; i != 16; ++i) {
7109             if (isa<UndefValue>(Mask->getOperand(i)))
7110               continue;
7111             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7112             Idx &= 31;  // Match the hardware behavior.
7113             
7114             if (ExtractedElts[Idx] == 0) {
7115               Instruction *Elt = 
7116                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7117               InsertNewInstBefore(Elt, CI);
7118               ExtractedElts[Idx] = Elt;
7119             }
7120           
7121             // Insert this value into the result vector.
7122             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7123             InsertNewInstBefore(cast<Instruction>(Result), CI);
7124           }
7125           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7126         }
7127       }
7128       break;
7129
7130     case Intrinsic::stackrestore: {
7131       // If the save is right next to the restore, remove the restore.  This can
7132       // happen when variable allocas are DCE'd.
7133       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7134         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7135           BasicBlock::iterator BI = SS;
7136           if (&*++BI == II)
7137             return EraseInstFromFunction(CI);
7138         }
7139       }
7140       
7141       // If the stack restore is in a return/unwind block and if there are no
7142       // allocas or calls between the restore and the return, nuke the restore.
7143       TerminatorInst *TI = II->getParent()->getTerminator();
7144       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7145         BasicBlock::iterator BI = II;
7146         bool CannotRemove = false;
7147         for (++BI; &*BI != TI; ++BI) {
7148           if (isa<AllocaInst>(BI) ||
7149               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7150             CannotRemove = true;
7151             break;
7152           }
7153         }
7154         if (!CannotRemove)
7155           return EraseInstFromFunction(CI);
7156       }
7157       break;
7158     }
7159     }
7160   }
7161
7162   return visitCallSite(II);
7163 }
7164
7165 // InvokeInst simplification
7166 //
7167 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7168   return visitCallSite(&II);
7169 }
7170
7171 // visitCallSite - Improvements for call and invoke instructions.
7172 //
7173 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7174   bool Changed = false;
7175
7176   // If the callee is a constexpr cast of a function, attempt to move the cast
7177   // to the arguments of the call/invoke.
7178   if (transformConstExprCastCall(CS)) return 0;
7179
7180   Value *Callee = CS.getCalledValue();
7181
7182   if (Function *CalleeF = dyn_cast<Function>(Callee))
7183     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7184       Instruction *OldCall = CS.getInstruction();
7185       // If the call and callee calling conventions don't match, this call must
7186       // be unreachable, as the call is undefined.
7187       new StoreInst(ConstantInt::getTrue(),
7188                     UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
7189       if (!OldCall->use_empty())
7190         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7191       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7192         return EraseInstFromFunction(*OldCall);
7193       return 0;
7194     }
7195
7196   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7197     // This instruction is not reachable, just remove it.  We insert a store to
7198     // undef so that we know that this code is not reachable, despite the fact
7199     // that we can't modify the CFG here.
7200     new StoreInst(ConstantInt::getTrue(),
7201                   UndefValue::get(PointerType::get(Type::Int1Ty)),
7202                   CS.getInstruction());
7203
7204     if (!CS.getInstruction()->use_empty())
7205       CS.getInstruction()->
7206         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7207
7208     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7209       // Don't break the CFG, insert a dummy cond branch.
7210       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7211                      ConstantInt::getTrue(), II);
7212     }
7213     return EraseInstFromFunction(*CS.getInstruction());
7214   }
7215
7216   const PointerType *PTy = cast<PointerType>(Callee->getType());
7217   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7218   if (FTy->isVarArg()) {
7219     // See if we can optimize any arguments passed through the varargs area of
7220     // the call.
7221     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7222            E = CS.arg_end(); I != E; ++I)
7223       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7224         // If this cast does not effect the value passed through the varargs
7225         // area, we can eliminate the use of the cast.
7226         Value *Op = CI->getOperand(0);
7227         if (CI->isLosslessCast()) {
7228           *I = Op;
7229           Changed = true;
7230         }
7231       }
7232   }
7233
7234   return Changed ? CS.getInstruction() : 0;
7235 }
7236
7237 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7238 // attempt to move the cast to the arguments of the call/invoke.
7239 //
7240 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7241   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7242   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7243   if (CE->getOpcode() != Instruction::BitCast || 
7244       !isa<Function>(CE->getOperand(0)))
7245     return false;
7246   Function *Callee = cast<Function>(CE->getOperand(0));
7247   Instruction *Caller = CS.getInstruction();
7248
7249   // Okay, this is a cast from a function to a different type.  Unless doing so
7250   // would cause a type conversion of one of our arguments, change this call to
7251   // be a direct call with arguments casted to the appropriate types.
7252   //
7253   const FunctionType *FT = Callee->getFunctionType();
7254   const Type *OldRetTy = Caller->getType();
7255
7256   // Check to see if we are changing the return type...
7257   if (OldRetTy != FT->getReturnType()) {
7258     if (Callee->isDeclaration() && !Caller->use_empty() && 
7259         OldRetTy != FT->getReturnType() &&
7260         // Conversion is ok if changing from pointer to int of same size.
7261         !(isa<PointerType>(FT->getReturnType()) &&
7262           TD->getIntPtrType() == OldRetTy))
7263       return false;   // Cannot transform this return value.
7264
7265     // If the callsite is an invoke instruction, and the return value is used by
7266     // a PHI node in a successor, we cannot change the return type of the call
7267     // because there is no place to put the cast instruction (without breaking
7268     // the critical edge).  Bail out in this case.
7269     if (!Caller->use_empty())
7270       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7271         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7272              UI != E; ++UI)
7273           if (PHINode *PN = dyn_cast<PHINode>(*UI))
7274             if (PN->getParent() == II->getNormalDest() ||
7275                 PN->getParent() == II->getUnwindDest())
7276               return false;
7277   }
7278
7279   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7280   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7281
7282   CallSite::arg_iterator AI = CS.arg_begin();
7283   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7284     const Type *ParamTy = FT->getParamType(i);
7285     const Type *ActTy = (*AI)->getType();
7286     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7287     //Either we can cast directly, or we can upconvert the argument
7288     bool isConvertible = ActTy == ParamTy ||
7289       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
7290       (ParamTy->isInteger() && ActTy->isInteger() &&
7291        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7292       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7293        && c->getSExtValue() > 0);
7294     if (Callee->isDeclaration() && !isConvertible) return false;
7295   }
7296
7297   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7298       Callee->isDeclaration())
7299     return false;   // Do not delete arguments unless we have a function body...
7300
7301   // Okay, we decided that this is a safe thing to do: go ahead and start
7302   // inserting cast instructions as necessary...
7303   std::vector<Value*> Args;
7304   Args.reserve(NumActualArgs);
7305
7306   AI = CS.arg_begin();
7307   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7308     const Type *ParamTy = FT->getParamType(i);
7309     if ((*AI)->getType() == ParamTy) {
7310       Args.push_back(*AI);
7311     } else {
7312       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7313           false, ParamTy, false);
7314       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7315       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7316     }
7317   }
7318
7319   // If the function takes more arguments than the call was taking, add them
7320   // now...
7321   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7322     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7323
7324   // If we are removing arguments to the function, emit an obnoxious warning...
7325   if (FT->getNumParams() < NumActualArgs)
7326     if (!FT->isVarArg()) {
7327       cerr << "WARNING: While resolving call to function '"
7328            << Callee->getName() << "' arguments were dropped!\n";
7329     } else {
7330       // Add all of the arguments in their promoted form to the arg list...
7331       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7332         const Type *PTy = getPromotedType((*AI)->getType());
7333         if (PTy != (*AI)->getType()) {
7334           // Must promote to pass through va_arg area!
7335           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
7336                                                                 PTy, false);
7337           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7338           InsertNewInstBefore(Cast, *Caller);
7339           Args.push_back(Cast);
7340         } else {
7341           Args.push_back(*AI);
7342         }
7343       }
7344     }
7345
7346   if (FT->getReturnType() == Type::VoidTy)
7347     Caller->setName("");   // Void type should not have a name.
7348
7349   Instruction *NC;
7350   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7351     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7352                         &Args[0], Args.size(), Caller->getName(), Caller);
7353     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7354   } else {
7355     NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
7356     if (cast<CallInst>(Caller)->isTailCall())
7357       cast<CallInst>(NC)->setTailCall();
7358    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7359   }
7360
7361   // Insert a cast of the return type as necessary.
7362   Value *NV = NC;
7363   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7364     if (NV->getType() != Type::VoidTy) {
7365       const Type *CallerTy = Caller->getType();
7366       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
7367                                                             CallerTy, false);
7368       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7369
7370       // If this is an invoke instruction, we should insert it after the first
7371       // non-phi, instruction in the normal successor block.
7372       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7373         BasicBlock::iterator I = II->getNormalDest()->begin();
7374         while (isa<PHINode>(I)) ++I;
7375         InsertNewInstBefore(NC, *I);
7376       } else {
7377         // Otherwise, it's a call, just insert cast right after the call instr
7378         InsertNewInstBefore(NC, *Caller);
7379       }
7380       AddUsersToWorkList(*Caller);
7381     } else {
7382       NV = UndefValue::get(Caller->getType());
7383     }
7384   }
7385
7386   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7387     Caller->replaceAllUsesWith(NV);
7388   Caller->eraseFromParent();
7389   removeFromWorkList(Caller);
7390   return true;
7391 }
7392
7393 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7394 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7395 /// and a single binop.
7396 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7397   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7398   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7399          isa<CmpInst>(FirstInst));
7400   unsigned Opc = FirstInst->getOpcode();
7401   Value *LHSVal = FirstInst->getOperand(0);
7402   Value *RHSVal = FirstInst->getOperand(1);
7403     
7404   const Type *LHSType = LHSVal->getType();
7405   const Type *RHSType = RHSVal->getType();
7406   
7407   // Scan to see if all operands are the same opcode, all have one use, and all
7408   // kill their operands (i.e. the operands have one use).
7409   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7410     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7411     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7412         // Verify type of the LHS matches so we don't fold cmp's of different
7413         // types or GEP's with different index types.
7414         I->getOperand(0)->getType() != LHSType ||
7415         I->getOperand(1)->getType() != RHSType)
7416       return 0;
7417
7418     // If they are CmpInst instructions, check their predicates
7419     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7420       if (cast<CmpInst>(I)->getPredicate() !=
7421           cast<CmpInst>(FirstInst)->getPredicate())
7422         return 0;
7423     
7424     // Keep track of which operand needs a phi node.
7425     if (I->getOperand(0) != LHSVal) LHSVal = 0;
7426     if (I->getOperand(1) != RHSVal) RHSVal = 0;
7427   }
7428   
7429   // Otherwise, this is safe to transform, determine if it is profitable.
7430
7431   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7432   // Indexes are often folded into load/store instructions, so we don't want to
7433   // hide them behind a phi.
7434   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7435     return 0;
7436   
7437   Value *InLHS = FirstInst->getOperand(0);
7438   Value *InRHS = FirstInst->getOperand(1);
7439   PHINode *NewLHS = 0, *NewRHS = 0;
7440   if (LHSVal == 0) {
7441     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7442     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7443     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7444     InsertNewInstBefore(NewLHS, PN);
7445     LHSVal = NewLHS;
7446   }
7447   
7448   if (RHSVal == 0) {
7449     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7450     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7451     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7452     InsertNewInstBefore(NewRHS, PN);
7453     RHSVal = NewRHS;
7454   }
7455   
7456   // Add all operands to the new PHIs.
7457   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7458     if (NewLHS) {
7459       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7460       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7461     }
7462     if (NewRHS) {
7463       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7464       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7465     }
7466   }
7467     
7468   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7469     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7470   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7471     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
7472                            RHSVal);
7473   else {
7474     assert(isa<GetElementPtrInst>(FirstInst));
7475     return new GetElementPtrInst(LHSVal, RHSVal);
7476   }
7477 }
7478
7479 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7480 /// of the block that defines it.  This means that it must be obvious the value
7481 /// of the load is not changed from the point of the load to the end of the
7482 /// block it is in.
7483 ///
7484 /// Finally, it is safe, but not profitable, to sink a load targetting a
7485 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
7486 /// to a register.
7487 static bool isSafeToSinkLoad(LoadInst *L) {
7488   BasicBlock::iterator BBI = L, E = L->getParent()->end();
7489   
7490   for (++BBI; BBI != E; ++BBI)
7491     if (BBI->mayWriteToMemory())
7492       return false;
7493   
7494   // Check for non-address taken alloca.  If not address-taken already, it isn't
7495   // profitable to do this xform.
7496   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7497     bool isAddressTaken = false;
7498     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7499          UI != E; ++UI) {
7500       if (isa<LoadInst>(UI)) continue;
7501       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7502         // If storing TO the alloca, then the address isn't taken.
7503         if (SI->getOperand(1) == AI) continue;
7504       }
7505       isAddressTaken = true;
7506       break;
7507     }
7508     
7509     if (!isAddressTaken)
7510       return false;
7511   }
7512   
7513   return true;
7514 }
7515
7516
7517 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7518 // operator and they all are only used by the PHI, PHI together their
7519 // inputs, and do the operation once, to the result of the PHI.
7520 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7521   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7522
7523   // Scan the instruction, looking for input operations that can be folded away.
7524   // If all input operands to the phi are the same instruction (e.g. a cast from
7525   // the same type or "+42") we can pull the operation through the PHI, reducing
7526   // code size and simplifying code.
7527   Constant *ConstantOp = 0;
7528   const Type *CastSrcTy = 0;
7529   bool isVolatile = false;
7530   if (isa<CastInst>(FirstInst)) {
7531     CastSrcTy = FirstInst->getOperand(0)->getType();
7532   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
7533     // Can fold binop, compare or shift here if the RHS is a constant, 
7534     // otherwise call FoldPHIArgBinOpIntoPHI.
7535     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7536     if (ConstantOp == 0)
7537       return FoldPHIArgBinOpIntoPHI(PN);
7538   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7539     isVolatile = LI->isVolatile();
7540     // We can't sink the load if the loaded value could be modified between the
7541     // load and the PHI.
7542     if (LI->getParent() != PN.getIncomingBlock(0) ||
7543         !isSafeToSinkLoad(LI))
7544       return 0;
7545   } else if (isa<GetElementPtrInst>(FirstInst)) {
7546     if (FirstInst->getNumOperands() == 2)
7547       return FoldPHIArgBinOpIntoPHI(PN);
7548     // Can't handle general GEPs yet.
7549     return 0;
7550   } else {
7551     return 0;  // Cannot fold this operation.
7552   }
7553
7554   // Check to see if all arguments are the same operation.
7555   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7556     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7557     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7558     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
7559       return 0;
7560     if (CastSrcTy) {
7561       if (I->getOperand(0)->getType() != CastSrcTy)
7562         return 0;  // Cast operation must match.
7563     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7564       // We can't sink the load if the loaded value could be modified between 
7565       // the load and the PHI.
7566       if (LI->isVolatile() != isVolatile ||
7567           LI->getParent() != PN.getIncomingBlock(i) ||
7568           !isSafeToSinkLoad(LI))
7569         return 0;
7570     } else if (I->getOperand(1) != ConstantOp) {
7571       return 0;
7572     }
7573   }
7574
7575   // Okay, they are all the same operation.  Create a new PHI node of the
7576   // correct type, and PHI together all of the LHS's of the instructions.
7577   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7578                                PN.getName()+".in");
7579   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7580
7581   Value *InVal = FirstInst->getOperand(0);
7582   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7583
7584   // Add all operands to the new PHI.
7585   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7586     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7587     if (NewInVal != InVal)
7588       InVal = 0;
7589     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7590   }
7591
7592   Value *PhiVal;
7593   if (InVal) {
7594     // The new PHI unions all of the same values together.  This is really
7595     // common, so we handle it intelligently here for compile-time speed.
7596     PhiVal = InVal;
7597     delete NewPN;
7598   } else {
7599     InsertNewInstBefore(NewPN, PN);
7600     PhiVal = NewPN;
7601   }
7602
7603   // Insert and return the new operation.
7604   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7605     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7606   else if (isa<LoadInst>(FirstInst))
7607     return new LoadInst(PhiVal, "", isVolatile);
7608   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7609     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7610   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7611     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
7612                            PhiVal, ConstantOp);
7613   else
7614     assert(0 && "Unknown operation");
7615 }
7616
7617 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7618 /// that is dead.
7619 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7620   if (PN->use_empty()) return true;
7621   if (!PN->hasOneUse()) return false;
7622
7623   // Remember this node, and if we find the cycle, return.
7624   if (!PotentiallyDeadPHIs.insert(PN).second)
7625     return true;
7626
7627   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7628     return DeadPHICycle(PU, PotentiallyDeadPHIs);
7629
7630   return false;
7631 }
7632
7633 // PHINode simplification
7634 //
7635 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7636   // If LCSSA is around, don't mess with Phi nodes
7637   if (mustPreserveAnalysisID(LCSSAID)) return 0;
7638   
7639   if (Value *V = PN.hasConstantValue())
7640     return ReplaceInstUsesWith(PN, V);
7641
7642   // If all PHI operands are the same operation, pull them through the PHI,
7643   // reducing code size.
7644   if (isa<Instruction>(PN.getIncomingValue(0)) &&
7645       PN.getIncomingValue(0)->hasOneUse())
7646     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7647       return Result;
7648
7649   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
7650   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7651   // PHI)... break the cycle.
7652   if (PN.hasOneUse()) {
7653     Instruction *PHIUser = cast<Instruction>(PN.use_back());
7654     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
7655       std::set<PHINode*> PotentiallyDeadPHIs;
7656       PotentiallyDeadPHIs.insert(&PN);
7657       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7658         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7659     }
7660    
7661     // If this phi has a single use, and if that use just computes a value for
7662     // the next iteration of a loop, delete the phi.  This occurs with unused
7663     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
7664     // common case here is good because the only other things that catch this
7665     // are induction variable analysis (sometimes) and ADCE, which is only run
7666     // late.
7667     if (PHIUser->hasOneUse() &&
7668         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7669         PHIUser->use_back() == &PN) {
7670       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7671     }
7672   }
7673
7674   return 0;
7675 }
7676
7677 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7678                                    Instruction *InsertPoint,
7679                                    InstCombiner *IC) {
7680   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7681   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
7682   // We must cast correctly to the pointer type. Ensure that we
7683   // sign extend the integer value if it is smaller as this is
7684   // used for address computation.
7685   Instruction::CastOps opcode = 
7686      (VTySize < PtrSize ? Instruction::SExt :
7687       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7688   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
7689 }
7690
7691
7692 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7693   Value *PtrOp = GEP.getOperand(0);
7694   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
7695   // If so, eliminate the noop.
7696   if (GEP.getNumOperands() == 1)
7697     return ReplaceInstUsesWith(GEP, PtrOp);
7698
7699   if (isa<UndefValue>(GEP.getOperand(0)))
7700     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7701
7702   bool HasZeroPointerIndex = false;
7703   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7704     HasZeroPointerIndex = C->isNullValue();
7705
7706   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7707     return ReplaceInstUsesWith(GEP, PtrOp);
7708
7709   // Eliminate unneeded casts for indices.
7710   bool MadeChange = false;
7711   gep_type_iterator GTI = gep_type_begin(GEP);
7712   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7713     if (isa<SequentialType>(*GTI)) {
7714       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7715         if (CI->getOpcode() == Instruction::ZExt ||
7716             CI->getOpcode() == Instruction::SExt) {
7717           const Type *SrcTy = CI->getOperand(0)->getType();
7718           // We can eliminate a cast from i32 to i64 iff the target 
7719           // is a 32-bit pointer target.
7720           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7721             MadeChange = true;
7722             GEP.setOperand(i, CI->getOperand(0));
7723           }
7724         }
7725       }
7726       // If we are using a wider index than needed for this platform, shrink it
7727       // to what we need.  If the incoming value needs a cast instruction,
7728       // insert it.  This explicit cast can make subsequent optimizations more
7729       // obvious.
7730       Value *Op = GEP.getOperand(i);
7731       if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
7732         if (Constant *C = dyn_cast<Constant>(Op)) {
7733           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
7734           MadeChange = true;
7735         } else {
7736           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7737                                 GEP);
7738           GEP.setOperand(i, Op);
7739           MadeChange = true;
7740         }
7741     }
7742   if (MadeChange) return &GEP;
7743
7744   // Combine Indices - If the source pointer to this getelementptr instruction
7745   // is a getelementptr instruction, combine the indices of the two
7746   // getelementptr instructions into a single instruction.
7747   //
7748   SmallVector<Value*, 8> SrcGEPOperands;
7749   if (User *Src = dyn_castGetElementPtr(PtrOp))
7750     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
7751
7752   if (!SrcGEPOperands.empty()) {
7753     // Note that if our source is a gep chain itself that we wait for that
7754     // chain to be resolved before we perform this transformation.  This
7755     // avoids us creating a TON of code in some cases.
7756     //
7757     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7758         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7759       return 0;   // Wait until our source is folded to completion.
7760
7761     SmallVector<Value*, 8> Indices;
7762
7763     // Find out whether the last index in the source GEP is a sequential idx.
7764     bool EndsWithSequential = false;
7765     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7766            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7767       EndsWithSequential = !isa<StructType>(*I);
7768
7769     // Can we combine the two pointer arithmetics offsets?
7770     if (EndsWithSequential) {
7771       // Replace: gep (gep %P, long B), long A, ...
7772       // With:    T = long A+B; gep %P, T, ...
7773       //
7774       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7775       if (SO1 == Constant::getNullValue(SO1->getType())) {
7776         Sum = GO1;
7777       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7778         Sum = SO1;
7779       } else {
7780         // If they aren't the same type, convert both to an integer of the
7781         // target's pointer size.
7782         if (SO1->getType() != GO1->getType()) {
7783           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7784             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
7785           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7786             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
7787           } else {
7788             unsigned PS = TD->getPointerSize();
7789             if (TD->getTypeSize(SO1->getType()) == PS) {
7790               // Convert GO1 to SO1's type.
7791               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
7792
7793             } else if (TD->getTypeSize(GO1->getType()) == PS) {
7794               // Convert SO1 to GO1's type.
7795               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
7796             } else {
7797               const Type *PT = TD->getIntPtrType();
7798               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7799               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
7800             }
7801           }
7802         }
7803         if (isa<Constant>(SO1) && isa<Constant>(GO1))
7804           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7805         else {
7806           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7807           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7808         }
7809       }
7810
7811       // Recycle the GEP we already have if possible.
7812       if (SrcGEPOperands.size() == 2) {
7813         GEP.setOperand(0, SrcGEPOperands[0]);
7814         GEP.setOperand(1, Sum);
7815         return &GEP;
7816       } else {
7817         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7818                        SrcGEPOperands.end()-1);
7819         Indices.push_back(Sum);
7820         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7821       }
7822     } else if (isa<Constant>(*GEP.idx_begin()) &&
7823                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7824                SrcGEPOperands.size() != 1) {
7825       // Otherwise we can do the fold if the first index of the GEP is a zero
7826       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7827                      SrcGEPOperands.end());
7828       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7829     }
7830
7831     if (!Indices.empty())
7832       return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
7833                                    Indices.size(), GEP.getName());
7834
7835   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7836     // GEP of global variable.  If all of the indices for this GEP are
7837     // constants, we can promote this to a constexpr instead of an instruction.
7838
7839     // Scan for nonconstants...
7840     SmallVector<Constant*, 8> Indices;
7841     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7842     for (; I != E && isa<Constant>(*I); ++I)
7843       Indices.push_back(cast<Constant>(*I));
7844
7845     if (I == E) {  // If they are all constants...
7846       Constant *CE = ConstantExpr::getGetElementPtr(GV,
7847                                                     &Indices[0],Indices.size());
7848
7849       // Replace all uses of the GEP with the new constexpr...
7850       return ReplaceInstUsesWith(GEP, CE);
7851     }
7852   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
7853     if (!isa<PointerType>(X->getType())) {
7854       // Not interesting.  Source pointer must be a cast from pointer.
7855     } else if (HasZeroPointerIndex) {
7856       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7857       // into     : GEP [10 x ubyte]* X, long 0, ...
7858       //
7859       // This occurs when the program declares an array extern like "int X[];"
7860       //
7861       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7862       const PointerType *XTy = cast<PointerType>(X->getType());
7863       if (const ArrayType *XATy =
7864           dyn_cast<ArrayType>(XTy->getElementType()))
7865         if (const ArrayType *CATy =
7866             dyn_cast<ArrayType>(CPTy->getElementType()))
7867           if (CATy->getElementType() == XATy->getElementType()) {
7868             // At this point, we know that the cast source type is a pointer
7869             // to an array of the same type as the destination pointer
7870             // array.  Because the array type is never stepped over (there
7871             // is a leading zero) we can fold the cast into this GEP.
7872             GEP.setOperand(0, X);
7873             return &GEP;
7874           }
7875     } else if (GEP.getNumOperands() == 2) {
7876       // Transform things like:
7877       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7878       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7879       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7880       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7881       if (isa<ArrayType>(SrcElTy) &&
7882           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7883           TD->getTypeSize(ResElTy)) {
7884         Value *V = InsertNewInstBefore(
7885                new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7886                                      GEP.getOperand(1), GEP.getName()), GEP);
7887         // V and GEP are both pointer types --> BitCast
7888         return new BitCastInst(V, GEP.getType());
7889       }
7890       
7891       // Transform things like:
7892       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7893       //   (where tmp = 8*tmp2) into:
7894       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7895       
7896       if (isa<ArrayType>(SrcElTy) &&
7897           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
7898         uint64_t ArrayEltSize =
7899             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7900         
7901         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
7902         // allow either a mul, shift, or constant here.
7903         Value *NewIdx = 0;
7904         ConstantInt *Scale = 0;
7905         if (ArrayEltSize == 1) {
7906           NewIdx = GEP.getOperand(1);
7907           Scale = ConstantInt::get(NewIdx->getType(), 1);
7908         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7909           NewIdx = ConstantInt::get(CI->getType(), 1);
7910           Scale = CI;
7911         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7912           if (Inst->getOpcode() == Instruction::Shl &&
7913               isa<ConstantInt>(Inst->getOperand(1))) {
7914             unsigned ShAmt =
7915               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7916             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7917             NewIdx = Inst->getOperand(0);
7918           } else if (Inst->getOpcode() == Instruction::Mul &&
7919                      isa<ConstantInt>(Inst->getOperand(1))) {
7920             Scale = cast<ConstantInt>(Inst->getOperand(1));
7921             NewIdx = Inst->getOperand(0);
7922           }
7923         }
7924
7925         // If the index will be to exactly the right offset with the scale taken
7926         // out, perform the transformation.
7927         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7928           if (isa<ConstantInt>(Scale))
7929             Scale = ConstantInt::get(Scale->getType(),
7930                                       Scale->getZExtValue() / ArrayEltSize);
7931           if (Scale->getZExtValue() != 1) {
7932             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7933                                                        true /*SExt*/);
7934             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7935             NewIdx = InsertNewInstBefore(Sc, GEP);
7936           }
7937
7938           // Insert the new GEP instruction.
7939           Instruction *NewGEP =
7940             new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7941                                   NewIdx, GEP.getName());
7942           NewGEP = InsertNewInstBefore(NewGEP, GEP);
7943           // The NewGEP must be pointer typed, so must the old one -> BitCast
7944           return new BitCastInst(NewGEP, GEP.getType());
7945         }
7946       }
7947     }
7948   }
7949
7950   return 0;
7951 }
7952
7953 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7954   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7955   if (AI.isArrayAllocation())    // Check C != 1
7956     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7957       const Type *NewTy = 
7958         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7959       AllocationInst *New = 0;
7960
7961       // Create and insert the replacement instruction...
7962       if (isa<MallocInst>(AI))
7963         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7964       else {
7965         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7966         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7967       }
7968
7969       InsertNewInstBefore(New, AI);
7970
7971       // Scan to the end of the allocation instructions, to skip over a block of
7972       // allocas if possible...
7973       //
7974       BasicBlock::iterator It = New;
7975       while (isa<AllocationInst>(*It)) ++It;
7976
7977       // Now that I is pointing to the first non-allocation-inst in the block,
7978       // insert our getelementptr instruction...
7979       //
7980       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
7981       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7982                                        New->getName()+".sub", It);
7983
7984       // Now make everything use the getelementptr instead of the original
7985       // allocation.
7986       return ReplaceInstUsesWith(AI, V);
7987     } else if (isa<UndefValue>(AI.getArraySize())) {
7988       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7989     }
7990
7991   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7992   // Note that we only do this for alloca's, because malloc should allocate and
7993   // return a unique pointer, even for a zero byte allocation.
7994   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7995       TD->getTypeSize(AI.getAllocatedType()) == 0)
7996     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7997
7998   return 0;
7999 }
8000
8001 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8002   Value *Op = FI.getOperand(0);
8003
8004   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8005   if (CastInst *CI = dyn_cast<CastInst>(Op))
8006     if (isa<PointerType>(CI->getOperand(0)->getType())) {
8007       FI.setOperand(0, CI->getOperand(0));
8008       return &FI;
8009     }
8010
8011   // free undef -> unreachable.
8012   if (isa<UndefValue>(Op)) {
8013     // Insert a new store to null because we cannot modify the CFG here.
8014     new StoreInst(ConstantInt::getTrue(),
8015                   UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
8016     return EraseInstFromFunction(FI);
8017   }
8018
8019   // If we have 'free null' delete the instruction.  This can happen in stl code
8020   // when lots of inlining happens.
8021   if (isa<ConstantPointerNull>(Op))
8022     return EraseInstFromFunction(FI);
8023
8024   return 0;
8025 }
8026
8027
8028 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
8029 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8030   User *CI = cast<User>(LI.getOperand(0));
8031   Value *CastOp = CI->getOperand(0);
8032
8033   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8034   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8035     const Type *SrcPTy = SrcTy->getElementType();
8036
8037     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
8038          isa<VectorType>(DestPTy)) {
8039       // If the source is an array, the code below will not succeed.  Check to
8040       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8041       // constants.
8042       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8043         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8044           if (ASrcTy->getNumElements() != 0) {
8045             Value *Idxs[2];
8046             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8047             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8048             SrcTy = cast<PointerType>(CastOp->getType());
8049             SrcPTy = SrcTy->getElementType();
8050           }
8051
8052       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
8053             isa<VectorType>(SrcPTy)) &&
8054           // Do not allow turning this into a load of an integer, which is then
8055           // casted to a pointer, this pessimizes pointer analysis a lot.
8056           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8057           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8058                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8059
8060         // Okay, we are casting from one integer or pointer type to another of
8061         // the same size.  Instead of casting the pointer before the load, cast
8062         // the result of the loaded value.
8063         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8064                                                              CI->getName(),
8065                                                          LI.isVolatile()),LI);
8066         // Now cast the result of the load.
8067         return new BitCastInst(NewLoad, LI.getType());
8068       }
8069     }
8070   }
8071   return 0;
8072 }
8073
8074 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8075 /// from this value cannot trap.  If it is not obviously safe to load from the
8076 /// specified pointer, we do a quick local scan of the basic block containing
8077 /// ScanFrom, to determine if the address is already accessed.
8078 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8079   // If it is an alloca or global variable, it is always safe to load from.
8080   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8081
8082   // Otherwise, be a little bit agressive by scanning the local block where we
8083   // want to check to see if the pointer is already being loaded or stored
8084   // from/to.  If so, the previous load or store would have already trapped,
8085   // so there is no harm doing an extra load (also, CSE will later eliminate
8086   // the load entirely).
8087   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8088
8089   while (BBI != E) {
8090     --BBI;
8091
8092     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8093       if (LI->getOperand(0) == V) return true;
8094     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8095       if (SI->getOperand(1) == V) return true;
8096
8097   }
8098   return false;
8099 }
8100
8101 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8102   Value *Op = LI.getOperand(0);
8103
8104   // load (cast X) --> cast (load X) iff safe
8105   if (isa<CastInst>(Op))
8106     if (Instruction *Res = InstCombineLoadCast(*this, LI))
8107       return Res;
8108
8109   // None of the following transforms are legal for volatile loads.
8110   if (LI.isVolatile()) return 0;
8111   
8112   if (&LI.getParent()->front() != &LI) {
8113     BasicBlock::iterator BBI = &LI; --BBI;
8114     // If the instruction immediately before this is a store to the same
8115     // address, do a simple form of store->load forwarding.
8116     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8117       if (SI->getOperand(1) == LI.getOperand(0))
8118         return ReplaceInstUsesWith(LI, SI->getOperand(0));
8119     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8120       if (LIB->getOperand(0) == LI.getOperand(0))
8121         return ReplaceInstUsesWith(LI, LIB);
8122   }
8123
8124   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8125     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8126         isa<UndefValue>(GEPI->getOperand(0))) {
8127       // Insert a new store to null instruction before the load to indicate
8128       // that this code is not reachable.  We do this instead of inserting
8129       // an unreachable instruction directly because we cannot modify the
8130       // CFG.
8131       new StoreInst(UndefValue::get(LI.getType()),
8132                     Constant::getNullValue(Op->getType()), &LI);
8133       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8134     }
8135
8136   if (Constant *C = dyn_cast<Constant>(Op)) {
8137     // load null/undef -> undef
8138     if ((C->isNullValue() || isa<UndefValue>(C))) {
8139       // Insert a new store to null instruction before the load to indicate that
8140       // this code is not reachable.  We do this instead of inserting an
8141       // unreachable instruction directly because we cannot modify the CFG.
8142       new StoreInst(UndefValue::get(LI.getType()),
8143                     Constant::getNullValue(Op->getType()), &LI);
8144       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8145     }
8146
8147     // Instcombine load (constant global) into the value loaded.
8148     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8149       if (GV->isConstant() && !GV->isDeclaration())
8150         return ReplaceInstUsesWith(LI, GV->getInitializer());
8151
8152     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8153     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8154       if (CE->getOpcode() == Instruction::GetElementPtr) {
8155         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8156           if (GV->isConstant() && !GV->isDeclaration())
8157             if (Constant *V = 
8158                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8159               return ReplaceInstUsesWith(LI, V);
8160         if (CE->getOperand(0)->isNullValue()) {
8161           // Insert a new store to null instruction before the load to indicate
8162           // that this code is not reachable.  We do this instead of inserting
8163           // an unreachable instruction directly because we cannot modify the
8164           // CFG.
8165           new StoreInst(UndefValue::get(LI.getType()),
8166                         Constant::getNullValue(Op->getType()), &LI);
8167           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8168         }
8169
8170       } else if (CE->isCast()) {
8171         if (Instruction *Res = InstCombineLoadCast(*this, LI))
8172           return Res;
8173       }
8174   }
8175
8176   if (Op->hasOneUse()) {
8177     // Change select and PHI nodes to select values instead of addresses: this
8178     // helps alias analysis out a lot, allows many others simplifications, and
8179     // exposes redundancy in the code.
8180     //
8181     // Note that we cannot do the transformation unless we know that the
8182     // introduced loads cannot trap!  Something like this is valid as long as
8183     // the condition is always false: load (select bool %C, int* null, int* %G),
8184     // but it would not be valid if we transformed it to load from null
8185     // unconditionally.
8186     //
8187     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8188       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
8189       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8190           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8191         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8192                                      SI->getOperand(1)->getName()+".val"), LI);
8193         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8194                                      SI->getOperand(2)->getName()+".val"), LI);
8195         return new SelectInst(SI->getCondition(), V1, V2);
8196       }
8197
8198       // load (select (cond, null, P)) -> load P
8199       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8200         if (C->isNullValue()) {
8201           LI.setOperand(0, SI->getOperand(2));
8202           return &LI;
8203         }
8204
8205       // load (select (cond, P, null)) -> load P
8206       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8207         if (C->isNullValue()) {
8208           LI.setOperand(0, SI->getOperand(1));
8209           return &LI;
8210         }
8211     }
8212   }
8213   return 0;
8214 }
8215
8216 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
8217 /// when possible.
8218 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8219   User *CI = cast<User>(SI.getOperand(1));
8220   Value *CastOp = CI->getOperand(0);
8221
8222   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8223   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8224     const Type *SrcPTy = SrcTy->getElementType();
8225
8226     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8227       // If the source is an array, the code below will not succeed.  Check to
8228       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8229       // constants.
8230       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8231         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8232           if (ASrcTy->getNumElements() != 0) {
8233             Value* Idxs[2];
8234             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8235             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8236             SrcTy = cast<PointerType>(CastOp->getType());
8237             SrcPTy = SrcTy->getElementType();
8238           }
8239
8240       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8241           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8242                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8243
8244         // Okay, we are casting from one integer or pointer type to another of
8245         // the same size.  Instead of casting the pointer before 
8246         // the store, cast the value to be stored.
8247         Value *NewCast;
8248         Value *SIOp0 = SI.getOperand(0);
8249         Instruction::CastOps opcode = Instruction::BitCast;
8250         const Type* CastSrcTy = SIOp0->getType();
8251         const Type* CastDstTy = SrcPTy;
8252         if (isa<PointerType>(CastDstTy)) {
8253           if (CastSrcTy->isInteger())
8254             opcode = Instruction::IntToPtr;
8255         } else if (isa<IntegerType>(CastDstTy)) {
8256           if (isa<PointerType>(SIOp0->getType()))
8257             opcode = Instruction::PtrToInt;
8258         }
8259         if (Constant *C = dyn_cast<Constant>(SIOp0))
8260           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
8261         else
8262           NewCast = IC.InsertNewInstBefore(
8263             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
8264             SI);
8265         return new StoreInst(NewCast, CastOp);
8266       }
8267     }
8268   }
8269   return 0;
8270 }
8271
8272 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8273   Value *Val = SI.getOperand(0);
8274   Value *Ptr = SI.getOperand(1);
8275
8276   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
8277     EraseInstFromFunction(SI);
8278     ++NumCombined;
8279     return 0;
8280   }
8281   
8282   // If the RHS is an alloca with a single use, zapify the store, making the
8283   // alloca dead.
8284   if (Ptr->hasOneUse()) {
8285     if (isa<AllocaInst>(Ptr)) {
8286       EraseInstFromFunction(SI);
8287       ++NumCombined;
8288       return 0;
8289     }
8290     
8291     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8292       if (isa<AllocaInst>(GEP->getOperand(0)) &&
8293           GEP->getOperand(0)->hasOneUse()) {
8294         EraseInstFromFunction(SI);
8295         ++NumCombined;
8296         return 0;
8297       }
8298   }
8299
8300   // Do really simple DSE, to catch cases where there are several consequtive
8301   // stores to the same location, separated by a few arithmetic operations. This
8302   // situation often occurs with bitfield accesses.
8303   BasicBlock::iterator BBI = &SI;
8304   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8305        --ScanInsts) {
8306     --BBI;
8307     
8308     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8309       // Prev store isn't volatile, and stores to the same location?
8310       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8311         ++NumDeadStore;
8312         ++BBI;
8313         EraseInstFromFunction(*PrevSI);
8314         continue;
8315       }
8316       break;
8317     }
8318     
8319     // If this is a load, we have to stop.  However, if the loaded value is from
8320     // the pointer we're loading and is producing the pointer we're storing,
8321     // then *this* store is dead (X = load P; store X -> P).
8322     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8323       if (LI == Val && LI->getOperand(0) == Ptr) {
8324         EraseInstFromFunction(SI);
8325         ++NumCombined;
8326         return 0;
8327       }
8328       // Otherwise, this is a load from some other location.  Stores before it
8329       // may not be dead.
8330       break;
8331     }
8332     
8333     // Don't skip over loads or things that can modify memory.
8334     if (BBI->mayWriteToMemory())
8335       break;
8336   }
8337   
8338   
8339   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
8340
8341   // store X, null    -> turns into 'unreachable' in SimplifyCFG
8342   if (isa<ConstantPointerNull>(Ptr)) {
8343     if (!isa<UndefValue>(Val)) {
8344       SI.setOperand(0, UndefValue::get(Val->getType()));
8345       if (Instruction *U = dyn_cast<Instruction>(Val))
8346         WorkList.push_back(U);  // Dropped a use.
8347       ++NumCombined;
8348     }
8349     return 0;  // Do not modify these!
8350   }
8351
8352   // store undef, Ptr -> noop
8353   if (isa<UndefValue>(Val)) {
8354     EraseInstFromFunction(SI);
8355     ++NumCombined;
8356     return 0;
8357   }
8358
8359   // If the pointer destination is a cast, see if we can fold the cast into the
8360   // source instead.
8361   if (isa<CastInst>(Ptr))
8362     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8363       return Res;
8364   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8365     if (CE->isCast())
8366       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8367         return Res;
8368
8369   
8370   // If this store is the last instruction in the basic block, and if the block
8371   // ends with an unconditional branch, try to move it to the successor block.
8372   BBI = &SI; ++BBI;
8373   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8374     if (BI->isUnconditional()) {
8375       // Check to see if the successor block has exactly two incoming edges.  If
8376       // so, see if the other predecessor contains a store to the same location.
8377       // if so, insert a PHI node (if needed) and move the stores down.
8378       BasicBlock *Dest = BI->getSuccessor(0);
8379
8380       pred_iterator PI = pred_begin(Dest);
8381       BasicBlock *Other = 0;
8382       if (*PI != BI->getParent())
8383         Other = *PI;
8384       ++PI;
8385       if (PI != pred_end(Dest)) {
8386         if (*PI != BI->getParent())
8387           if (Other)
8388             Other = 0;
8389           else
8390             Other = *PI;
8391         if (++PI != pred_end(Dest))
8392           Other = 0;
8393       }
8394       if (Other) {  // If only one other pred...
8395         BBI = Other->getTerminator();
8396         // Make sure this other block ends in an unconditional branch and that
8397         // there is an instruction before the branch.
8398         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8399             BBI != Other->begin()) {
8400           --BBI;
8401           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8402           
8403           // If this instruction is a store to the same location.
8404           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8405             // Okay, we know we can perform this transformation.  Insert a PHI
8406             // node now if we need it.
8407             Value *MergedVal = OtherStore->getOperand(0);
8408             if (MergedVal != SI.getOperand(0)) {
8409               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8410               PN->reserveOperandSpace(2);
8411               PN->addIncoming(SI.getOperand(0), SI.getParent());
8412               PN->addIncoming(OtherStore->getOperand(0), Other);
8413               MergedVal = InsertNewInstBefore(PN, Dest->front());
8414             }
8415             
8416             // Advance to a place where it is safe to insert the new store and
8417             // insert it.
8418             BBI = Dest->begin();
8419             while (isa<PHINode>(BBI)) ++BBI;
8420             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8421                                               OtherStore->isVolatile()), *BBI);
8422
8423             // Nuke the old stores.
8424             EraseInstFromFunction(SI);
8425             EraseInstFromFunction(*OtherStore);
8426             ++NumCombined;
8427             return 0;
8428           }
8429         }
8430       }
8431     }
8432   
8433   return 0;
8434 }
8435
8436
8437 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8438   // Change br (not X), label True, label False to: br X, label False, True
8439   Value *X = 0;
8440   BasicBlock *TrueDest;
8441   BasicBlock *FalseDest;
8442   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8443       !isa<Constant>(X)) {
8444     // Swap Destinations and condition...
8445     BI.setCondition(X);
8446     BI.setSuccessor(0, FalseDest);
8447     BI.setSuccessor(1, TrueDest);
8448     return &BI;
8449   }
8450
8451   // Cannonicalize fcmp_one -> fcmp_oeq
8452   FCmpInst::Predicate FPred; Value *Y;
8453   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
8454                              TrueDest, FalseDest)))
8455     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8456          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8457       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
8458       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8459       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8460       NewSCC->takeName(I);
8461       // Swap Destinations and condition...
8462       BI.setCondition(NewSCC);
8463       BI.setSuccessor(0, FalseDest);
8464       BI.setSuccessor(1, TrueDest);
8465       removeFromWorkList(I);
8466       I->eraseFromParent();
8467       WorkList.push_back(NewSCC);
8468       return &BI;
8469     }
8470
8471   // Cannonicalize icmp_ne -> icmp_eq
8472   ICmpInst::Predicate IPred;
8473   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8474                       TrueDest, FalseDest)))
8475     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
8476          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8477          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8478       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8479       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8480       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8481       NewSCC->takeName(I);
8482       // Swap Destinations and condition...
8483       BI.setCondition(NewSCC);
8484       BI.setSuccessor(0, FalseDest);
8485       BI.setSuccessor(1, TrueDest);
8486       removeFromWorkList(I);
8487       I->eraseFromParent();;
8488       WorkList.push_back(NewSCC);
8489       return &BI;
8490     }
8491
8492   return 0;
8493 }
8494
8495 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8496   Value *Cond = SI.getCondition();
8497   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8498     if (I->getOpcode() == Instruction::Add)
8499       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8500         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8501         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8502           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8503                                                 AddRHS));
8504         SI.setOperand(0, I->getOperand(0));
8505         WorkList.push_back(I);
8506         return &SI;
8507       }
8508   }
8509   return 0;
8510 }
8511
8512 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8513 /// is to leave as a vector operation.
8514 static bool CheapToScalarize(Value *V, bool isConstant) {
8515   if (isa<ConstantAggregateZero>(V)) 
8516     return true;
8517   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
8518     if (isConstant) return true;
8519     // If all elts are the same, we can extract.
8520     Constant *Op0 = C->getOperand(0);
8521     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8522       if (C->getOperand(i) != Op0)
8523         return false;
8524     return true;
8525   }
8526   Instruction *I = dyn_cast<Instruction>(V);
8527   if (!I) return false;
8528   
8529   // Insert element gets simplified to the inserted element or is deleted if
8530   // this is constant idx extract element and its a constant idx insertelt.
8531   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8532       isa<ConstantInt>(I->getOperand(2)))
8533     return true;
8534   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8535     return true;
8536   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8537     if (BO->hasOneUse() &&
8538         (CheapToScalarize(BO->getOperand(0), isConstant) ||
8539          CheapToScalarize(BO->getOperand(1), isConstant)))
8540       return true;
8541   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8542     if (CI->hasOneUse() &&
8543         (CheapToScalarize(CI->getOperand(0), isConstant) ||
8544          CheapToScalarize(CI->getOperand(1), isConstant)))
8545       return true;
8546   
8547   return false;
8548 }
8549
8550 /// Read and decode a shufflevector mask.
8551 ///
8552 /// It turns undef elements into values that are larger than the number of
8553 /// elements in the input.
8554 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8555   unsigned NElts = SVI->getType()->getNumElements();
8556   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8557     return std::vector<unsigned>(NElts, 0);
8558   if (isa<UndefValue>(SVI->getOperand(2)))
8559     return std::vector<unsigned>(NElts, 2*NElts);
8560
8561   std::vector<unsigned> Result;
8562   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
8563   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8564     if (isa<UndefValue>(CP->getOperand(i)))
8565       Result.push_back(NElts*2);  // undef -> 8
8566     else
8567       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8568   return Result;
8569 }
8570
8571 /// FindScalarElement - Given a vector and an element number, see if the scalar
8572 /// value is already around as a register, for example if it were inserted then
8573 /// extracted from the vector.
8574 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8575   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8576   const VectorType *PTy = cast<VectorType>(V->getType());
8577   unsigned Width = PTy->getNumElements();
8578   if (EltNo >= Width)  // Out of range access.
8579     return UndefValue::get(PTy->getElementType());
8580   
8581   if (isa<UndefValue>(V))
8582     return UndefValue::get(PTy->getElementType());
8583   else if (isa<ConstantAggregateZero>(V))
8584     return Constant::getNullValue(PTy->getElementType());
8585   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
8586     return CP->getOperand(EltNo);
8587   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8588     // If this is an insert to a variable element, we don't know what it is.
8589     if (!isa<ConstantInt>(III->getOperand(2))) 
8590       return 0;
8591     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8592     
8593     // If this is an insert to the element we are looking for, return the
8594     // inserted value.
8595     if (EltNo == IIElt) 
8596       return III->getOperand(1);
8597     
8598     // Otherwise, the insertelement doesn't modify the value, recurse on its
8599     // vector input.
8600     return FindScalarElement(III->getOperand(0), EltNo);
8601   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8602     unsigned InEl = getShuffleMask(SVI)[EltNo];
8603     if (InEl < Width)
8604       return FindScalarElement(SVI->getOperand(0), InEl);
8605     else if (InEl < Width*2)
8606       return FindScalarElement(SVI->getOperand(1), InEl - Width);
8607     else
8608       return UndefValue::get(PTy->getElementType());
8609   }
8610   
8611   // Otherwise, we don't know.
8612   return 0;
8613 }
8614
8615 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8616
8617   // If packed val is undef, replace extract with scalar undef.
8618   if (isa<UndefValue>(EI.getOperand(0)))
8619     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8620
8621   // If packed val is constant 0, replace extract with scalar 0.
8622   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8623     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8624   
8625   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
8626     // If packed val is constant with uniform operands, replace EI
8627     // with that operand
8628     Constant *op0 = C->getOperand(0);
8629     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8630       if (C->getOperand(i) != op0) {
8631         op0 = 0; 
8632         break;
8633       }
8634     if (op0)
8635       return ReplaceInstUsesWith(EI, op0);
8636   }
8637   
8638   // If extracting a specified index from the vector, see if we can recursively
8639   // find a previously computed scalar that was inserted into the vector.
8640   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8641     // This instruction only demands the single element from the input vector.
8642     // If the input vector has a single use, simplify it based on this use
8643     // property.
8644     uint64_t IndexVal = IdxC->getZExtValue();
8645     if (EI.getOperand(0)->hasOneUse()) {
8646       uint64_t UndefElts;
8647       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8648                                                 1 << IndexVal,
8649                                                 UndefElts)) {
8650         EI.setOperand(0, V);
8651         return &EI;
8652       }
8653     }
8654     
8655     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8656       return ReplaceInstUsesWith(EI, Elt);
8657   }
8658   
8659   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8660     if (I->hasOneUse()) {
8661       // Push extractelement into predecessor operation if legal and
8662       // profitable to do so
8663       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8664         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8665         if (CheapToScalarize(BO, isConstantElt)) {
8666           ExtractElementInst *newEI0 = 
8667             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8668                                    EI.getName()+".lhs");
8669           ExtractElementInst *newEI1 =
8670             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8671                                    EI.getName()+".rhs");
8672           InsertNewInstBefore(newEI0, EI);
8673           InsertNewInstBefore(newEI1, EI);
8674           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8675         }
8676       } else if (isa<LoadInst>(I)) {
8677         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
8678                                       PointerType::get(EI.getType()), EI);
8679         GetElementPtrInst *GEP = 
8680           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8681         InsertNewInstBefore(GEP, EI);
8682         return new LoadInst(GEP);
8683       }
8684     }
8685     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8686       // Extracting the inserted element?
8687       if (IE->getOperand(2) == EI.getOperand(1))
8688         return ReplaceInstUsesWith(EI, IE->getOperand(1));
8689       // If the inserted and extracted elements are constants, they must not
8690       // be the same value, extract from the pre-inserted value instead.
8691       if (isa<Constant>(IE->getOperand(2)) &&
8692           isa<Constant>(EI.getOperand(1))) {
8693         AddUsesToWorkList(EI);
8694         EI.setOperand(0, IE->getOperand(0));
8695         return &EI;
8696       }
8697     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8698       // If this is extracting an element from a shufflevector, figure out where
8699       // it came from and extract from the appropriate input element instead.
8700       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8701         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8702         Value *Src;
8703         if (SrcIdx < SVI->getType()->getNumElements())
8704           Src = SVI->getOperand(0);
8705         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8706           SrcIdx -= SVI->getType()->getNumElements();
8707           Src = SVI->getOperand(1);
8708         } else {
8709           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8710         }
8711         return new ExtractElementInst(Src, SrcIdx);
8712       }
8713     }
8714   }
8715   return 0;
8716 }
8717
8718 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8719 /// elements from either LHS or RHS, return the shuffle mask and true. 
8720 /// Otherwise, return false.
8721 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8722                                          std::vector<Constant*> &Mask) {
8723   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8724          "Invalid CollectSingleShuffleElements");
8725   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
8726
8727   if (isa<UndefValue>(V)) {
8728     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8729     return true;
8730   } else if (V == LHS) {
8731     for (unsigned i = 0; i != NumElts; ++i)
8732       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8733     return true;
8734   } else if (V == RHS) {
8735     for (unsigned i = 0; i != NumElts; ++i)
8736       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
8737     return true;
8738   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8739     // If this is an insert of an extract from some other vector, include it.
8740     Value *VecOp    = IEI->getOperand(0);
8741     Value *ScalarOp = IEI->getOperand(1);
8742     Value *IdxOp    = IEI->getOperand(2);
8743     
8744     if (!isa<ConstantInt>(IdxOp))
8745       return false;
8746     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8747     
8748     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
8749       // Okay, we can handle this if the vector we are insertinting into is
8750       // transitively ok.
8751       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8752         // If so, update the mask to reflect the inserted undef.
8753         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
8754         return true;
8755       }      
8756     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8757       if (isa<ConstantInt>(EI->getOperand(1)) &&
8758           EI->getOperand(0)->getType() == V->getType()) {
8759         unsigned ExtractedIdx =
8760           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8761         
8762         // This must be extracting from either LHS or RHS.
8763         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8764           // Okay, we can handle this if the vector we are insertinting into is
8765           // transitively ok.
8766           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8767             // If so, update the mask to reflect the inserted value.
8768             if (EI->getOperand(0) == LHS) {
8769               Mask[InsertedIdx & (NumElts-1)] = 
8770                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8771             } else {
8772               assert(EI->getOperand(0) == RHS);
8773               Mask[InsertedIdx & (NumElts-1)] = 
8774                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
8775               
8776             }
8777             return true;
8778           }
8779         }
8780       }
8781     }
8782   }
8783   // TODO: Handle shufflevector here!
8784   
8785   return false;
8786 }
8787
8788 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8789 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
8790 /// that computes V and the LHS value of the shuffle.
8791 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8792                                      Value *&RHS) {
8793   assert(isa<VectorType>(V->getType()) && 
8794          (RHS == 0 || V->getType() == RHS->getType()) &&
8795          "Invalid shuffle!");
8796   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
8797
8798   if (isa<UndefValue>(V)) {
8799     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8800     return V;
8801   } else if (isa<ConstantAggregateZero>(V)) {
8802     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
8803     return V;
8804   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8805     // If this is an insert of an extract from some other vector, include it.
8806     Value *VecOp    = IEI->getOperand(0);
8807     Value *ScalarOp = IEI->getOperand(1);
8808     Value *IdxOp    = IEI->getOperand(2);
8809     
8810     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8811       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8812           EI->getOperand(0)->getType() == V->getType()) {
8813         unsigned ExtractedIdx =
8814           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8815         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8816         
8817         // Either the extracted from or inserted into vector must be RHSVec,
8818         // otherwise we'd end up with a shuffle of three inputs.
8819         if (EI->getOperand(0) == RHS || RHS == 0) {
8820           RHS = EI->getOperand(0);
8821           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8822           Mask[InsertedIdx & (NumElts-1)] = 
8823             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
8824           return V;
8825         }
8826         
8827         if (VecOp == RHS) {
8828           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8829           // Everything but the extracted element is replaced with the RHS.
8830           for (unsigned i = 0; i != NumElts; ++i) {
8831             if (i != InsertedIdx)
8832               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
8833           }
8834           return V;
8835         }
8836         
8837         // If this insertelement is a chain that comes from exactly these two
8838         // vectors, return the vector and the effective shuffle.
8839         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8840           return EI->getOperand(0);
8841         
8842       }
8843     }
8844   }
8845   // TODO: Handle shufflevector here!
8846   
8847   // Otherwise, can't do anything fancy.  Return an identity vector.
8848   for (unsigned i = 0; i != NumElts; ++i)
8849     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8850   return V;
8851 }
8852
8853 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8854   Value *VecOp    = IE.getOperand(0);
8855   Value *ScalarOp = IE.getOperand(1);
8856   Value *IdxOp    = IE.getOperand(2);
8857   
8858   // If the inserted element was extracted from some other vector, and if the 
8859   // indexes are constant, try to turn this into a shufflevector operation.
8860   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8861     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8862         EI->getOperand(0)->getType() == IE.getType()) {
8863       unsigned NumVectorElts = IE.getType()->getNumElements();
8864       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8865       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8866       
8867       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8868         return ReplaceInstUsesWith(IE, VecOp);
8869       
8870       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
8871         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8872       
8873       // If we are extracting a value from a vector, then inserting it right
8874       // back into the same place, just use the input vector.
8875       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8876         return ReplaceInstUsesWith(IE, VecOp);      
8877       
8878       // We could theoretically do this for ANY input.  However, doing so could
8879       // turn chains of insertelement instructions into a chain of shufflevector
8880       // instructions, and right now we do not merge shufflevectors.  As such,
8881       // only do this in a situation where it is clear that there is benefit.
8882       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8883         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
8884         // the values of VecOp, except then one read from EIOp0.
8885         // Build a new shuffle mask.
8886         std::vector<Constant*> Mask;
8887         if (isa<UndefValue>(VecOp))
8888           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
8889         else {
8890           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8891           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
8892                                                        NumVectorElts));
8893         } 
8894         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8895         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8896                                      ConstantVector::get(Mask));
8897       }
8898       
8899       // If this insertelement isn't used by some other insertelement, turn it
8900       // (and any insertelements it points to), into one big shuffle.
8901       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8902         std::vector<Constant*> Mask;
8903         Value *RHS = 0;
8904         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8905         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8906         // We now have a shuffle of LHS, RHS, Mask.
8907         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
8908       }
8909     }
8910   }
8911
8912   return 0;
8913 }
8914
8915
8916 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8917   Value *LHS = SVI.getOperand(0);
8918   Value *RHS = SVI.getOperand(1);
8919   std::vector<unsigned> Mask = getShuffleMask(&SVI);
8920
8921   bool MadeChange = false;
8922   
8923   // Undefined shuffle mask -> undefined value.
8924   if (isa<UndefValue>(SVI.getOperand(2)))
8925     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8926   
8927   // If we have shuffle(x, undef, mask) and any elements of mask refer to
8928   // the undef, change them to undefs.
8929   if (isa<UndefValue>(SVI.getOperand(1))) {
8930     // Scan to see if there are any references to the RHS.  If so, replace them
8931     // with undef element refs and set MadeChange to true.
8932     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8933       if (Mask[i] >= e && Mask[i] != 2*e) {
8934         Mask[i] = 2*e;
8935         MadeChange = true;
8936       }
8937     }
8938     
8939     if (MadeChange) {
8940       // Remap any references to RHS to use LHS.
8941       std::vector<Constant*> Elts;
8942       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8943         if (Mask[i] == 2*e)
8944           Elts.push_back(UndefValue::get(Type::Int32Ty));
8945         else
8946           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8947       }
8948       SVI.setOperand(2, ConstantVector::get(Elts));
8949     }
8950   }
8951   
8952   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
8953   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8954   if (LHS == RHS || isa<UndefValue>(LHS)) {
8955     if (isa<UndefValue>(LHS) && LHS == RHS) {
8956       // shuffle(undef,undef,mask) -> undef.
8957       return ReplaceInstUsesWith(SVI, LHS);
8958     }
8959     
8960     // Remap any references to RHS to use LHS.
8961     std::vector<Constant*> Elts;
8962     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8963       if (Mask[i] >= 2*e)
8964         Elts.push_back(UndefValue::get(Type::Int32Ty));
8965       else {
8966         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8967             (Mask[i] <  e && isa<UndefValue>(LHS)))
8968           Mask[i] = 2*e;     // Turn into undef.
8969         else
8970           Mask[i] &= (e-1);  // Force to LHS.
8971         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8972       }
8973     }
8974     SVI.setOperand(0, SVI.getOperand(1));
8975     SVI.setOperand(1, UndefValue::get(RHS->getType()));
8976     SVI.setOperand(2, ConstantVector::get(Elts));
8977     LHS = SVI.getOperand(0);
8978     RHS = SVI.getOperand(1);
8979     MadeChange = true;
8980   }
8981   
8982   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8983   bool isLHSID = true, isRHSID = true;
8984     
8985   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8986     if (Mask[i] >= e*2) continue;  // Ignore undef values.
8987     // Is this an identity shuffle of the LHS value?
8988     isLHSID &= (Mask[i] == i);
8989       
8990     // Is this an identity shuffle of the RHS value?
8991     isRHSID &= (Mask[i]-e == i);
8992   }
8993
8994   // Eliminate identity shuffles.
8995   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8996   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8997   
8998   // If the LHS is a shufflevector itself, see if we can combine it with this
8999   // one without producing an unusual shuffle.  Here we are really conservative:
9000   // we are absolutely afraid of producing a shuffle mask not in the input
9001   // program, because the code gen may not be smart enough to turn a merged
9002   // shuffle into two specific shuffles: it may produce worse code.  As such,
9003   // we only merge two shuffles if the result is one of the two input shuffle
9004   // masks.  In this case, merging the shuffles just removes one instruction,
9005   // which we know is safe.  This is good for things like turning:
9006   // (splat(splat)) -> splat.
9007   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9008     if (isa<UndefValue>(RHS)) {
9009       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9010
9011       std::vector<unsigned> NewMask;
9012       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9013         if (Mask[i] >= 2*e)
9014           NewMask.push_back(2*e);
9015         else
9016           NewMask.push_back(LHSMask[Mask[i]]);
9017       
9018       // If the result mask is equal to the src shuffle or this shuffle mask, do
9019       // the replacement.
9020       if (NewMask == LHSMask || NewMask == Mask) {
9021         std::vector<Constant*> Elts;
9022         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9023           if (NewMask[i] >= e*2) {
9024             Elts.push_back(UndefValue::get(Type::Int32Ty));
9025           } else {
9026             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
9027           }
9028         }
9029         return new ShuffleVectorInst(LHSSVI->getOperand(0),
9030                                      LHSSVI->getOperand(1),
9031                                      ConstantVector::get(Elts));
9032       }
9033     }
9034   }
9035
9036   return MadeChange ? &SVI : 0;
9037 }
9038
9039
9040
9041 void InstCombiner::removeFromWorkList(Instruction *I) {
9042   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
9043                  WorkList.end());
9044 }
9045
9046
9047 /// TryToSinkInstruction - Try to move the specified instruction from its
9048 /// current block into the beginning of DestBlock, which can only happen if it's
9049 /// safe to move the instruction past all of the instructions between it and the
9050 /// end of its block.
9051 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9052   assert(I->hasOneUse() && "Invariants didn't hold!");
9053
9054   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9055   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
9056
9057   // Do not sink alloca instructions out of the entry block.
9058   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9059     return false;
9060
9061   // We can only sink load instructions if there is nothing between the load and
9062   // the end of block that could change the value.
9063   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9064     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9065          Scan != E; ++Scan)
9066       if (Scan->mayWriteToMemory())
9067         return false;
9068   }
9069
9070   BasicBlock::iterator InsertPos = DestBlock->begin();
9071   while (isa<PHINode>(InsertPos)) ++InsertPos;
9072
9073   I->moveBefore(InsertPos);
9074   ++NumSunkInst;
9075   return true;
9076 }
9077
9078
9079 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9080 /// all reachable code to the worklist.
9081 ///
9082 /// This has a couple of tricks to make the code faster and more powerful.  In
9083 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9084 /// them to the worklist (this significantly speeds up instcombine on code where
9085 /// many instructions are dead or constant).  Additionally, if we find a branch
9086 /// whose condition is a known constant, we only visit the reachable successors.
9087 ///
9088 static void AddReachableCodeToWorklist(BasicBlock *BB, 
9089                                        SmallPtrSet<BasicBlock*, 64> &Visited,
9090                                        std::vector<Instruction*> &WorkList,
9091                                        const TargetData *TD) {
9092   // We have now visited this block!  If we've already been here, bail out.
9093   if (!Visited.insert(BB)) return;
9094     
9095   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9096     Instruction *Inst = BBI++;
9097     
9098     // DCE instruction if trivially dead.
9099     if (isInstructionTriviallyDead(Inst)) {
9100       ++NumDeadInst;
9101       DOUT << "IC: DCE: " << *Inst;
9102       Inst->eraseFromParent();
9103       continue;
9104     }
9105     
9106     // ConstantProp instruction if trivially constant.
9107     if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9108       DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9109       Inst->replaceAllUsesWith(C);
9110       ++NumConstProp;
9111       Inst->eraseFromParent();
9112       continue;
9113     }
9114     
9115     WorkList.push_back(Inst);
9116   }
9117
9118   // Recursively visit successors.  If this is a branch or switch on a constant,
9119   // only visit the reachable successor.
9120   TerminatorInst *TI = BB->getTerminator();
9121   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9122     if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9123       bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9124       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9125                                  TD);
9126       return;
9127     }
9128   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9129     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9130       // See if this is an explicit destination.
9131       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9132         if (SI->getCaseValue(i) == Cond) {
9133           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
9134           return;
9135         }
9136       
9137       // Otherwise it is the default destination.
9138       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
9139       return;
9140     }
9141   }
9142   
9143   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9144     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
9145 }
9146
9147 bool InstCombiner::runOnFunction(Function &F) {
9148   bool Changed = false;
9149   TD = &getAnalysis<TargetData>();
9150
9151   {
9152     // Do a depth-first traversal of the function, populate the worklist with
9153     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
9154     // track of which blocks we visit.
9155     SmallPtrSet<BasicBlock*, 64> Visited;
9156     AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
9157
9158     // Do a quick scan over the function.  If we find any blocks that are
9159     // unreachable, remove any instructions inside of them.  This prevents
9160     // the instcombine code from having to deal with some bad special cases.
9161     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9162       if (!Visited.count(BB)) {
9163         Instruction *Term = BB->getTerminator();
9164         while (Term != BB->begin()) {   // Remove instrs bottom-up
9165           BasicBlock::iterator I = Term; --I;
9166
9167           DOUT << "IC: DCE: " << *I;
9168           ++NumDeadInst;
9169
9170           if (!I->use_empty())
9171             I->replaceAllUsesWith(UndefValue::get(I->getType()));
9172           I->eraseFromParent();
9173         }
9174       }
9175   }
9176
9177   while (!WorkList.empty()) {
9178     Instruction *I = WorkList.back();  // Get an instruction from the worklist
9179     WorkList.pop_back();
9180
9181     // Check to see if we can DCE the instruction.
9182     if (isInstructionTriviallyDead(I)) {
9183       // Add operands to the worklist.
9184       if (I->getNumOperands() < 4)
9185         AddUsesToWorkList(*I);
9186       ++NumDeadInst;
9187
9188       DOUT << "IC: DCE: " << *I;
9189
9190       I->eraseFromParent();
9191       removeFromWorkList(I);
9192       continue;
9193     }
9194
9195     // Instruction isn't dead, see if we can constant propagate it.
9196     if (Constant *C = ConstantFoldInstruction(I, TD)) {
9197       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9198
9199       // Add operands to the worklist.
9200       AddUsesToWorkList(*I);
9201       ReplaceInstUsesWith(*I, C);
9202
9203       ++NumConstProp;
9204       I->eraseFromParent();
9205       removeFromWorkList(I);
9206       continue;
9207     }
9208
9209     // See if we can trivially sink this instruction to a successor basic block.
9210     if (I->hasOneUse()) {
9211       BasicBlock *BB = I->getParent();
9212       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9213       if (UserParent != BB) {
9214         bool UserIsSuccessor = false;
9215         // See if the user is one of our successors.
9216         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9217           if (*SI == UserParent) {
9218             UserIsSuccessor = true;
9219             break;
9220           }
9221
9222         // If the user is one of our immediate successors, and if that successor
9223         // only has us as a predecessors (we'd have to split the critical edge
9224         // otherwise), we can keep going.
9225         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9226             next(pred_begin(UserParent)) == pred_end(UserParent))
9227           // Okay, the CFG is simple enough, try to sink this instruction.
9228           Changed |= TryToSinkInstruction(I, UserParent);
9229       }
9230     }
9231
9232     // Now that we have an instruction, try combining it to simplify it...
9233     if (Instruction *Result = visit(*I)) {
9234       ++NumCombined;
9235       // Should we replace the old instruction with a new one?
9236       if (Result != I) {
9237         DOUT << "IC: Old = " << *I
9238              << "    New = " << *Result;
9239
9240         // Everything uses the new instruction now.
9241         I->replaceAllUsesWith(Result);
9242
9243         // Push the new instruction and any users onto the worklist.
9244         WorkList.push_back(Result);
9245         AddUsersToWorkList(*Result);
9246
9247         // Move the name to the new instruction first.
9248         Result->takeName(I);
9249
9250         // Insert the new instruction into the basic block...
9251         BasicBlock *InstParent = I->getParent();
9252         BasicBlock::iterator InsertPos = I;
9253
9254         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
9255           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9256             ++InsertPos;
9257
9258         InstParent->getInstList().insert(InsertPos, Result);
9259
9260         // Make sure that we reprocess all operands now that we reduced their
9261         // use counts.
9262         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9263           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9264             WorkList.push_back(OpI);
9265
9266         // Instructions can end up on the worklist more than once.  Make sure
9267         // we do not process an instruction that has been deleted.
9268         removeFromWorkList(I);
9269
9270         // Erase the old instruction.
9271         InstParent->getInstList().erase(I);
9272       } else {
9273         DOUT << "IC: MOD = " << *I;
9274
9275         // If the instruction was modified, it's possible that it is now dead.
9276         // if so, remove it.
9277         if (isInstructionTriviallyDead(I)) {
9278           // Make sure we process all operands now that we are reducing their
9279           // use counts.
9280           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9281             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9282               WorkList.push_back(OpI);
9283
9284           // Instructions may end up in the worklist more than once.  Erase all
9285           // occurrences of this instruction.
9286           removeFromWorkList(I);
9287           I->eraseFromParent();
9288         } else {
9289           WorkList.push_back(Result);
9290           AddUsersToWorkList(*Result);
9291         }
9292       }
9293       Changed = true;
9294     }
9295   }
9296
9297   return Changed;
9298 }
9299
9300 FunctionPass *llvm::createInstructionCombiningPass() {
9301   return new InstCombiner();
9302 }
9303