Clean up some code around the store V, (cast P) -> store (cast V), P
[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/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include <algorithm>
55 using namespace llvm;
56 using namespace llvm::PatternMatch;
57
58 STATISTIC(NumCombined , "Number of insts combined");
59 STATISTIC(NumConstProp, "Number of constant folds");
60 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
61 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
62 STATISTIC(NumSunkInst , "Number of instructions sunk");
63
64 namespace {
65   class VISIBILITY_HIDDEN InstCombiner
66     : public FunctionPass,
67       public InstVisitor<InstCombiner, Instruction*> {
68     // Worklist of all of the instructions that need to be simplified.
69     std::vector<Instruction*> WorkList;
70     TargetData *TD;
71
72     /// AddUsersToWorkList - When an instruction is simplified, add all users of
73     /// the instruction to the work lists because they might get more simplified
74     /// now.
75     ///
76     void AddUsersToWorkList(Value &I) {
77       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
78            UI != UE; ++UI)
79         WorkList.push_back(cast<Instruction>(*UI));
80     }
81
82     /// AddUsesToWorkList - When an instruction is simplified, add operands to
83     /// the work lists because they might get more simplified now.
84     ///
85     void AddUsesToWorkList(Instruction &I) {
86       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88           WorkList.push_back(Op);
89     }
90     
91     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
92     /// dead.  Add all of its operands to the worklist, turning them into
93     /// undef's to reduce the number of uses of those instructions.
94     ///
95     /// Return the specified operand before it is turned into an undef.
96     ///
97     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
98       Value *R = I.getOperand(op);
99       
100       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
101         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
102           WorkList.push_back(Op);
103           // Set the operand to undef to drop the use.
104           I.setOperand(i, UndefValue::get(Op->getType()));
105         }
106       
107       return R;
108     }
109
110     // removeFromWorkList - remove all instances of I from the worklist.
111     void removeFromWorkList(Instruction *I);
112   public:
113     virtual bool runOnFunction(Function &F);
114
115     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
116       AU.addRequired<TargetData>();
117       AU.addPreservedID(LCSSAID);
118       AU.setPreservesCFG();
119     }
120
121     TargetData &getTargetData() const { return *TD; }
122
123     // Visitation implementation - Implement instruction combining for different
124     // instruction types.  The semantics are as follows:
125     // Return Value:
126     //    null        - No change was made
127     //     I          - Change was made, I is still valid, I may be dead though
128     //   otherwise    - Change was made, replace I with returned instruction
129     //
130     Instruction *visitAdd(BinaryOperator &I);
131     Instruction *visitSub(BinaryOperator &I);
132     Instruction *visitMul(BinaryOperator &I);
133     Instruction *visitURem(BinaryOperator &I);
134     Instruction *visitSRem(BinaryOperator &I);
135     Instruction *visitFRem(BinaryOperator &I);
136     Instruction *commonRemTransforms(BinaryOperator &I);
137     Instruction *commonIRemTransforms(BinaryOperator &I);
138     Instruction *commonDivTransforms(BinaryOperator &I);
139     Instruction *commonIDivTransforms(BinaryOperator &I);
140     Instruction *visitUDiv(BinaryOperator &I);
141     Instruction *visitSDiv(BinaryOperator &I);
142     Instruction *visitFDiv(BinaryOperator &I);
143     Instruction *visitAnd(BinaryOperator &I);
144     Instruction *visitOr (BinaryOperator &I);
145     Instruction *visitXor(BinaryOperator &I);
146     Instruction *visitFCmpInst(FCmpInst &I);
147     Instruction *visitICmpInst(ICmpInst &I);
148     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
149
150     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
151                              ICmpInst::Predicate Cond, Instruction &I);
152     Instruction *visitShiftInst(ShiftInst &I);
153     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
154                                      ShiftInst &I);
155     Instruction *commonCastTransforms(CastInst &CI);
156     Instruction *commonIntCastTransforms(CastInst &CI);
157     Instruction *visitTrunc(CastInst &CI);
158     Instruction *visitZExt(CastInst &CI);
159     Instruction *visitSExt(CastInst &CI);
160     Instruction *visitFPTrunc(CastInst &CI);
161     Instruction *visitFPExt(CastInst &CI);
162     Instruction *visitFPToUI(CastInst &CI);
163     Instruction *visitFPToSI(CastInst &CI);
164     Instruction *visitUIToFP(CastInst &CI);
165     Instruction *visitSIToFP(CastInst &CI);
166     Instruction *visitPtrToInt(CastInst &CI);
167     Instruction *visitIntToPtr(CastInst &CI);
168     Instruction *visitBitCast(CastInst &CI);
169     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
170                                 Instruction *FI);
171     Instruction *visitSelectInst(SelectInst &CI);
172     Instruction *visitCallInst(CallInst &CI);
173     Instruction *visitInvokeInst(InvokeInst &II);
174     Instruction *visitPHINode(PHINode &PN);
175     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
176     Instruction *visitAllocationInst(AllocationInst &AI);
177     Instruction *visitFreeInst(FreeInst &FI);
178     Instruction *visitLoadInst(LoadInst &LI);
179     Instruction *visitStoreInst(StoreInst &SI);
180     Instruction *visitBranchInst(BranchInst &BI);
181     Instruction *visitSwitchInst(SwitchInst &SI);
182     Instruction *visitInsertElementInst(InsertElementInst &IE);
183     Instruction *visitExtractElementInst(ExtractElementInst &EI);
184     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
185
186     // visitInstruction - Specify what to return for unhandled instructions...
187     Instruction *visitInstruction(Instruction &I) { return 0; }
188
189   private:
190     Instruction *visitCallSite(CallSite CS);
191     bool transformConstExprCastCall(CallSite CS);
192
193   public:
194     // InsertNewInstBefore - insert an instruction New before instruction Old
195     // in the program.  Add the new instruction to the worklist.
196     //
197     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
198       assert(New && New->getParent() == 0 &&
199              "New instruction already inserted into a basic block!");
200       BasicBlock *BB = Old.getParent();
201       BB->getInstList().insert(&Old, New);  // Insert inst
202       WorkList.push_back(New);              // Add to worklist
203       return New;
204     }
205
206     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
207     /// This also adds the cast to the worklist.  Finally, this returns the
208     /// cast.
209     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
210                             Instruction &Pos) {
211       if (V->getType() == Ty) return V;
212
213       if (Constant *CV = dyn_cast<Constant>(V))
214         return ConstantExpr::getCast(opc, CV, Ty);
215       
216       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
217       WorkList.push_back(C);
218       return C;
219     }
220
221     // ReplaceInstUsesWith - This method is to be used when an instruction is
222     // found to be dead, replacable with another preexisting expression.  Here
223     // we add all uses of I to the worklist, replace all uses of I with the new
224     // value, then return I, so that the inst combiner will know that I was
225     // modified.
226     //
227     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
228       AddUsersToWorkList(I);         // Add all modified instrs to worklist
229       if (&I != V) {
230         I.replaceAllUsesWith(V);
231         return &I;
232       } else {
233         // If we are replacing the instruction with itself, this must be in a
234         // segment of unreachable code, so just clobber the instruction.
235         I.replaceAllUsesWith(UndefValue::get(I.getType()));
236         return &I;
237       }
238     }
239
240     // UpdateValueUsesWith - This method is to be used when an value is
241     // found to be replacable with another preexisting expression or was
242     // updated.  Here we add all uses of I to the worklist, replace all uses of
243     // I with the new value (unless the instruction was just updated), then
244     // return true, so that the inst combiner will know that I was modified.
245     //
246     bool UpdateValueUsesWith(Value *Old, Value *New) {
247       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
248       if (Old != New)
249         Old->replaceAllUsesWith(New);
250       if (Instruction *I = dyn_cast<Instruction>(Old))
251         WorkList.push_back(I);
252       if (Instruction *I = dyn_cast<Instruction>(New))
253         WorkList.push_back(I);
254       return true;
255     }
256     
257     // EraseInstFromFunction - When dealing with an instruction that has side
258     // effects or produces a void value, we can't rely on DCE to delete the
259     // instruction.  Instead, visit methods should return the value returned by
260     // this function.
261     Instruction *EraseInstFromFunction(Instruction &I) {
262       assert(I.use_empty() && "Cannot erase instruction that is used!");
263       AddUsesToWorkList(I);
264       removeFromWorkList(&I);
265       I.eraseFromParent();
266       return 0;  // Don't do anything with FI
267     }
268
269   private:
270     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
271     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
272     /// casts that are known to not do anything...
273     ///
274     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
275                                    Value *V, const Type *DestTy,
276                                    Instruction *InsertBefore);
277
278     /// SimplifyCommutative - This performs a few simplifications for 
279     /// commutative operators.
280     bool SimplifyCommutative(BinaryOperator &I);
281
282     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
283     /// most-complex to least-complex order.
284     bool SimplifyCompare(CmpInst &I);
285
286     bool SimplifyDemandedBits(Value *V, uint64_t Mask, 
287                               uint64_t &KnownZero, uint64_t &KnownOne,
288                               unsigned Depth = 0);
289
290     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
291                                       uint64_t &UndefElts, unsigned Depth = 0);
292       
293     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
294     // PHI node as operand #0, see if we can fold the instruction into the PHI
295     // (which is only possible if all operands to the PHI are constants).
296     Instruction *FoldOpIntoPhi(Instruction &I);
297
298     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
299     // operator and they all are only used by the PHI, PHI together their
300     // inputs, and do the operation once, to the result of the PHI.
301     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
302     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
303     
304     
305     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
306                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
307     
308     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
309                               bool isSub, Instruction &I);
310     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
311                                  bool isSigned, bool Inside, Instruction &IB);
312     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
313     Instruction *MatchBSwap(BinaryOperator &I);
314
315     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
316   };
317
318   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
319 }
320
321 // getComplexity:  Assign a complexity or rank value to LLVM Values...
322 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
323 static unsigned getComplexity(Value *V) {
324   if (isa<Instruction>(V)) {
325     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
326       return 3;
327     return 4;
328   }
329   if (isa<Argument>(V)) return 3;
330   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
331 }
332
333 // isOnlyUse - Return true if this instruction will be deleted if we stop using
334 // it.
335 static bool isOnlyUse(Value *V) {
336   return V->hasOneUse() || isa<Constant>(V);
337 }
338
339 // getPromotedType - Return the specified type promoted as it would be to pass
340 // though a va_arg area...
341 static const Type *getPromotedType(const Type *Ty) {
342   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
343     if (ITy->getBitWidth() < 32)
344       return Type::Int32Ty;
345   } else if (Ty == Type::FloatTy)
346     return Type::DoubleTy;
347   return Ty;
348 }
349
350 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
351 /// expression bitcast,  return the operand value, otherwise return null.
352 static Value *getBitCastOperand(Value *V) {
353   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
354     return I->getOperand(0);
355   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
356     if (CE->getOpcode() == Instruction::BitCast)
357       return CE->getOperand(0);
358   return 0;
359 }
360
361 /// This function is a wrapper around CastInst::isEliminableCastPair. It
362 /// simply extracts arguments and returns what that function returns.
363 /// @Determine if it is valid to eliminate a Convert pair
364 static Instruction::CastOps 
365 isEliminableCastPair(
366   const CastInst *CI, ///< The first cast instruction
367   unsigned opcode,       ///< The opcode of the second cast instruction
368   const Type *DstTy,     ///< The target type for the second cast instruction
369   TargetData *TD         ///< The target data for pointer size
370 ) {
371   
372   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
373   const Type *MidTy = CI->getType();                  // B from above
374
375   // Get the opcodes of the two Cast instructions
376   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
377   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
378
379   return Instruction::CastOps(
380       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
381                                      DstTy, TD->getIntPtrType()));
382 }
383
384 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
385 /// in any code being generated.  It does not require codegen if V is simple
386 /// enough or if the cast can be folded into other casts.
387 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
388                               const Type *Ty, TargetData *TD) {
389   if (V->getType() == Ty || isa<Constant>(V)) return false;
390   
391   // If this is another cast that can be eliminated, it isn't codegen either.
392   if (const CastInst *CI = dyn_cast<CastInst>(V))
393     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
394       return false;
395   return true;
396 }
397
398 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
399 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
400 /// casts that are known to not do anything...
401 ///
402 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
403                                              Value *V, const Type *DestTy,
404                                              Instruction *InsertBefore) {
405   if (V->getType() == DestTy) return V;
406   if (Constant *C = dyn_cast<Constant>(V))
407     return ConstantExpr::getCast(opcode, C, DestTy);
408   
409   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
410 }
411
412 // SimplifyCommutative - This performs a few simplifications for commutative
413 // operators:
414 //
415 //  1. Order operands such that they are listed from right (least complex) to
416 //     left (most complex).  This puts constants before unary operators before
417 //     binary operators.
418 //
419 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
420 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
421 //
422 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
423   bool Changed = false;
424   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
425     Changed = !I.swapOperands();
426
427   if (!I.isAssociative()) return Changed;
428   Instruction::BinaryOps Opcode = I.getOpcode();
429   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
430     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
431       if (isa<Constant>(I.getOperand(1))) {
432         Constant *Folded = ConstantExpr::get(I.getOpcode(),
433                                              cast<Constant>(I.getOperand(1)),
434                                              cast<Constant>(Op->getOperand(1)));
435         I.setOperand(0, Op->getOperand(0));
436         I.setOperand(1, Folded);
437         return true;
438       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
439         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
440             isOnlyUse(Op) && isOnlyUse(Op1)) {
441           Constant *C1 = cast<Constant>(Op->getOperand(1));
442           Constant *C2 = cast<Constant>(Op1->getOperand(1));
443
444           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
445           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
446           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
447                                                     Op1->getOperand(0),
448                                                     Op1->getName(), &I);
449           WorkList.push_back(New);
450           I.setOperand(0, New);
451           I.setOperand(1, Folded);
452           return true;
453         }
454     }
455   return Changed;
456 }
457
458 /// SimplifyCompare - For a CmpInst this function just orders the operands
459 /// so that theyare listed from right (least complex) to left (most complex).
460 /// This puts constants before unary operators before binary operators.
461 bool InstCombiner::SimplifyCompare(CmpInst &I) {
462   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
463     return false;
464   I.swapOperands();
465   // Compare instructions are not associative so there's nothing else we can do.
466   return true;
467 }
468
469 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
470 // if the LHS is a constant zero (which is the 'negate' form).
471 //
472 static inline Value *dyn_castNegVal(Value *V) {
473   if (BinaryOperator::isNeg(V))
474     return BinaryOperator::getNegArgument(V);
475
476   // Constants can be considered to be negated values if they can be folded.
477   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
478     return ConstantExpr::getNeg(C);
479   return 0;
480 }
481
482 static inline Value *dyn_castNotVal(Value *V) {
483   if (BinaryOperator::isNot(V))
484     return BinaryOperator::getNotArgument(V);
485
486   // Constants can be considered to be not'ed values...
487   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
488     return ConstantExpr::getNot(C);
489   return 0;
490 }
491
492 // dyn_castFoldableMul - If this value is a multiply that can be folded into
493 // other computations (because it has a constant operand), return the
494 // non-constant operand of the multiply, and set CST to point to the multiplier.
495 // Otherwise, return null.
496 //
497 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
498   if (V->hasOneUse() && V->getType()->isInteger())
499     if (Instruction *I = dyn_cast<Instruction>(V)) {
500       if (I->getOpcode() == Instruction::Mul)
501         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
502           return I->getOperand(0);
503       if (I->getOpcode() == Instruction::Shl)
504         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
505           // The multiplier is really 1 << CST.
506           Constant *One = ConstantInt::get(V->getType(), 1);
507           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
508           return I->getOperand(0);
509         }
510     }
511   return 0;
512 }
513
514 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
515 /// expression, return it.
516 static User *dyn_castGetElementPtr(Value *V) {
517   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
518   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
519     if (CE->getOpcode() == Instruction::GetElementPtr)
520       return cast<User>(V);
521   return false;
522 }
523
524 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
525 static ConstantInt *AddOne(ConstantInt *C) {
526   return cast<ConstantInt>(ConstantExpr::getAdd(C,
527                                          ConstantInt::get(C->getType(), 1)));
528 }
529 static ConstantInt *SubOne(ConstantInt *C) {
530   return cast<ConstantInt>(ConstantExpr::getSub(C,
531                                          ConstantInt::get(C->getType(), 1)));
532 }
533
534 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
535 /// known to be either zero or one and return them in the KnownZero/KnownOne
536 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
537 /// processing.
538 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
539                               uint64_t &KnownOne, unsigned Depth = 0) {
540   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
541   // we cannot optimize based on the assumption that it is zero without changing
542   // it to be an explicit zero.  If we don't change it to zero, other code could
543   // optimized based on the contradictory assumption that it is non-zero.
544   // Because instcombine aggressively folds operations with undef args anyway,
545   // this won't lose us code quality.
546   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
547     // We know all of the bits for a constant!
548     KnownOne = CI->getZExtValue() & Mask;
549     KnownZero = ~KnownOne & Mask;
550     return;
551   }
552
553   KnownZero = KnownOne = 0;   // Don't know anything.
554   if (Depth == 6 || Mask == 0)
555     return;  // Limit search depth.
556
557   uint64_t KnownZero2, KnownOne2;
558   Instruction *I = dyn_cast<Instruction>(V);
559   if (!I) return;
560
561   Mask &= V->getType()->getIntegerTypeMask();
562   
563   switch (I->getOpcode()) {
564   case Instruction::And:
565     // If either the LHS or the RHS are Zero, the result is zero.
566     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
567     Mask &= ~KnownZero;
568     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
569     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
570     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
571     
572     // Output known-1 bits are only known if set in both the LHS & RHS.
573     KnownOne &= KnownOne2;
574     // Output known-0 are known to be clear if zero in either the LHS | RHS.
575     KnownZero |= KnownZero2;
576     return;
577   case Instruction::Or:
578     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
579     Mask &= ~KnownOne;
580     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
581     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
582     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
583     
584     // Output known-0 bits are only known if clear in both the LHS & RHS.
585     KnownZero &= KnownZero2;
586     // Output known-1 are known to be set if set in either the LHS | RHS.
587     KnownOne |= KnownOne2;
588     return;
589   case Instruction::Xor: {
590     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
591     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
592     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
593     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
594     
595     // Output known-0 bits are known if clear or set in both the LHS & RHS.
596     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
597     // Output known-1 are known to be set if set in only one of the LHS, RHS.
598     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
599     KnownZero = KnownZeroOut;
600     return;
601   }
602   case Instruction::Select:
603     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
604     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
605     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
606     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
607
608     // Only known if known in both the LHS and RHS.
609     KnownOne &= KnownOne2;
610     KnownZero &= KnownZero2;
611     return;
612   case Instruction::FPTrunc:
613   case Instruction::FPExt:
614   case Instruction::FPToUI:
615   case Instruction::FPToSI:
616   case Instruction::SIToFP:
617   case Instruction::PtrToInt:
618   case Instruction::UIToFP:
619   case Instruction::IntToPtr:
620     return; // Can't work with floating point or pointers
621   case Instruction::Trunc: 
622     // All these have integer operands
623     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
624     return;
625   case Instruction::BitCast: {
626     const Type *SrcTy = I->getOperand(0)->getType();
627     if (SrcTy->isInteger()) {
628       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
629       return;
630     }
631     break;
632   }
633   case Instruction::ZExt:  {
634     // Compute the bits in the result that are not present in the input.
635     const Type *SrcTy = I->getOperand(0)->getType();
636     uint64_t NotIn = ~SrcTy->getIntegerTypeMask();
637     uint64_t NewBits = I->getType()->getIntegerTypeMask() & NotIn;
638       
639     Mask &= SrcTy->getIntegerTypeMask();
640     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
641     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
642     // The top bits are known to be zero.
643     KnownZero |= NewBits;
644     return;
645   }
646   case Instruction::SExt: {
647     // Compute the bits in the result that are not present in the input.
648     const Type *SrcTy = I->getOperand(0)->getType();
649     uint64_t NotIn = ~SrcTy->getIntegerTypeMask();
650     uint64_t NewBits = I->getType()->getIntegerTypeMask() & NotIn;
651       
652     Mask &= SrcTy->getIntegerTypeMask();
653     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
654     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
655
656     // If the sign bit of the input is known set or clear, then we know the
657     // top bits of the result.
658     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
659     if (KnownZero & InSignBit) {          // Input sign bit known zero
660       KnownZero |= NewBits;
661       KnownOne &= ~NewBits;
662     } else if (KnownOne & InSignBit) {    // Input sign bit known set
663       KnownOne |= NewBits;
664       KnownZero &= ~NewBits;
665     } else {                              // Input sign bit unknown
666       KnownZero &= ~NewBits;
667       KnownOne &= ~NewBits;
668     }
669     return;
670   }
671   case Instruction::Shl:
672     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
673     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
674       uint64_t ShiftAmt = SA->getZExtValue();
675       Mask >>= ShiftAmt;
676       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
677       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
678       KnownZero <<= ShiftAmt;
679       KnownOne  <<= ShiftAmt;
680       KnownZero |= (1ULL << ShiftAmt)-1;  // low bits known zero.
681       return;
682     }
683     break;
684   case Instruction::LShr:
685     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
686     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
687       // Compute the new bits that are at the top now.
688       uint64_t ShiftAmt = SA->getZExtValue();
689       uint64_t HighBits = (1ULL << ShiftAmt)-1;
690       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
691       
692       // Unsigned shift right.
693       Mask <<= ShiftAmt;
694       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
695       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
696       KnownZero >>= ShiftAmt;
697       KnownOne  >>= ShiftAmt;
698       KnownZero |= HighBits;  // high bits known zero.
699       return;
700     }
701     break;
702   case Instruction::AShr:
703     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
704     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
705       // Compute the new bits that are at the top now.
706       uint64_t ShiftAmt = SA->getZExtValue();
707       uint64_t HighBits = (1ULL << ShiftAmt)-1;
708       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
709       
710       // Signed shift right.
711       Mask <<= ShiftAmt;
712       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
713       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
714       KnownZero >>= ShiftAmt;
715       KnownOne  >>= ShiftAmt;
716         
717       // Handle the sign bits.
718       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
719       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
720         
721       if (KnownZero & SignBit) {       // New bits are known zero.
722         KnownZero |= HighBits;
723       } else if (KnownOne & SignBit) { // New bits are known one.
724         KnownOne |= HighBits;
725       }
726       return;
727     }
728     break;
729   }
730 }
731
732 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
733 /// this predicate to simplify operations downstream.  Mask is known to be zero
734 /// for bits that V cannot have.
735 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
736   uint64_t KnownZero, KnownOne;
737   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
738   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
739   return (KnownZero & Mask) == Mask;
740 }
741
742 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
743 /// specified instruction is a constant integer.  If so, check to see if there
744 /// are any bits set in the constant that are not demanded.  If so, shrink the
745 /// constant and return true.
746 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
747                                    uint64_t Demanded) {
748   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
749   if (!OpC) return false;
750
751   // If there are no bits set that aren't demanded, nothing to do.
752   if ((~Demanded & OpC->getZExtValue()) == 0)
753     return false;
754
755   // This is producing any bits that are not needed, shrink the RHS.
756   uint64_t Val = Demanded & OpC->getZExtValue();
757   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
758   return true;
759 }
760
761 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
762 // set of known zero and one bits, compute the maximum and minimum values that
763 // could have the specified known zero and known one bits, returning them in
764 // min/max.
765 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
766                                                    uint64_t KnownZero,
767                                                    uint64_t KnownOne,
768                                                    int64_t &Min, int64_t &Max) {
769   uint64_t TypeBits = Ty->getIntegerTypeMask();
770   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
771
772   uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
773   
774   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
775   // bit if it is unknown.
776   Min = KnownOne;
777   Max = KnownOne|UnknownBits;
778   
779   if (SignBit & UnknownBits) { // Sign bit is unknown
780     Min |= SignBit;
781     Max &= ~SignBit;
782   }
783   
784   // Sign extend the min/max values.
785   int ShAmt = 64-Ty->getPrimitiveSizeInBits();
786   Min = (Min << ShAmt) >> ShAmt;
787   Max = (Max << ShAmt) >> ShAmt;
788 }
789
790 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
791 // a set of known zero and one bits, compute the maximum and minimum values that
792 // could have the specified known zero and known one bits, returning them in
793 // min/max.
794 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
795                                                      uint64_t KnownZero,
796                                                      uint64_t KnownOne,
797                                                      uint64_t &Min,
798                                                      uint64_t &Max) {
799   uint64_t TypeBits = Ty->getIntegerTypeMask();
800   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
801   
802   // The minimum value is when the unknown bits are all zeros.
803   Min = KnownOne;
804   // The maximum value is when the unknown bits are all ones.
805   Max = KnownOne|UnknownBits;
806 }
807
808
809 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
810 /// DemandedMask bits of the result of V are ever used downstream.  If we can
811 /// use this information to simplify V, do so and return true.  Otherwise,
812 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
813 /// the expression (used to simplify the caller).  The KnownZero/One bits may
814 /// only be accurate for those bits in the DemandedMask.
815 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
816                                         uint64_t &KnownZero, uint64_t &KnownOne,
817                                         unsigned Depth) {
818   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
819     // We know all of the bits for a constant!
820     KnownOne = CI->getZExtValue() & DemandedMask;
821     KnownZero = ~KnownOne & DemandedMask;
822     return false;
823   }
824   
825   KnownZero = KnownOne = 0;
826   if (!V->hasOneUse()) {    // Other users may use these bits.
827     if (Depth != 0) {       // Not at the root.
828       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
829       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
830       return false;
831     }
832     // If this is the root being simplified, allow it to have multiple uses,
833     // just set the DemandedMask to all bits.
834     DemandedMask = V->getType()->getIntegerTypeMask();
835   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
836     if (V != UndefValue::get(V->getType()))
837       return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
838     return false;
839   } else if (Depth == 6) {        // Limit search depth.
840     return false;
841   }
842   
843   Instruction *I = dyn_cast<Instruction>(V);
844   if (!I) return false;        // Only analyze instructions.
845
846   DemandedMask &= V->getType()->getIntegerTypeMask();
847   
848   uint64_t KnownZero2 = 0, KnownOne2 = 0;
849   switch (I->getOpcode()) {
850   default: break;
851   case Instruction::And:
852     // If either the LHS or the RHS are Zero, the result is zero.
853     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
854                              KnownZero, KnownOne, Depth+1))
855       return true;
856     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
857
858     // If something is known zero on the RHS, the bits aren't demanded on the
859     // LHS.
860     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
861                              KnownZero2, KnownOne2, Depth+1))
862       return true;
863     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
864
865     // If all of the demanded bits are known 1 on one side, return the other.
866     // These bits cannot contribute to the result of the 'and'.
867     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
868       return UpdateValueUsesWith(I, I->getOperand(0));
869     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
870       return UpdateValueUsesWith(I, I->getOperand(1));
871     
872     // If all of the demanded bits in the inputs are known zeros, return zero.
873     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
874       return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
875       
876     // If the RHS is a constant, see if we can simplify it.
877     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
878       return UpdateValueUsesWith(I, I);
879       
880     // Output known-1 bits are only known if set in both the LHS & RHS.
881     KnownOne &= KnownOne2;
882     // Output known-0 are known to be clear if zero in either the LHS | RHS.
883     KnownZero |= KnownZero2;
884     break;
885   case Instruction::Or:
886     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
887                              KnownZero, KnownOne, Depth+1))
888       return true;
889     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
890     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
891                              KnownZero2, KnownOne2, Depth+1))
892       return true;
893     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
894     
895     // If all of the demanded bits are known zero on one side, return the other.
896     // These bits cannot contribute to the result of the 'or'.
897     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
898       return UpdateValueUsesWith(I, I->getOperand(0));
899     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
900       return UpdateValueUsesWith(I, I->getOperand(1));
901
902     // If all of the potentially set bits on one side are known to be set on
903     // the other side, just use the 'other' side.
904     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
905         (DemandedMask & (~KnownZero)))
906       return UpdateValueUsesWith(I, I->getOperand(0));
907     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
908         (DemandedMask & (~KnownZero2)))
909       return UpdateValueUsesWith(I, I->getOperand(1));
910         
911     // If the RHS is a constant, see if we can simplify it.
912     if (ShrinkDemandedConstant(I, 1, DemandedMask))
913       return UpdateValueUsesWith(I, I);
914           
915     // Output known-0 bits are only known if clear in both the LHS & RHS.
916     KnownZero &= KnownZero2;
917     // Output known-1 are known to be set if set in either the LHS | RHS.
918     KnownOne |= KnownOne2;
919     break;
920   case Instruction::Xor: {
921     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
922                              KnownZero, KnownOne, Depth+1))
923       return true;
924     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
925     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
926                              KnownZero2, KnownOne2, Depth+1))
927       return true;
928     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
929     
930     // If all of the demanded bits are known zero on one side, return the other.
931     // These bits cannot contribute to the result of the 'xor'.
932     if ((DemandedMask & KnownZero) == DemandedMask)
933       return UpdateValueUsesWith(I, I->getOperand(0));
934     if ((DemandedMask & KnownZero2) == DemandedMask)
935       return UpdateValueUsesWith(I, I->getOperand(1));
936     
937     // Output known-0 bits are known if clear or set in both the LHS & RHS.
938     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
939     // Output known-1 are known to be set if set in only one of the LHS, RHS.
940     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
941     
942     // If all of the demanded bits are known to be zero on one side or the
943     // other, turn this into an *inclusive* or.
944     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
945     if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
946       Instruction *Or =
947         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
948                                  I->getName());
949       InsertNewInstBefore(Or, *I);
950       return UpdateValueUsesWith(I, Or);
951     }
952     
953     // If all of the demanded bits on one side are known, and all of the set
954     // bits on that side are also known to be set on the other side, turn this
955     // into an AND, as we know the bits will be cleared.
956     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
957     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
958       if ((KnownOne & KnownOne2) == KnownOne) {
959         Constant *AndC = ConstantInt::get(I->getType(), 
960                                           ~KnownOne & DemandedMask);
961         Instruction *And = 
962           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
963         InsertNewInstBefore(And, *I);
964         return UpdateValueUsesWith(I, And);
965       }
966     }
967     
968     // If the RHS is a constant, see if we can simplify it.
969     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
970     if (ShrinkDemandedConstant(I, 1, DemandedMask))
971       return UpdateValueUsesWith(I, I);
972     
973     KnownZero = KnownZeroOut;
974     KnownOne  = KnownOneOut;
975     break;
976   }
977   case Instruction::Select:
978     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
979                              KnownZero, KnownOne, Depth+1))
980       return true;
981     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
982                              KnownZero2, KnownOne2, Depth+1))
983       return true;
984     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
985     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
986     
987     // If the operands are constants, see if we can simplify them.
988     if (ShrinkDemandedConstant(I, 1, DemandedMask))
989       return UpdateValueUsesWith(I, I);
990     if (ShrinkDemandedConstant(I, 2, DemandedMask))
991       return UpdateValueUsesWith(I, I);
992     
993     // Only known if known in both the LHS and RHS.
994     KnownOne &= KnownOne2;
995     KnownZero &= KnownZero2;
996     break;
997   case Instruction::Trunc:
998     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
999                              KnownZero, KnownOne, Depth+1))
1000       return true;
1001     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1002     break;
1003   case Instruction::BitCast:
1004     if (!I->getOperand(0)->getType()->isInteger())
1005       return false;
1006       
1007     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1008                              KnownZero, KnownOne, Depth+1))
1009       return true;
1010     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1011     break;
1012   case Instruction::ZExt: {
1013     // Compute the bits in the result that are not present in the input.
1014     const Type *SrcTy = I->getOperand(0)->getType();
1015     uint64_t NotIn = ~SrcTy->getIntegerTypeMask();
1016     uint64_t NewBits = I->getType()->getIntegerTypeMask() & NotIn;
1017     
1018     DemandedMask &= SrcTy->getIntegerTypeMask();
1019     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1020                              KnownZero, KnownOne, Depth+1))
1021       return true;
1022     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1023     // The top bits are known to be zero.
1024     KnownZero |= NewBits;
1025     break;
1026   }
1027   case Instruction::SExt: {
1028     // Compute the bits in the result that are not present in the input.
1029     const Type *SrcTy = I->getOperand(0)->getType();
1030     uint64_t NotIn = ~SrcTy->getIntegerTypeMask();
1031     uint64_t NewBits = I->getType()->getIntegerTypeMask() & NotIn;
1032     
1033     // Get the sign bit for the source type
1034     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1035     int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegerTypeMask();
1036
1037     // If any of the sign extended bits are demanded, we know that the sign
1038     // bit is demanded.
1039     if (NewBits & DemandedMask)
1040       InputDemandedBits |= InSignBit;
1041       
1042     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1043                              KnownZero, KnownOne, Depth+1))
1044       return true;
1045     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1046       
1047     // If the sign bit of the input is known set or clear, then we know the
1048     // top bits of the result.
1049
1050     // If the input sign bit is known zero, or if the NewBits are not demanded
1051     // convert this into a zero extension.
1052     if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1053       // Convert to ZExt cast
1054       CastInst *NewCast = CastInst::create(
1055         Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1056       return UpdateValueUsesWith(I, NewCast);
1057     } else if (KnownOne & InSignBit) {    // Input sign bit known set
1058       KnownOne |= NewBits;
1059       KnownZero &= ~NewBits;
1060     } else {                              // Input sign bit unknown
1061       KnownZero &= ~NewBits;
1062       KnownOne &= ~NewBits;
1063     }
1064     break;
1065   }
1066   case Instruction::Add:
1067     // If there is a constant on the RHS, there are a variety of xformations
1068     // we can do.
1069     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1070       // If null, this should be simplified elsewhere.  Some of the xforms here
1071       // won't work if the RHS is zero.
1072       if (RHS->isNullValue())
1073         break;
1074       
1075       // Figure out what the input bits are.  If the top bits of the and result
1076       // are not demanded, then the add doesn't demand them from its input
1077       // either.
1078       
1079       // Shift the demanded mask up so that it's at the top of the uint64_t.
1080       unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1081       unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1082       
1083       // If the top bit of the output is demanded, demand everything from the
1084       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1085       uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
1086
1087       // Find information about known zero/one bits in the input.
1088       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1089                                KnownZero2, KnownOne2, Depth+1))
1090         return true;
1091
1092       // If the RHS of the add has bits set that can't affect the input, reduce
1093       // the constant.
1094       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1095         return UpdateValueUsesWith(I, I);
1096       
1097       // Avoid excess work.
1098       if (KnownZero2 == 0 && KnownOne2 == 0)
1099         break;
1100       
1101       // Turn it into OR if input bits are zero.
1102       if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1103         Instruction *Or =
1104           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1105                                    I->getName());
1106         InsertNewInstBefore(Or, *I);
1107         return UpdateValueUsesWith(I, Or);
1108       }
1109       
1110       // We can say something about the output known-zero and known-one bits,
1111       // depending on potential carries from the input constant and the
1112       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1113       // bits set and the RHS constant is 0x01001, then we know we have a known
1114       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1115       
1116       // To compute this, we first compute the potential carry bits.  These are
1117       // the bits which may be modified.  I'm not aware of a better way to do
1118       // this scan.
1119       uint64_t RHSVal = RHS->getZExtValue();
1120       
1121       bool CarryIn = false;
1122       uint64_t CarryBits = 0;
1123       uint64_t CurBit = 1;
1124       for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1125         // Record the current carry in.
1126         if (CarryIn) CarryBits |= CurBit;
1127         
1128         bool CarryOut;
1129         
1130         // This bit has a carry out unless it is "zero + zero" or
1131         // "zero + anything" with no carry in.
1132         if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1133           CarryOut = false;  // 0 + 0 has no carry out, even with carry in.
1134         } else if (!CarryIn &&
1135                    ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1136           CarryOut = false;  // 0 + anything has no carry out if no carry in.
1137         } else {
1138           // Otherwise, we have to assume we have a carry out.
1139           CarryOut = true;
1140         }
1141         
1142         // This stage's carry out becomes the next stage's carry-in.
1143         CarryIn = CarryOut;
1144       }
1145       
1146       // Now that we know which bits have carries, compute the known-1/0 sets.
1147       
1148       // Bits are known one if they are known zero in one operand and one in the
1149       // other, and there is no input carry.
1150       KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1151       
1152       // Bits are known zero if they are known zero in both operands and there
1153       // is no input carry.
1154       KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1155     }
1156     break;
1157   case Instruction::Shl:
1158     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1159       uint64_t ShiftAmt = SA->getZExtValue();
1160       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt, 
1161                                KnownZero, KnownOne, Depth+1))
1162         return true;
1163       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1164       KnownZero <<= ShiftAmt;
1165       KnownOne  <<= ShiftAmt;
1166       KnownZero |= (1ULL << ShiftAmt) - 1;  // low bits known zero.
1167     }
1168     break;
1169   case Instruction::LShr:
1170     // For a logical shift right
1171     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1172       unsigned ShiftAmt = SA->getZExtValue();
1173       
1174       // Compute the new bits that are at the top now.
1175       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1176       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1177       uint64_t TypeMask = I->getType()->getIntegerTypeMask();
1178       // Unsigned shift right.
1179       if (SimplifyDemandedBits(I->getOperand(0),
1180                               (DemandedMask << ShiftAmt) & TypeMask,
1181                                KnownZero, KnownOne, Depth+1))
1182         return true;
1183       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1184       KnownZero &= TypeMask;
1185       KnownOne  &= TypeMask;
1186       KnownZero >>= ShiftAmt;
1187       KnownOne  >>= ShiftAmt;
1188       KnownZero |= HighBits;  // high bits known zero.
1189     }
1190     break;
1191   case Instruction::AShr:
1192     // If this is an arithmetic shift right and only the low-bit is set, we can
1193     // always convert this into a logical shr, even if the shift amount is
1194     // variable.  The low bit of the shift cannot be an input sign bit unless
1195     // the shift amount is >= the size of the datatype, which is undefined.
1196     if (DemandedMask == 1) {
1197       // Perform the logical shift right.
1198       Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1199                                     I->getOperand(1), I->getName());
1200       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1201       return UpdateValueUsesWith(I, NewVal);
1202     }    
1203     
1204     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1205       unsigned ShiftAmt = SA->getZExtValue();
1206       
1207       // Compute the new bits that are at the top now.
1208       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1209       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1210       uint64_t TypeMask = I->getType()->getIntegerTypeMask();
1211       // Signed shift right.
1212       if (SimplifyDemandedBits(I->getOperand(0),
1213                                (DemandedMask << ShiftAmt) & TypeMask,
1214                                KnownZero, KnownOne, Depth+1))
1215         return true;
1216       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1217       KnownZero &= TypeMask;
1218       KnownOne  &= TypeMask;
1219       KnownZero >>= ShiftAmt;
1220       KnownOne  >>= ShiftAmt;
1221         
1222       // Handle the sign bits.
1223       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1224       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
1225         
1226       // If the input sign bit is known to be zero, or if none of the top bits
1227       // are demanded, turn this into an unsigned shift right.
1228       if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1229         // Perform the logical shift right.
1230         Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1231                                       SA, I->getName());
1232         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1233         return UpdateValueUsesWith(I, NewVal);
1234       } else if (KnownOne & SignBit) { // New bits are known one.
1235         KnownOne |= HighBits;
1236       }
1237     }
1238     break;
1239   }
1240   
1241   // If the client is only demanding bits that we know, return the known
1242   // constant.
1243   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1244     return UpdateValueUsesWith(I, ConstantInt::get(I->getType(), KnownOne));
1245   return false;
1246 }  
1247
1248
1249 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1250 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1251 /// actually used by the caller.  This method analyzes which elements of the
1252 /// operand are undef and returns that information in UndefElts.
1253 ///
1254 /// If the information about demanded elements can be used to simplify the
1255 /// operation, the operation is simplified, then the resultant value is
1256 /// returned.  This returns null if no change was made.
1257 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1258                                                 uint64_t &UndefElts,
1259                                                 unsigned Depth) {
1260   unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1261   assert(VWidth <= 64 && "Vector too wide to analyze!");
1262   uint64_t EltMask = ~0ULL >> (64-VWidth);
1263   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1264          "Invalid DemandedElts!");
1265
1266   if (isa<UndefValue>(V)) {
1267     // If the entire vector is undefined, just return this info.
1268     UndefElts = EltMask;
1269     return 0;
1270   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1271     UndefElts = EltMask;
1272     return UndefValue::get(V->getType());
1273   }
1274   
1275   UndefElts = 0;
1276   if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1277     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1278     Constant *Undef = UndefValue::get(EltTy);
1279
1280     std::vector<Constant*> Elts;
1281     for (unsigned i = 0; i != VWidth; ++i)
1282       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1283         Elts.push_back(Undef);
1284         UndefElts |= (1ULL << i);
1285       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1286         Elts.push_back(Undef);
1287         UndefElts |= (1ULL << i);
1288       } else {                               // Otherwise, defined.
1289         Elts.push_back(CP->getOperand(i));
1290       }
1291         
1292     // If we changed the constant, return it.
1293     Constant *NewCP = ConstantPacked::get(Elts);
1294     return NewCP != CP ? NewCP : 0;
1295   } else if (isa<ConstantAggregateZero>(V)) {
1296     // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1297     // set to undef.
1298     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1299     Constant *Zero = Constant::getNullValue(EltTy);
1300     Constant *Undef = UndefValue::get(EltTy);
1301     std::vector<Constant*> Elts;
1302     for (unsigned i = 0; i != VWidth; ++i)
1303       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1304     UndefElts = DemandedElts ^ EltMask;
1305     return ConstantPacked::get(Elts);
1306   }
1307   
1308   if (!V->hasOneUse()) {    // Other users may use these bits.
1309     if (Depth != 0) {       // Not at the root.
1310       // TODO: Just compute the UndefElts information recursively.
1311       return false;
1312     }
1313     return false;
1314   } else if (Depth == 10) {        // Limit search depth.
1315     return false;
1316   }
1317   
1318   Instruction *I = dyn_cast<Instruction>(V);
1319   if (!I) return false;        // Only analyze instructions.
1320   
1321   bool MadeChange = false;
1322   uint64_t UndefElts2;
1323   Value *TmpV;
1324   switch (I->getOpcode()) {
1325   default: break;
1326     
1327   case Instruction::InsertElement: {
1328     // If this is a variable index, we don't know which element it overwrites.
1329     // demand exactly the same input as we produce.
1330     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1331     if (Idx == 0) {
1332       // Note that we can't propagate undef elt info, because we don't know
1333       // which elt is getting updated.
1334       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1335                                         UndefElts2, Depth+1);
1336       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1337       break;
1338     }
1339     
1340     // If this is inserting an element that isn't demanded, remove this
1341     // insertelement.
1342     unsigned IdxNo = Idx->getZExtValue();
1343     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1344       return AddSoonDeadInstToWorklist(*I, 0);
1345     
1346     // Otherwise, the element inserted overwrites whatever was there, so the
1347     // input demanded set is simpler than the output set.
1348     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1349                                       DemandedElts & ~(1ULL << IdxNo),
1350                                       UndefElts, Depth+1);
1351     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1352
1353     // The inserted element is defined.
1354     UndefElts |= 1ULL << IdxNo;
1355     break;
1356   }
1357     
1358   case Instruction::And:
1359   case Instruction::Or:
1360   case Instruction::Xor:
1361   case Instruction::Add:
1362   case Instruction::Sub:
1363   case Instruction::Mul:
1364     // div/rem demand all inputs, because they don't want divide by zero.
1365     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1366                                       UndefElts, Depth+1);
1367     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1368     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1369                                       UndefElts2, Depth+1);
1370     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1371       
1372     // Output elements are undefined if both are undefined.  Consider things
1373     // like undef&0.  The result is known zero, not undef.
1374     UndefElts &= UndefElts2;
1375     break;
1376     
1377   case Instruction::Call: {
1378     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1379     if (!II) break;
1380     switch (II->getIntrinsicID()) {
1381     default: break;
1382       
1383     // Binary vector operations that work column-wise.  A dest element is a
1384     // function of the corresponding input elements from the two inputs.
1385     case Intrinsic::x86_sse_sub_ss:
1386     case Intrinsic::x86_sse_mul_ss:
1387     case Intrinsic::x86_sse_min_ss:
1388     case Intrinsic::x86_sse_max_ss:
1389     case Intrinsic::x86_sse2_sub_sd:
1390     case Intrinsic::x86_sse2_mul_sd:
1391     case Intrinsic::x86_sse2_min_sd:
1392     case Intrinsic::x86_sse2_max_sd:
1393       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1394                                         UndefElts, Depth+1);
1395       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1396       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1397                                         UndefElts2, Depth+1);
1398       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1399
1400       // If only the low elt is demanded and this is a scalarizable intrinsic,
1401       // scalarize it now.
1402       if (DemandedElts == 1) {
1403         switch (II->getIntrinsicID()) {
1404         default: break;
1405         case Intrinsic::x86_sse_sub_ss:
1406         case Intrinsic::x86_sse_mul_ss:
1407         case Intrinsic::x86_sse2_sub_sd:
1408         case Intrinsic::x86_sse2_mul_sd:
1409           // TODO: Lower MIN/MAX/ABS/etc
1410           Value *LHS = II->getOperand(1);
1411           Value *RHS = II->getOperand(2);
1412           // Extract the element as scalars.
1413           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1414           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1415           
1416           switch (II->getIntrinsicID()) {
1417           default: assert(0 && "Case stmts out of sync!");
1418           case Intrinsic::x86_sse_sub_ss:
1419           case Intrinsic::x86_sse2_sub_sd:
1420             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1421                                                         II->getName()), *II);
1422             break;
1423           case Intrinsic::x86_sse_mul_ss:
1424           case Intrinsic::x86_sse2_mul_sd:
1425             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1426                                                          II->getName()), *II);
1427             break;
1428           }
1429           
1430           Instruction *New =
1431             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1432                                   II->getName());
1433           InsertNewInstBefore(New, *II);
1434           AddSoonDeadInstToWorklist(*II, 0);
1435           return New;
1436         }            
1437       }
1438         
1439       // Output elements are undefined if both are undefined.  Consider things
1440       // like undef&0.  The result is known zero, not undef.
1441       UndefElts &= UndefElts2;
1442       break;
1443     }
1444     break;
1445   }
1446   }
1447   return MadeChange ? I : 0;
1448 }
1449
1450 /// @returns true if the specified compare instruction is
1451 /// true when both operands are equal...
1452 /// @brief Determine if the ICmpInst returns true if both operands are equal
1453 static bool isTrueWhenEqual(ICmpInst &ICI) {
1454   ICmpInst::Predicate pred = ICI.getPredicate();
1455   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1456          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1457          pred == ICmpInst::ICMP_SLE;
1458 }
1459
1460 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1461 /// function is designed to check a chain of associative operators for a
1462 /// potential to apply a certain optimization.  Since the optimization may be
1463 /// applicable if the expression was reassociated, this checks the chain, then
1464 /// reassociates the expression as necessary to expose the optimization
1465 /// opportunity.  This makes use of a special Functor, which must define
1466 /// 'shouldApply' and 'apply' methods.
1467 ///
1468 template<typename Functor>
1469 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1470   unsigned Opcode = Root.getOpcode();
1471   Value *LHS = Root.getOperand(0);
1472
1473   // Quick check, see if the immediate LHS matches...
1474   if (F.shouldApply(LHS))
1475     return F.apply(Root);
1476
1477   // Otherwise, if the LHS is not of the same opcode as the root, return.
1478   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1479   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1480     // Should we apply this transform to the RHS?
1481     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1482
1483     // If not to the RHS, check to see if we should apply to the LHS...
1484     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1485       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1486       ShouldApply = true;
1487     }
1488
1489     // If the functor wants to apply the optimization to the RHS of LHSI,
1490     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1491     if (ShouldApply) {
1492       BasicBlock *BB = Root.getParent();
1493
1494       // Now all of the instructions are in the current basic block, go ahead
1495       // and perform the reassociation.
1496       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1497
1498       // First move the selected RHS to the LHS of the root...
1499       Root.setOperand(0, LHSI->getOperand(1));
1500
1501       // Make what used to be the LHS of the root be the user of the root...
1502       Value *ExtraOperand = TmpLHSI->getOperand(1);
1503       if (&Root == TmpLHSI) {
1504         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1505         return 0;
1506       }
1507       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1508       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1509       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1510       BasicBlock::iterator ARI = &Root; ++ARI;
1511       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1512       ARI = Root;
1513
1514       // Now propagate the ExtraOperand down the chain of instructions until we
1515       // get to LHSI.
1516       while (TmpLHSI != LHSI) {
1517         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1518         // Move the instruction to immediately before the chain we are
1519         // constructing to avoid breaking dominance properties.
1520         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1521         BB->getInstList().insert(ARI, NextLHSI);
1522         ARI = NextLHSI;
1523
1524         Value *NextOp = NextLHSI->getOperand(1);
1525         NextLHSI->setOperand(1, ExtraOperand);
1526         TmpLHSI = NextLHSI;
1527         ExtraOperand = NextOp;
1528       }
1529
1530       // Now that the instructions are reassociated, have the functor perform
1531       // the transformation...
1532       return F.apply(Root);
1533     }
1534
1535     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1536   }
1537   return 0;
1538 }
1539
1540
1541 // AddRHS - Implements: X + X --> X << 1
1542 struct AddRHS {
1543   Value *RHS;
1544   AddRHS(Value *rhs) : RHS(rhs) {}
1545   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1546   Instruction *apply(BinaryOperator &Add) const {
1547     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1548                          ConstantInt::get(Type::Int8Ty, 1));
1549   }
1550 };
1551
1552 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1553 //                 iff C1&C2 == 0
1554 struct AddMaskingAnd {
1555   Constant *C2;
1556   AddMaskingAnd(Constant *c) : C2(c) {}
1557   bool shouldApply(Value *LHS) const {
1558     ConstantInt *C1;
1559     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1560            ConstantExpr::getAnd(C1, C2)->isNullValue();
1561   }
1562   Instruction *apply(BinaryOperator &Add) const {
1563     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1564   }
1565 };
1566
1567 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1568                                              InstCombiner *IC) {
1569   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1570     if (Constant *SOC = dyn_cast<Constant>(SO))
1571       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1572
1573     return IC->InsertNewInstBefore(CastInst::create(
1574           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1575   }
1576
1577   // Figure out if the constant is the left or the right argument.
1578   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1579   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1580
1581   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1582     if (ConstIsRHS)
1583       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1584     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1585   }
1586
1587   Value *Op0 = SO, *Op1 = ConstOperand;
1588   if (!ConstIsRHS)
1589     std::swap(Op0, Op1);
1590   Instruction *New;
1591   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1592     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1593   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1594     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1595                           SO->getName()+".cmp");
1596   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1597     New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1598   else {
1599     assert(0 && "Unknown binary instruction type!");
1600     abort();
1601   }
1602   return IC->InsertNewInstBefore(New, I);
1603 }
1604
1605 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1606 // constant as the other operand, try to fold the binary operator into the
1607 // select arguments.  This also works for Cast instructions, which obviously do
1608 // not have a second operand.
1609 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1610                                      InstCombiner *IC) {
1611   // Don't modify shared select instructions
1612   if (!SI->hasOneUse()) return 0;
1613   Value *TV = SI->getOperand(1);
1614   Value *FV = SI->getOperand(2);
1615
1616   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1617     // Bool selects with constant operands can be folded to logical ops.
1618     if (SI->getType() == Type::Int1Ty) return 0;
1619
1620     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1621     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1622
1623     return new SelectInst(SI->getCondition(), SelectTrueVal,
1624                           SelectFalseVal);
1625   }
1626   return 0;
1627 }
1628
1629
1630 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1631 /// node as operand #0, see if we can fold the instruction into the PHI (which
1632 /// is only possible if all operands to the PHI are constants).
1633 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1634   PHINode *PN = cast<PHINode>(I.getOperand(0));
1635   unsigned NumPHIValues = PN->getNumIncomingValues();
1636   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1637
1638   // Check to see if all of the operands of the PHI are constants.  If there is
1639   // one non-constant value, remember the BB it is.  If there is more than one
1640   // bail out.
1641   BasicBlock *NonConstBB = 0;
1642   for (unsigned i = 0; i != NumPHIValues; ++i)
1643     if (!isa<Constant>(PN->getIncomingValue(i))) {
1644       if (NonConstBB) return 0;  // More than one non-const value.
1645       NonConstBB = PN->getIncomingBlock(i);
1646       
1647       // If the incoming non-constant value is in I's block, we have an infinite
1648       // loop.
1649       if (NonConstBB == I.getParent())
1650         return 0;
1651     }
1652   
1653   // If there is exactly one non-constant value, we can insert a copy of the
1654   // operation in that block.  However, if this is a critical edge, we would be
1655   // inserting the computation one some other paths (e.g. inside a loop).  Only
1656   // do this if the pred block is unconditionally branching into the phi block.
1657   if (NonConstBB) {
1658     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1659     if (!BI || !BI->isUnconditional()) return 0;
1660   }
1661
1662   // Okay, we can do the transformation: create the new PHI node.
1663   PHINode *NewPN = new PHINode(I.getType(), I.getName());
1664   I.setName("");
1665   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1666   InsertNewInstBefore(NewPN, *PN);
1667
1668   // Next, add all of the operands to the PHI.
1669   if (I.getNumOperands() == 2) {
1670     Constant *C = cast<Constant>(I.getOperand(1));
1671     for (unsigned i = 0; i != NumPHIValues; ++i) {
1672       Value *InV;
1673       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1674         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1675           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1676         else
1677           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1678       } else {
1679         assert(PN->getIncomingBlock(i) == NonConstBB);
1680         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1681           InV = BinaryOperator::create(BO->getOpcode(),
1682                                        PN->getIncomingValue(i), C, "phitmp",
1683                                        NonConstBB->getTerminator());
1684         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1685           InV = CmpInst::create(CI->getOpcode(), 
1686                                 CI->getPredicate(),
1687                                 PN->getIncomingValue(i), C, "phitmp",
1688                                 NonConstBB->getTerminator());
1689         else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1690           InV = new ShiftInst(SI->getOpcode(),
1691                               PN->getIncomingValue(i), C, "phitmp",
1692                               NonConstBB->getTerminator());
1693         else
1694           assert(0 && "Unknown binop!");
1695         
1696         WorkList.push_back(cast<Instruction>(InV));
1697       }
1698       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1699     }
1700   } else { 
1701     CastInst *CI = cast<CastInst>(&I);
1702     const Type *RetTy = CI->getType();
1703     for (unsigned i = 0; i != NumPHIValues; ++i) {
1704       Value *InV;
1705       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1706         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1707       } else {
1708         assert(PN->getIncomingBlock(i) == NonConstBB);
1709         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1710                                I.getType(), "phitmp", 
1711                                NonConstBB->getTerminator());
1712         WorkList.push_back(cast<Instruction>(InV));
1713       }
1714       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1715     }
1716   }
1717   return ReplaceInstUsesWith(I, NewPN);
1718 }
1719
1720 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1721   bool Changed = SimplifyCommutative(I);
1722   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1723
1724   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1725     // X + undef -> undef
1726     if (isa<UndefValue>(RHS))
1727       return ReplaceInstUsesWith(I, RHS);
1728
1729     // X + 0 --> X
1730     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1731       if (RHSC->isNullValue())
1732         return ReplaceInstUsesWith(I, LHS);
1733     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1734       if (CFP->isExactlyValue(-0.0))
1735         return ReplaceInstUsesWith(I, LHS);
1736     }
1737
1738     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1739       // X + (signbit) --> X ^ signbit
1740       uint64_t Val = CI->getZExtValue();
1741       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1742         return BinaryOperator::createXor(LHS, RHS);
1743       
1744       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1745       // (X & 254)+1 -> (X&254)|1
1746       uint64_t KnownZero, KnownOne;
1747       if (!isa<PackedType>(I.getType()) &&
1748           SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
1749                                KnownZero, KnownOne))
1750         return &I;
1751     }
1752
1753     if (isa<PHINode>(LHS))
1754       if (Instruction *NV = FoldOpIntoPhi(I))
1755         return NV;
1756     
1757     ConstantInt *XorRHS = 0;
1758     Value *XorLHS = 0;
1759     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1760       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1761       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1762       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1763       
1764       uint64_t C0080Val = 1ULL << 31;
1765       int64_t CFF80Val = -C0080Val;
1766       unsigned Size = 32;
1767       do {
1768         if (TySizeBits > Size) {
1769           bool Found = false;
1770           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1771           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1772           if (RHSSExt == CFF80Val) {
1773             if (XorRHS->getZExtValue() == C0080Val)
1774               Found = true;
1775           } else if (RHSZExt == C0080Val) {
1776             if (XorRHS->getSExtValue() == CFF80Val)
1777               Found = true;
1778           }
1779           if (Found) {
1780             // This is a sign extend if the top bits are known zero.
1781             uint64_t Mask = ~0ULL;
1782             Mask <<= 64-(TySizeBits-Size);
1783             Mask &= XorLHS->getType()->getIntegerTypeMask();
1784             if (!MaskedValueIsZero(XorLHS, Mask))
1785               Size = 0;  // Not a sign ext, but can't be any others either.
1786             goto FoundSExt;
1787           }
1788         }
1789         Size >>= 1;
1790         C0080Val >>= Size;
1791         CFF80Val >>= Size;
1792       } while (Size >= 8);
1793       
1794 FoundSExt:
1795       const Type *MiddleType = 0;
1796       switch (Size) {
1797       default: break;
1798       case 32: MiddleType = Type::Int32Ty; break;
1799       case 16: MiddleType = Type::Int16Ty; break;
1800       case 8:  MiddleType = Type::Int8Ty; break;
1801       }
1802       if (MiddleType) {
1803         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1804         InsertNewInstBefore(NewTrunc, I);
1805         return new SExtInst(NewTrunc, I.getType());
1806       }
1807     }
1808   }
1809
1810   // X + X --> X << 1
1811   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
1812     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1813
1814     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1815       if (RHSI->getOpcode() == Instruction::Sub)
1816         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1817           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1818     }
1819     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1820       if (LHSI->getOpcode() == Instruction::Sub)
1821         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1822           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1823     }
1824   }
1825
1826   // -A + B  -->  B - A
1827   if (Value *V = dyn_castNegVal(LHS))
1828     return BinaryOperator::createSub(RHS, V);
1829
1830   // A + -B  -->  A - B
1831   if (!isa<Constant>(RHS))
1832     if (Value *V = dyn_castNegVal(RHS))
1833       return BinaryOperator::createSub(LHS, V);
1834
1835
1836   ConstantInt *C2;
1837   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1838     if (X == RHS)   // X*C + X --> X * (C+1)
1839       return BinaryOperator::createMul(RHS, AddOne(C2));
1840
1841     // X*C1 + X*C2 --> X * (C1+C2)
1842     ConstantInt *C1;
1843     if (X == dyn_castFoldableMul(RHS, C1))
1844       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1845   }
1846
1847   // X + X*C --> X * (C+1)
1848   if (dyn_castFoldableMul(RHS, C2) == LHS)
1849     return BinaryOperator::createMul(LHS, AddOne(C2));
1850
1851   // X + ~X --> -1   since   ~X = -X-1
1852   if (dyn_castNotVal(LHS) == RHS ||
1853       dyn_castNotVal(RHS) == LHS)
1854     return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1855   
1856
1857   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1858   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1859     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1860       return R;
1861
1862   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1863     Value *X = 0;
1864     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
1865       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1866       return BinaryOperator::createSub(C, X);
1867     }
1868
1869     // (X & FF00) + xx00  -> (X+xx00) & FF00
1870     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1871       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1872       if (Anded == CRHS) {
1873         // See if all bits from the first bit set in the Add RHS up are included
1874         // in the mask.  First, get the rightmost bit.
1875         uint64_t AddRHSV = CRHS->getZExtValue();
1876
1877         // Form a mask of all bits from the lowest bit added through the top.
1878         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1879         AddRHSHighBits &= C2->getType()->getIntegerTypeMask();
1880
1881         // See if the and mask includes all of these bits.
1882         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1883
1884         if (AddRHSHighBits == AddRHSHighBitsAnd) {
1885           // Okay, the xform is safe.  Insert the new add pronto.
1886           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1887                                                             LHS->getName()), I);
1888           return BinaryOperator::createAnd(NewAdd, C2);
1889         }
1890       }
1891     }
1892
1893     // Try to fold constant add into select arguments.
1894     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1895       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1896         return R;
1897   }
1898
1899   // add (cast *A to intptrtype) B -> 
1900   //   cast (GEP (cast *A to sbyte*) B) -> 
1901   //     intptrtype
1902   {
1903     CastInst *CI = dyn_cast<CastInst>(LHS);
1904     Value *Other = RHS;
1905     if (!CI) {
1906       CI = dyn_cast<CastInst>(RHS);
1907       Other = LHS;
1908     }
1909     if (CI && CI->getType()->isSized() && 
1910         (CI->getType()->getPrimitiveSizeInBits() == 
1911          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
1912         && isa<PointerType>(CI->getOperand(0)->getType())) {
1913       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
1914                                    PointerType::get(Type::Int8Ty), I);
1915       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1916       return new PtrToIntInst(I2, CI->getType());
1917     }
1918   }
1919
1920   return Changed ? &I : 0;
1921 }
1922
1923 // isSignBit - Return true if the value represented by the constant only has the
1924 // highest order bit set.
1925 static bool isSignBit(ConstantInt *CI) {
1926   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1927   return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1928 }
1929
1930 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1931   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1932
1933   if (Op0 == Op1)         // sub X, X  -> 0
1934     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1935
1936   // If this is a 'B = x-(-A)', change to B = x+A...
1937   if (Value *V = dyn_castNegVal(Op1))
1938     return BinaryOperator::createAdd(Op0, V);
1939
1940   if (isa<UndefValue>(Op0))
1941     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
1942   if (isa<UndefValue>(Op1))
1943     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
1944
1945   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1946     // Replace (-1 - A) with (~A)...
1947     if (C->isAllOnesValue())
1948       return BinaryOperator::createNot(Op1);
1949
1950     // C - ~X == X + (1+C)
1951     Value *X = 0;
1952     if (match(Op1, m_Not(m_Value(X))))
1953       return BinaryOperator::createAdd(X,
1954                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1955     // -(X >>u 31) -> (X >>s 31)
1956     // -(X >>s 31) -> (X >>u 31)
1957     if (C->isNullValue()) {
1958       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op1))
1959         if (SI->getOpcode() == Instruction::LShr) {
1960           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1961             // Check to see if we are shifting out everything but the sign bit.
1962             if (CU->getZExtValue() == 
1963                 SI->getType()->getPrimitiveSizeInBits()-1) {
1964               // Ok, the transformation is safe.  Insert AShr.
1965               return new ShiftInst(Instruction::AShr, SI->getOperand(0), CU,
1966                                    SI->getName());
1967             }
1968           }
1969         }
1970         else if (SI->getOpcode() == Instruction::AShr) {
1971           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1972             // Check to see if we are shifting out everything but the sign bit.
1973             if (CU->getZExtValue() == 
1974                 SI->getType()->getPrimitiveSizeInBits()-1) {
1975               // Ok, the transformation is safe.  Insert LShr. 
1976               return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU, 
1977                                    SI->getName());
1978             }
1979           }
1980         } 
1981     }
1982
1983     // Try to fold constant sub into select arguments.
1984     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1985       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1986         return R;
1987
1988     if (isa<PHINode>(Op0))
1989       if (Instruction *NV = FoldOpIntoPhi(I))
1990         return NV;
1991   }
1992
1993   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1994     if (Op1I->getOpcode() == Instruction::Add &&
1995         !Op0->getType()->isFPOrFPVector()) {
1996       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
1997         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
1998       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
1999         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2000       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2001         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2002           // C1-(X+C2) --> (C1-C2)-X
2003           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2004                                            Op1I->getOperand(0));
2005       }
2006     }
2007
2008     if (Op1I->hasOneUse()) {
2009       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2010       // is not used by anyone else...
2011       //
2012       if (Op1I->getOpcode() == Instruction::Sub &&
2013           !Op1I->getType()->isFPOrFPVector()) {
2014         // Swap the two operands of the subexpr...
2015         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2016         Op1I->setOperand(0, IIOp1);
2017         Op1I->setOperand(1, IIOp0);
2018
2019         // Create the new top level add instruction...
2020         return BinaryOperator::createAdd(Op0, Op1);
2021       }
2022
2023       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2024       //
2025       if (Op1I->getOpcode() == Instruction::And &&
2026           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2027         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2028
2029         Value *NewNot =
2030           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2031         return BinaryOperator::createAnd(Op0, NewNot);
2032       }
2033
2034       // 0 - (X sdiv C)  -> (X sdiv -C)
2035       if (Op1I->getOpcode() == Instruction::SDiv)
2036         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2037           if (CSI->isNullValue())
2038             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2039               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2040                                                ConstantExpr::getNeg(DivRHS));
2041
2042       // X - X*C --> X * (1-C)
2043       ConstantInt *C2 = 0;
2044       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2045         Constant *CP1 =
2046           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2047         return BinaryOperator::createMul(Op0, CP1);
2048       }
2049     }
2050   }
2051
2052   if (!Op0->getType()->isFPOrFPVector())
2053     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2054       if (Op0I->getOpcode() == Instruction::Add) {
2055         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2056           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2057         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2058           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2059       } else if (Op0I->getOpcode() == Instruction::Sub) {
2060         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2061           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2062       }
2063
2064   ConstantInt *C1;
2065   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2066     if (X == Op1) { // X*C - X --> X * (C-1)
2067       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2068       return BinaryOperator::createMul(Op1, CP1);
2069     }
2070
2071     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2072     if (X == dyn_castFoldableMul(Op1, C2))
2073       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2074   }
2075   return 0;
2076 }
2077
2078 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2079 /// really just returns true if the most significant (sign) bit is set.
2080 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2081   switch (pred) {
2082     case ICmpInst::ICMP_SLT: 
2083       // True if LHS s< RHS and RHS == 0
2084       return RHS->isNullValue();
2085     case ICmpInst::ICMP_SLE: 
2086       // True if LHS s<= RHS and RHS == -1
2087       return RHS->isAllOnesValue();
2088     case ICmpInst::ICMP_UGE: 
2089       // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2090       return RHS->getZExtValue() == (1ULL << 
2091         (RHS->getType()->getPrimitiveSizeInBits()-1));
2092     case ICmpInst::ICMP_UGT:
2093       // True if LHS u> RHS and RHS == high-bit-mask - 1
2094       return RHS->getZExtValue() ==
2095         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2096     default:
2097       return false;
2098   }
2099 }
2100
2101 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2102   bool Changed = SimplifyCommutative(I);
2103   Value *Op0 = I.getOperand(0);
2104
2105   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2106     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2107
2108   // Simplify mul instructions with a constant RHS...
2109   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2110     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2111
2112       // ((X << C1)*C2) == (X * (C2 << C1))
2113       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2114         if (SI->getOpcode() == Instruction::Shl)
2115           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2116             return BinaryOperator::createMul(SI->getOperand(0),
2117                                              ConstantExpr::getShl(CI, ShOp));
2118
2119       if (CI->isNullValue())
2120         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2121       if (CI->equalsInt(1))                  // X * 1  == X
2122         return ReplaceInstUsesWith(I, Op0);
2123       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2124         return BinaryOperator::createNeg(Op0, I.getName());
2125
2126       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2127       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2128         uint64_t C = Log2_64(Val);
2129         return new ShiftInst(Instruction::Shl, Op0,
2130                              ConstantInt::get(Type::Int8Ty, C));
2131       }
2132     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2133       if (Op1F->isNullValue())
2134         return ReplaceInstUsesWith(I, Op1);
2135
2136       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2137       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2138       if (Op1F->getValue() == 1.0)
2139         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2140     }
2141     
2142     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2143       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2144           isa<ConstantInt>(Op0I->getOperand(1))) {
2145         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2146         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2147                                                      Op1, "tmp");
2148         InsertNewInstBefore(Add, I);
2149         Value *C1C2 = ConstantExpr::getMul(Op1, 
2150                                            cast<Constant>(Op0I->getOperand(1)));
2151         return BinaryOperator::createAdd(Add, C1C2);
2152         
2153       }
2154
2155     // Try to fold constant mul into select arguments.
2156     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2157       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2158         return R;
2159
2160     if (isa<PHINode>(Op0))
2161       if (Instruction *NV = FoldOpIntoPhi(I))
2162         return NV;
2163   }
2164
2165   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2166     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2167       return BinaryOperator::createMul(Op0v, Op1v);
2168
2169   // If one of the operands of the multiply is a cast from a boolean value, then
2170   // we know the bool is either zero or one, so this is a 'masking' multiply.
2171   // See if we can simplify things based on how the boolean was originally
2172   // formed.
2173   CastInst *BoolCast = 0;
2174   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2175     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2176       BoolCast = CI;
2177   if (!BoolCast)
2178     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2179       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2180         BoolCast = CI;
2181   if (BoolCast) {
2182     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2183       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2184       const Type *SCOpTy = SCIOp0->getType();
2185
2186       // If the icmp is true iff the sign bit of X is set, then convert this
2187       // multiply into a shift/and combination.
2188       if (isa<ConstantInt>(SCIOp1) &&
2189           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
2190         // Shift the X value right to turn it into "all signbits".
2191         Constant *Amt = ConstantInt::get(Type::Int8Ty,
2192                                           SCOpTy->getPrimitiveSizeInBits()-1);
2193         Value *V =
2194           InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
2195                                             BoolCast->getOperand(0)->getName()+
2196                                             ".mask"), I);
2197
2198         // If the multiply type is not the same as the source type, sign extend
2199         // or truncate to the multiply type.
2200         if (I.getType() != V->getType()) {
2201           unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2202           unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2203           Instruction::CastOps opcode = 
2204             (SrcBits == DstBits ? Instruction::BitCast : 
2205              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2206           V = InsertCastBefore(opcode, V, I.getType(), I);
2207         }
2208
2209         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2210         return BinaryOperator::createAnd(V, OtherOp);
2211       }
2212     }
2213   }
2214
2215   return Changed ? &I : 0;
2216 }
2217
2218 /// This function implements the transforms on div instructions that work
2219 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2220 /// used by the visitors to those instructions.
2221 /// @brief Transforms common to all three div instructions
2222 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2223   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2224
2225   // undef / X -> 0
2226   if (isa<UndefValue>(Op0))
2227     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2228
2229   // X / undef -> undef
2230   if (isa<UndefValue>(Op1))
2231     return ReplaceInstUsesWith(I, Op1);
2232
2233   // Handle cases involving: div X, (select Cond, Y, Z)
2234   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2235     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2236     // same basic block, then we replace the select with Y, and the condition 
2237     // of the select with false (if the cond value is in the same BB).  If the
2238     // select has uses other than the div, this allows them to be simplified
2239     // also. Note that div X, Y is just as good as div X, 0 (undef)
2240     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2241       if (ST->isNullValue()) {
2242         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2243         if (CondI && CondI->getParent() == I.getParent())
2244           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2245         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2246           I.setOperand(1, SI->getOperand(2));
2247         else
2248           UpdateValueUsesWith(SI, SI->getOperand(2));
2249         return &I;
2250       }
2251
2252     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2253     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2254       if (ST->isNullValue()) {
2255         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2256         if (CondI && CondI->getParent() == I.getParent())
2257           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2258         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2259           I.setOperand(1, SI->getOperand(1));
2260         else
2261           UpdateValueUsesWith(SI, SI->getOperand(1));
2262         return &I;
2263       }
2264   }
2265
2266   return 0;
2267 }
2268
2269 /// This function implements the transforms common to both integer division
2270 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2271 /// division instructions.
2272 /// @brief Common integer divide transforms
2273 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2274   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2275
2276   if (Instruction *Common = commonDivTransforms(I))
2277     return Common;
2278
2279   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2280     // div X, 1 == X
2281     if (RHS->equalsInt(1))
2282       return ReplaceInstUsesWith(I, Op0);
2283
2284     // (X / C1) / C2  -> X / (C1*C2)
2285     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2286       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2287         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2288           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2289                                         ConstantExpr::getMul(RHS, LHSRHS));
2290         }
2291
2292     if (!RHS->isNullValue()) { // avoid X udiv 0
2293       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2294         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2295           return R;
2296       if (isa<PHINode>(Op0))
2297         if (Instruction *NV = FoldOpIntoPhi(I))
2298           return NV;
2299     }
2300   }
2301
2302   // 0 / X == 0, we don't need to preserve faults!
2303   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2304     if (LHS->equalsInt(0))
2305       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2306
2307   return 0;
2308 }
2309
2310 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2311   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2312
2313   // Handle the integer div common cases
2314   if (Instruction *Common = commonIDivTransforms(I))
2315     return Common;
2316
2317   // X udiv C^2 -> X >> C
2318   // Check to see if this is an unsigned division with an exact power of 2,
2319   // if so, convert to a right shift.
2320   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2321     if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
2322       if (isPowerOf2_64(Val)) {
2323         uint64_t ShiftAmt = Log2_64(Val);
2324         return new ShiftInst(Instruction::LShr, Op0, 
2325                               ConstantInt::get(Type::Int8Ty, ShiftAmt));
2326       }
2327   }
2328
2329   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2330   if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2331     if (RHSI->getOpcode() == Instruction::Shl &&
2332         isa<ConstantInt>(RHSI->getOperand(0))) {
2333       uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2334       if (isPowerOf2_64(C1)) {
2335         Value *N = RHSI->getOperand(1);
2336         const Type *NTy = N->getType();
2337         if (uint64_t C2 = Log2_64(C1)) {
2338           Constant *C2V = ConstantInt::get(NTy, C2);
2339           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2340         }
2341         return new ShiftInst(Instruction::LShr, Op0, N);
2342       }
2343     }
2344   }
2345   
2346   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2347   // where C1&C2 are powers of two.
2348   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2349     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2350       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) 
2351         if (!STO->isNullValue() && !STO->isNullValue()) {
2352           uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2353           if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2354             // Compute the shift amounts
2355             unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2356             // Construct the "on true" case of the select
2357             Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
2358             Instruction *TSI = 
2359               new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
2360             TSI = InsertNewInstBefore(TSI, I);
2361     
2362             // Construct the "on false" case of the select
2363             Constant *FC = ConstantInt::get(Type::Int8Ty, FSA); 
2364             Instruction *FSI = 
2365               new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
2366             FSI = InsertNewInstBefore(FSI, I);
2367
2368             // construct the select instruction and return it.
2369             return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2370           }
2371         }
2372   }
2373   return 0;
2374 }
2375
2376 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2377   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2378
2379   // Handle the integer div common cases
2380   if (Instruction *Common = commonIDivTransforms(I))
2381     return Common;
2382
2383   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2384     // sdiv X, -1 == -X
2385     if (RHS->isAllOnesValue())
2386       return BinaryOperator::createNeg(Op0);
2387
2388     // -X/C -> X/-C
2389     if (Value *LHSNeg = dyn_castNegVal(Op0))
2390       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2391   }
2392
2393   // If the sign bits of both operands are zero (i.e. we can prove they are
2394   // unsigned inputs), turn this into a udiv.
2395   if (I.getType()->isInteger()) {
2396     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2397     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2398       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2399     }
2400   }      
2401   
2402   return 0;
2403 }
2404
2405 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2406   return commonDivTransforms(I);
2407 }
2408
2409 /// GetFactor - If we can prove that the specified value is at least a multiple
2410 /// of some factor, return that factor.
2411 static Constant *GetFactor(Value *V) {
2412   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2413     return CI;
2414   
2415   // Unless we can be tricky, we know this is a multiple of 1.
2416   Constant *Result = ConstantInt::get(V->getType(), 1);
2417   
2418   Instruction *I = dyn_cast<Instruction>(V);
2419   if (!I) return Result;
2420   
2421   if (I->getOpcode() == Instruction::Mul) {
2422     // Handle multiplies by a constant, etc.
2423     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2424                                 GetFactor(I->getOperand(1)));
2425   } else if (I->getOpcode() == Instruction::Shl) {
2426     // (X<<C) -> X * (1 << C)
2427     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2428       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2429       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2430     }
2431   } else if (I->getOpcode() == Instruction::And) {
2432     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2433       // X & 0xFFF0 is known to be a multiple of 16.
2434       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2435       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2436         return ConstantExpr::getShl(Result, 
2437                                     ConstantInt::get(Type::Int8Ty, Zeros));
2438     }
2439   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2440     // Only handle int->int casts.
2441     if (!CI->isIntegerCast())
2442       return Result;
2443     Value *Op = CI->getOperand(0);
2444     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2445   }    
2446   return Result;
2447 }
2448
2449 /// This function implements the transforms on rem instructions that work
2450 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2451 /// is used by the visitors to those instructions.
2452 /// @brief Transforms common to all three rem instructions
2453 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2454   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2455
2456   // 0 % X == 0, we don't need to preserve faults!
2457   if (Constant *LHS = dyn_cast<Constant>(Op0))
2458     if (LHS->isNullValue())
2459       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2460
2461   if (isa<UndefValue>(Op0))              // undef % X -> 0
2462     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2463   if (isa<UndefValue>(Op1))
2464     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2465
2466   // Handle cases involving: rem X, (select Cond, Y, Z)
2467   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2468     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2469     // the same basic block, then we replace the select with Y, and the
2470     // condition of the select with false (if the cond value is in the same
2471     // BB).  If the select has uses other than the div, this allows them to be
2472     // simplified also.
2473     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2474       if (ST->isNullValue()) {
2475         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2476         if (CondI && CondI->getParent() == I.getParent())
2477           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2478         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2479           I.setOperand(1, SI->getOperand(2));
2480         else
2481           UpdateValueUsesWith(SI, SI->getOperand(2));
2482         return &I;
2483       }
2484     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2485     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2486       if (ST->isNullValue()) {
2487         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2488         if (CondI && CondI->getParent() == I.getParent())
2489           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2490         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2491           I.setOperand(1, SI->getOperand(1));
2492         else
2493           UpdateValueUsesWith(SI, SI->getOperand(1));
2494         return &I;
2495       }
2496   }
2497
2498   return 0;
2499 }
2500
2501 /// This function implements the transforms common to both integer remainder
2502 /// instructions (urem and srem). It is called by the visitors to those integer
2503 /// remainder instructions.
2504 /// @brief Common integer remainder transforms
2505 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2506   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2507
2508   if (Instruction *common = commonRemTransforms(I))
2509     return common;
2510
2511   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2512     // X % 0 == undef, we don't need to preserve faults!
2513     if (RHS->equalsInt(0))
2514       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2515     
2516     if (RHS->equalsInt(1))  // X % 1 == 0
2517       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2518
2519     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2520       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2521         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2522           return R;
2523       } else if (isa<PHINode>(Op0I)) {
2524         if (Instruction *NV = FoldOpIntoPhi(I))
2525           return NV;
2526       }
2527       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2528       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2529         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2530     }
2531   }
2532
2533   return 0;
2534 }
2535
2536 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2537   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2538
2539   if (Instruction *common = commonIRemTransforms(I))
2540     return common;
2541   
2542   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2543     // X urem C^2 -> X and C
2544     // Check to see if this is an unsigned remainder with an exact power of 2,
2545     // if so, convert to a bitwise and.
2546     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2547       if (isPowerOf2_64(C->getZExtValue()))
2548         return BinaryOperator::createAnd(Op0, SubOne(C));
2549   }
2550
2551   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2552     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2553     if (RHSI->getOpcode() == Instruction::Shl &&
2554         isa<ConstantInt>(RHSI->getOperand(0))) {
2555       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2556       if (isPowerOf2_64(C1)) {
2557         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2558         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2559                                                                    "tmp"), I);
2560         return BinaryOperator::createAnd(Op0, Add);
2561       }
2562     }
2563   }
2564
2565   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2566   // where C1&C2 are powers of two.
2567   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2568     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2569       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2570         // STO == 0 and SFO == 0 handled above.
2571         if (isPowerOf2_64(STO->getZExtValue()) && 
2572             isPowerOf2_64(SFO->getZExtValue())) {
2573           Value *TrueAnd = InsertNewInstBefore(
2574             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2575           Value *FalseAnd = InsertNewInstBefore(
2576             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2577           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2578         }
2579       }
2580   }
2581   
2582   return 0;
2583 }
2584
2585 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2586   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2587
2588   if (Instruction *common = commonIRemTransforms(I))
2589     return common;
2590   
2591   if (Value *RHSNeg = dyn_castNegVal(Op1))
2592     if (!isa<ConstantInt>(RHSNeg) || 
2593         cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2594       // X % -Y -> X % Y
2595       AddUsesToWorkList(I);
2596       I.setOperand(1, RHSNeg);
2597       return &I;
2598     }
2599  
2600   // If the top bits of both operands are zero (i.e. we can prove they are
2601   // unsigned inputs), turn this into a urem.
2602   uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2603   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2604     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2605     return BinaryOperator::createURem(Op0, Op1, I.getName());
2606   }
2607
2608   return 0;
2609 }
2610
2611 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2612   return commonRemTransforms(I);
2613 }
2614
2615 // isMaxValueMinusOne - return true if this is Max-1
2616 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2617   if (isSigned) {
2618     // Calculate 0111111111..11111
2619     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2620     int64_t Val = INT64_MAX;             // All ones
2621     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
2622     return C->getSExtValue() == Val-1;
2623   }
2624   return C->getZExtValue() == C->getType()->getIntegerTypeMask()-1;
2625 }
2626
2627 // isMinValuePlusOne - return true if this is Min+1
2628 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2629   if (isSigned) {
2630     // Calculate 1111111111000000000000
2631     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2632     int64_t Val = -1;                    // All ones
2633     Val <<= TypeBits-1;                  // Shift over to the right spot
2634     return C->getSExtValue() == Val+1;
2635   }
2636   return C->getZExtValue() == 1; // unsigned
2637 }
2638
2639 // isOneBitSet - Return true if there is exactly one bit set in the specified
2640 // constant.
2641 static bool isOneBitSet(const ConstantInt *CI) {
2642   uint64_t V = CI->getZExtValue();
2643   return V && (V & (V-1)) == 0;
2644 }
2645
2646 #if 0   // Currently unused
2647 // isLowOnes - Return true if the constant is of the form 0+1+.
2648 static bool isLowOnes(const ConstantInt *CI) {
2649   uint64_t V = CI->getZExtValue();
2650
2651   // There won't be bits set in parts that the type doesn't contain.
2652   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2653
2654   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2655   return U && V && (U & V) == 0;
2656 }
2657 #endif
2658
2659 // isHighOnes - Return true if the constant is of the form 1+0+.
2660 // This is the same as lowones(~X).
2661 static bool isHighOnes(const ConstantInt *CI) {
2662   uint64_t V = ~CI->getZExtValue();
2663   if (~V == 0) return false;  // 0's does not match "1+"
2664
2665   // There won't be bits set in parts that the type doesn't contain.
2666   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2667
2668   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2669   return U && V && (U & V) == 0;
2670 }
2671
2672 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2673 /// are carefully arranged to allow folding of expressions such as:
2674 ///
2675 ///      (A < B) | (A > B) --> (A != B)
2676 ///
2677 /// Note that this is only valid if the first and second predicates have the
2678 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2679 ///
2680 /// Three bits are used to represent the condition, as follows:
2681 ///   0  A > B
2682 ///   1  A == B
2683 ///   2  A < B
2684 ///
2685 /// <=>  Value  Definition
2686 /// 000     0   Always false
2687 /// 001     1   A >  B
2688 /// 010     2   A == B
2689 /// 011     3   A >= B
2690 /// 100     4   A <  B
2691 /// 101     5   A != B
2692 /// 110     6   A <= B
2693 /// 111     7   Always true
2694 ///  
2695 static unsigned getICmpCode(const ICmpInst *ICI) {
2696   switch (ICI->getPredicate()) {
2697     // False -> 0
2698   case ICmpInst::ICMP_UGT: return 1;  // 001
2699   case ICmpInst::ICMP_SGT: return 1;  // 001
2700   case ICmpInst::ICMP_EQ:  return 2;  // 010
2701   case ICmpInst::ICMP_UGE: return 3;  // 011
2702   case ICmpInst::ICMP_SGE: return 3;  // 011
2703   case ICmpInst::ICMP_ULT: return 4;  // 100
2704   case ICmpInst::ICMP_SLT: return 4;  // 100
2705   case ICmpInst::ICMP_NE:  return 5;  // 101
2706   case ICmpInst::ICMP_ULE: return 6;  // 110
2707   case ICmpInst::ICMP_SLE: return 6;  // 110
2708     // True -> 7
2709   default:
2710     assert(0 && "Invalid ICmp predicate!");
2711     return 0;
2712   }
2713 }
2714
2715 /// getICmpValue - This is the complement of getICmpCode, which turns an
2716 /// opcode and two operands into either a constant true or false, or a brand 
2717 /// new /// ICmp instruction. The sign is passed in to determine which kind
2718 /// of predicate to use in new icmp instructions.
2719 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2720   switch (code) {
2721   default: assert(0 && "Illegal ICmp code!");
2722   case  0: return ConstantInt::getFalse();
2723   case  1: 
2724     if (sign)
2725       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2726     else
2727       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2728   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
2729   case  3: 
2730     if (sign)
2731       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2732     else
2733       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2734   case  4: 
2735     if (sign)
2736       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2737     else
2738       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2739   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
2740   case  6: 
2741     if (sign)
2742       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2743     else
2744       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2745   case  7: return ConstantInt::getTrue();
2746   }
2747 }
2748
2749 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2750   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2751     (ICmpInst::isSignedPredicate(p1) && 
2752      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2753     (ICmpInst::isSignedPredicate(p2) && 
2754      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2755 }
2756
2757 namespace { 
2758 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2759 struct FoldICmpLogical {
2760   InstCombiner &IC;
2761   Value *LHS, *RHS;
2762   ICmpInst::Predicate pred;
2763   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2764     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2765       pred(ICI->getPredicate()) {}
2766   bool shouldApply(Value *V) const {
2767     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2768       if (PredicatesFoldable(pred, ICI->getPredicate()))
2769         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2770                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2771     return false;
2772   }
2773   Instruction *apply(Instruction &Log) const {
2774     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2775     if (ICI->getOperand(0) != LHS) {
2776       assert(ICI->getOperand(1) == LHS);
2777       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
2778     }
2779
2780     unsigned LHSCode = getICmpCode(ICI);
2781     unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
2782     unsigned Code;
2783     switch (Log.getOpcode()) {
2784     case Instruction::And: Code = LHSCode & RHSCode; break;
2785     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2786     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2787     default: assert(0 && "Illegal logical opcode!"); return 0;
2788     }
2789
2790     Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
2791     if (Instruction *I = dyn_cast<Instruction>(RV))
2792       return I;
2793     // Otherwise, it's a constant boolean value...
2794     return IC.ReplaceInstUsesWith(Log, RV);
2795   }
2796 };
2797 } // end anonymous namespace
2798
2799 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2800 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2801 // guaranteed to be either a shift instruction or a binary operator.
2802 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2803                                     ConstantInt *OpRHS,
2804                                     ConstantInt *AndRHS,
2805                                     BinaryOperator &TheAnd) {
2806   Value *X = Op->getOperand(0);
2807   Constant *Together = 0;
2808   if (!isa<ShiftInst>(Op))
2809     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2810
2811   switch (Op->getOpcode()) {
2812   case Instruction::Xor:
2813     if (Op->hasOneUse()) {
2814       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2815       std::string OpName = Op->getName(); Op->setName("");
2816       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2817       InsertNewInstBefore(And, TheAnd);
2818       return BinaryOperator::createXor(And, Together);
2819     }
2820     break;
2821   case Instruction::Or:
2822     if (Together == AndRHS) // (X | C) & C --> C
2823       return ReplaceInstUsesWith(TheAnd, AndRHS);
2824
2825     if (Op->hasOneUse() && Together != OpRHS) {
2826       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2827       std::string Op0Name = Op->getName(); Op->setName("");
2828       Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2829       InsertNewInstBefore(Or, TheAnd);
2830       return BinaryOperator::createAnd(Or, AndRHS);
2831     }
2832     break;
2833   case Instruction::Add:
2834     if (Op->hasOneUse()) {
2835       // Adding a one to a single bit bit-field should be turned into an XOR
2836       // of the bit.  First thing to check is to see if this AND is with a
2837       // single bit constant.
2838       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2839
2840       // Clear bits that are not part of the constant.
2841       AndRHSV &= AndRHS->getType()->getIntegerTypeMask();
2842
2843       // If there is only one bit set...
2844       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2845         // Ok, at this point, we know that we are masking the result of the
2846         // ADD down to exactly one bit.  If the constant we are adding has
2847         // no bits set below this bit, then we can eliminate the ADD.
2848         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2849
2850         // Check to see if any bits below the one bit set in AndRHSV are set.
2851         if ((AddRHS & (AndRHSV-1)) == 0) {
2852           // If not, the only thing that can effect the output of the AND is
2853           // the bit specified by AndRHSV.  If that bit is set, the effect of
2854           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2855           // no effect.
2856           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2857             TheAnd.setOperand(0, X);
2858             return &TheAnd;
2859           } else {
2860             std::string Name = Op->getName(); Op->setName("");
2861             // Pull the XOR out of the AND.
2862             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2863             InsertNewInstBefore(NewAnd, TheAnd);
2864             return BinaryOperator::createXor(NewAnd, AndRHS);
2865           }
2866         }
2867       }
2868     }
2869     break;
2870
2871   case Instruction::Shl: {
2872     // We know that the AND will not produce any of the bits shifted in, so if
2873     // the anded constant includes them, clear them now!
2874     //
2875     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2876     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2877     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2878
2879     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2880       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2881     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2882       TheAnd.setOperand(1, CI);
2883       return &TheAnd;
2884     }
2885     break;
2886   }
2887   case Instruction::LShr:
2888   {
2889     // We know that the AND will not produce any of the bits shifted in, so if
2890     // the anded constant includes them, clear them now!  This only applies to
2891     // unsigned shifts, because a signed shr may bring in set bits!
2892     //
2893     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2894     Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2895     Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2896
2897     if (CI == ShrMask) {   // Masking out bits that the shift already masks.
2898       return ReplaceInstUsesWith(TheAnd, Op);
2899     } else if (CI != AndRHS) {
2900       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
2901       return &TheAnd;
2902     }
2903     break;
2904   }
2905   case Instruction::AShr:
2906     // Signed shr.
2907     // See if this is shifting in some sign extension, then masking it out
2908     // with an and.
2909     if (Op->hasOneUse()) {
2910       Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2911       Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2912       Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2913       if (C == AndRHS) {          // Masking out bits shifted in.
2914         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
2915         // Make the argument unsigned.
2916         Value *ShVal = Op->getOperand(0);
2917         ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal, 
2918                                     OpRHS, Op->getName()), TheAnd);
2919         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
2920       }
2921     }
2922     break;
2923   }
2924   return 0;
2925 }
2926
2927
2928 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2929 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
2930 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
2931 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
2932 /// insert new instructions.
2933 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2934                                            bool isSigned, bool Inside, 
2935                                            Instruction &IB) {
2936   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
2937             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
2938          "Lo is not <= Hi in range emission code!");
2939     
2940   if (Inside) {
2941     if (Lo == Hi)  // Trivially false.
2942       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
2943
2944     // V >= Min && V < Hi --> V < Hi
2945     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2946     ICmpInst::Predicate pred = (isSigned ? 
2947         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2948       return new ICmpInst(pred, V, Hi);
2949     }
2950
2951     // Emit V-Lo <u Hi-Lo
2952     Constant *NegLo = ConstantExpr::getNeg(Lo);
2953     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2954     InsertNewInstBefore(Add, IB);
2955     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2956     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
2957   }
2958
2959   if (Lo == Hi)  // Trivially true.
2960     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
2961
2962   // V < Min || V >= Hi ->'V > Hi-1'
2963   Hi = SubOne(cast<ConstantInt>(Hi));
2964   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2965     ICmpInst::Predicate pred = (isSigned ? 
2966         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
2967     return new ICmpInst(pred, V, Hi);
2968   }
2969
2970   // Emit V-Lo > Hi-1-Lo
2971   Constant *NegLo = ConstantExpr::getNeg(Lo);
2972   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2973   InsertNewInstBefore(Add, IB);
2974   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
2975   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
2976 }
2977
2978 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2979 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
2980 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
2981 // not, since all 1s are not contiguous.
2982 static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
2983   uint64_t V = Val->getZExtValue();
2984   if (!isShiftedMask_64(V)) return false;
2985
2986   // look for the first zero bit after the run of ones
2987   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2988   // look for the first non-zero bit
2989   ME = 64-CountLeadingZeros_64(V);
2990   return true;
2991 }
2992
2993
2994
2995 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2996 /// where isSub determines whether the operator is a sub.  If we can fold one of
2997 /// the following xforms:
2998 /// 
2999 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3000 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3001 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3002 ///
3003 /// return (A +/- B).
3004 ///
3005 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3006                                         ConstantInt *Mask, bool isSub,
3007                                         Instruction &I) {
3008   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3009   if (!LHSI || LHSI->getNumOperands() != 2 ||
3010       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3011
3012   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3013
3014   switch (LHSI->getOpcode()) {
3015   default: return 0;
3016   case Instruction::And:
3017     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3018       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3019       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3020         break;
3021
3022       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3023       // part, we don't need any explicit masks to take them out of A.  If that
3024       // is all N is, ignore it.
3025       unsigned MB, ME;
3026       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3027         uint64_t Mask = RHS->getType()->getIntegerTypeMask();
3028         Mask >>= 64-MB+1;
3029         if (MaskedValueIsZero(RHS, Mask))
3030           break;
3031       }
3032     }
3033     return 0;
3034   case Instruction::Or:
3035   case Instruction::Xor:
3036     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3037     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3038         ConstantExpr::getAnd(N, Mask)->isNullValue())
3039       break;
3040     return 0;
3041   }
3042   
3043   Instruction *New;
3044   if (isSub)
3045     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3046   else
3047     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3048   return InsertNewInstBefore(New, I);
3049 }
3050
3051 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3052   bool Changed = SimplifyCommutative(I);
3053   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3054
3055   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3056     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3057
3058   // and X, X = X
3059   if (Op0 == Op1)
3060     return ReplaceInstUsesWith(I, Op1);
3061
3062   // See if we can simplify any instructions used by the instruction whose sole 
3063   // purpose is to compute bits we don't care about.
3064   uint64_t KnownZero, KnownOne;
3065   if (!isa<PackedType>(I.getType()) &&
3066       SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
3067                            KnownZero, KnownOne))
3068     return &I;
3069   
3070   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3071     uint64_t AndRHSMask = AndRHS->getZExtValue();
3072     uint64_t TypeMask = Op0->getType()->getIntegerTypeMask();
3073     uint64_t NotAndRHS = AndRHSMask^TypeMask;
3074
3075     // Optimize a variety of ((val OP C1) & C2) combinations...
3076     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3077       Instruction *Op0I = cast<Instruction>(Op0);
3078       Value *Op0LHS = Op0I->getOperand(0);
3079       Value *Op0RHS = Op0I->getOperand(1);
3080       switch (Op0I->getOpcode()) {
3081       case Instruction::Xor:
3082       case Instruction::Or:
3083         // If the mask is only needed on one incoming arm, push it up.
3084         if (Op0I->hasOneUse()) {
3085           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3086             // Not masking anything out for the LHS, move to RHS.
3087             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3088                                                    Op0RHS->getName()+".masked");
3089             InsertNewInstBefore(NewRHS, I);
3090             return BinaryOperator::create(
3091                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3092           }
3093           if (!isa<Constant>(Op0RHS) &&
3094               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3095             // Not masking anything out for the RHS, move to LHS.
3096             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3097                                                    Op0LHS->getName()+".masked");
3098             InsertNewInstBefore(NewLHS, I);
3099             return BinaryOperator::create(
3100                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3101           }
3102         }
3103
3104         break;
3105       case Instruction::Add:
3106         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3107         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3108         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3109         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3110           return BinaryOperator::createAnd(V, AndRHS);
3111         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3112           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3113         break;
3114
3115       case Instruction::Sub:
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, true, I))
3120           return BinaryOperator::createAnd(V, AndRHS);
3121         break;
3122       }
3123
3124       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3125         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3126           return Res;
3127     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3128       // If this is an integer truncation or change from signed-to-unsigned, and
3129       // if the source is an and/or with immediate, transform it.  This
3130       // frequently occurs for bitfield accesses.
3131       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3132         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3133             CastOp->getNumOperands() == 2)
3134           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3135             if (CastOp->getOpcode() == Instruction::And) {
3136               // Change: and (cast (and X, C1) to T), C2
3137               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3138               // This will fold the two constants together, which may allow 
3139               // other simplifications.
3140               Instruction *NewCast = CastInst::createTruncOrBitCast(
3141                 CastOp->getOperand(0), I.getType(), 
3142                 CastOp->getName()+".shrunk");
3143               NewCast = InsertNewInstBefore(NewCast, I);
3144               // trunc_or_bitcast(C1)&C2
3145               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3146               C3 = ConstantExpr::getAnd(C3, AndRHS);
3147               return BinaryOperator::createAnd(NewCast, C3);
3148             } else if (CastOp->getOpcode() == Instruction::Or) {
3149               // Change: and (cast (or X, C1) to T), C2
3150               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3151               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3152               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3153                 return ReplaceInstUsesWith(I, AndRHS);
3154             }
3155       }
3156     }
3157
3158     // Try to fold constant and into select arguments.
3159     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3160       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3161         return R;
3162     if (isa<PHINode>(Op0))
3163       if (Instruction *NV = FoldOpIntoPhi(I))
3164         return NV;
3165   }
3166
3167   Value *Op0NotVal = dyn_castNotVal(Op0);
3168   Value *Op1NotVal = dyn_castNotVal(Op1);
3169
3170   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3171     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3172
3173   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3174   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3175     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3176                                                I.getName()+".demorgan");
3177     InsertNewInstBefore(Or, I);
3178     return BinaryOperator::createNot(Or);
3179   }
3180   
3181   {
3182     Value *A = 0, *B = 0;
3183     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3184       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3185         return ReplaceInstUsesWith(I, Op1);
3186     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3187       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3188         return ReplaceInstUsesWith(I, Op0);
3189     
3190     if (Op0->hasOneUse() &&
3191         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3192       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3193         I.swapOperands();     // Simplify below
3194         std::swap(Op0, Op1);
3195       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3196         cast<BinaryOperator>(Op0)->swapOperands();
3197         I.swapOperands();     // Simplify below
3198         std::swap(Op0, Op1);
3199       }
3200     }
3201     if (Op1->hasOneUse() &&
3202         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3203       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3204         cast<BinaryOperator>(Op1)->swapOperands();
3205         std::swap(A, B);
3206       }
3207       if (A == Op0) {                                // A&(A^B) -> A & ~B
3208         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3209         InsertNewInstBefore(NotB, I);
3210         return BinaryOperator::createAnd(A, NotB);
3211       }
3212     }
3213   }
3214   
3215   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3216     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3217     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3218       return R;
3219
3220     Value *LHSVal, *RHSVal;
3221     ConstantInt *LHSCst, *RHSCst;
3222     ICmpInst::Predicate LHSCC, RHSCC;
3223     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3224       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3225         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3226             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3227             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3228             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3229             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3230             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3231           // Ensure that the larger constant is on the RHS.
3232           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3233             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3234           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3235           ICmpInst *LHS = cast<ICmpInst>(Op0);
3236           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3237             std::swap(LHS, RHS);
3238             std::swap(LHSCst, RHSCst);
3239             std::swap(LHSCC, RHSCC);
3240           }
3241
3242           // At this point, we know we have have two icmp instructions
3243           // comparing a value against two constants and and'ing the result
3244           // together.  Because of the above check, we know that we only have
3245           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3246           // (from the FoldICmpLogical check above), that the two constants 
3247           // are not equal and that the larger constant is on the RHS
3248           assert(LHSCst != RHSCst && "Compares not folded above?");
3249
3250           switch (LHSCC) {
3251           default: assert(0 && "Unknown integer condition code!");
3252           case ICmpInst::ICMP_EQ:
3253             switch (RHSCC) {
3254             default: assert(0 && "Unknown integer condition code!");
3255             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3256             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3257             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3258               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3259             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3260             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3261             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3262               return ReplaceInstUsesWith(I, LHS);
3263             }
3264           case ICmpInst::ICMP_NE:
3265             switch (RHSCC) {
3266             default: assert(0 && "Unknown integer condition code!");
3267             case ICmpInst::ICMP_ULT:
3268               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3269                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3270               break;                        // (X != 13 & X u< 15) -> no change
3271             case ICmpInst::ICMP_SLT:
3272               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3273                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3274               break;                        // (X != 13 & X s< 15) -> no change
3275             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3276             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3277             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3278               return ReplaceInstUsesWith(I, RHS);
3279             case ICmpInst::ICMP_NE:
3280               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3281                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3282                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3283                                                       LHSVal->getName()+".off");
3284                 InsertNewInstBefore(Add, I);
3285                 return new ICmpInst(ICmpInst::ICMP_UGT, Add, AddCST);
3286               }
3287               break;                        // (X != 13 & X != 15) -> no change
3288             }
3289             break;
3290           case ICmpInst::ICMP_ULT:
3291             switch (RHSCC) {
3292             default: assert(0 && "Unknown integer condition code!");
3293             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3294             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3295               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3296             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3297               break;
3298             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3299             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3300               return ReplaceInstUsesWith(I, LHS);
3301             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3302               break;
3303             }
3304             break;
3305           case ICmpInst::ICMP_SLT:
3306             switch (RHSCC) {
3307             default: assert(0 && "Unknown integer condition code!");
3308             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3309             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3310               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3311             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3312               break;
3313             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3314             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3315               return ReplaceInstUsesWith(I, LHS);
3316             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3317               break;
3318             }
3319             break;
3320           case ICmpInst::ICMP_UGT:
3321             switch (RHSCC) {
3322             default: assert(0 && "Unknown integer condition code!");
3323             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3324               return ReplaceInstUsesWith(I, LHS);
3325             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3326               return ReplaceInstUsesWith(I, RHS);
3327             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3328               break;
3329             case ICmpInst::ICMP_NE:
3330               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3331                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3332               break;                        // (X u> 13 & X != 15) -> no change
3333             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3334               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3335                                      true, I);
3336             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3337               break;
3338             }
3339             break;
3340           case ICmpInst::ICMP_SGT:
3341             switch (RHSCC) {
3342             default: assert(0 && "Unknown integer condition code!");
3343             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
3344               return ReplaceInstUsesWith(I, LHS);
3345             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3346               return ReplaceInstUsesWith(I, RHS);
3347             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3348               break;
3349             case ICmpInst::ICMP_NE:
3350               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3351                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3352               break;                        // (X s> 13 & X != 15) -> no change
3353             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3354               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3355                                      true, I);
3356             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3357               break;
3358             }
3359             break;
3360           }
3361         }
3362   }
3363
3364   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3365   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3366     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3367       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3368         const Type *SrcTy = Op0C->getOperand(0)->getType();
3369         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3370             // Only do this if the casts both really cause code to be generated.
3371             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3372                               I.getType(), TD) &&
3373             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3374                               I.getType(), TD)) {
3375           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3376                                                          Op1C->getOperand(0),
3377                                                          I.getName());
3378           InsertNewInstBefore(NewOp, I);
3379           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3380         }
3381       }
3382     
3383   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3384   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3385     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3386       if (SI0->getOpcode() == SI1->getOpcode() && 
3387           SI0->getOperand(1) == SI1->getOperand(1) &&
3388           (SI0->hasOneUse() || SI1->hasOneUse())) {
3389         Instruction *NewOp =
3390           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3391                                                         SI1->getOperand(0),
3392                                                         SI0->getName()), I);
3393         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3394       }
3395   }
3396
3397   return Changed ? &I : 0;
3398 }
3399
3400 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3401 /// in the result.  If it does, and if the specified byte hasn't been filled in
3402 /// yet, fill it in and return false.
3403 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3404   Instruction *I = dyn_cast<Instruction>(V);
3405   if (I == 0) return true;
3406
3407   // If this is an or instruction, it is an inner node of the bswap.
3408   if (I->getOpcode() == Instruction::Or)
3409     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3410            CollectBSwapParts(I->getOperand(1), ByteValues);
3411   
3412   // If this is a shift by a constant int, and it is "24", then its operand
3413   // defines a byte.  We only handle unsigned types here.
3414   if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3415     // Not shifting the entire input by N-1 bytes?
3416     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3417         8*(ByteValues.size()-1))
3418       return true;
3419     
3420     unsigned DestNo;
3421     if (I->getOpcode() == Instruction::Shl) {
3422       // X << 24 defines the top byte with the lowest of the input bytes.
3423       DestNo = ByteValues.size()-1;
3424     } else {
3425       // X >>u 24 defines the low byte with the highest of the input bytes.
3426       DestNo = 0;
3427     }
3428     
3429     // If the destination byte value is already defined, the values are or'd
3430     // together, which isn't a bswap (unless it's an or of the same bits).
3431     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3432       return true;
3433     ByteValues[DestNo] = I->getOperand(0);
3434     return false;
3435   }
3436   
3437   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3438   // don't have this.
3439   Value *Shift = 0, *ShiftLHS = 0;
3440   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3441   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3442       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3443     return true;
3444   Instruction *SI = cast<Instruction>(Shift);
3445
3446   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3447   if (ShiftAmt->getZExtValue() & 7 ||
3448       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3449     return true;
3450   
3451   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3452   unsigned DestByte;
3453   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3454     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3455       break;
3456   // Unknown mask for bswap.
3457   if (DestByte == ByteValues.size()) return true;
3458   
3459   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3460   unsigned SrcByte;
3461   if (SI->getOpcode() == Instruction::Shl)
3462     SrcByte = DestByte - ShiftBytes;
3463   else
3464     SrcByte = DestByte + ShiftBytes;
3465   
3466   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3467   if (SrcByte != ByteValues.size()-DestByte-1)
3468     return true;
3469   
3470   // If the destination byte value is already defined, the values are or'd
3471   // together, which isn't a bswap (unless it's an or of the same bits).
3472   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3473     return true;
3474   ByteValues[DestByte] = SI->getOperand(0);
3475   return false;
3476 }
3477
3478 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3479 /// If so, insert the new bswap intrinsic and return it.
3480 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3481   // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3482   if (I.getType() == Type::Int8Ty)
3483     return 0;
3484   
3485   /// ByteValues - For each byte of the result, we keep track of which value
3486   /// defines each byte.
3487   std::vector<Value*> ByteValues;
3488   ByteValues.resize(TD->getTypeSize(I.getType()));
3489     
3490   // Try to find all the pieces corresponding to the bswap.
3491   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3492       CollectBSwapParts(I.getOperand(1), ByteValues))
3493     return 0;
3494   
3495   // Check to see if all of the bytes come from the same value.
3496   Value *V = ByteValues[0];
3497   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3498   
3499   // Check to make sure that all of the bytes come from the same value.
3500   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3501     if (ByteValues[i] != V)
3502       return 0;
3503     
3504   // If they do then *success* we can turn this into a bswap.  Figure out what
3505   // bswap to make it into.
3506   Module *M = I.getParent()->getParent()->getParent();
3507   const char *FnName = 0;
3508   if (I.getType() == Type::Int16Ty)
3509     FnName = "llvm.bswap.i16";
3510   else if (I.getType() == Type::Int32Ty)
3511     FnName = "llvm.bswap.i32";
3512   else if (I.getType() == Type::Int64Ty)
3513     FnName = "llvm.bswap.i64";
3514   else
3515     assert(0 && "Unknown integer type!");
3516   Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3517   return new CallInst(F, V);
3518 }
3519
3520
3521 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3522   bool Changed = SimplifyCommutative(I);
3523   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3524
3525   if (isa<UndefValue>(Op1))
3526     return ReplaceInstUsesWith(I,                         // X | undef -> -1
3527                                ConstantInt::getAllOnesValue(I.getType()));
3528
3529   // or X, X = X
3530   if (Op0 == Op1)
3531     return ReplaceInstUsesWith(I, Op0);
3532
3533   // See if we can simplify any instructions used by the instruction whose sole 
3534   // purpose is to compute bits we don't care about.
3535   uint64_t KnownZero, KnownOne;
3536   if (!isa<PackedType>(I.getType()) &&
3537       SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
3538                            KnownZero, KnownOne))
3539     return &I;
3540   
3541   // or X, -1 == -1
3542   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3543     ConstantInt *C1 = 0; Value *X = 0;
3544     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3545     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3546       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3547       Op0->setName("");
3548       InsertNewInstBefore(Or, I);
3549       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3550     }
3551
3552     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3553     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3554       std::string Op0Name = Op0->getName(); Op0->setName("");
3555       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3556       InsertNewInstBefore(Or, I);
3557       return BinaryOperator::createXor(Or,
3558                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3559     }
3560
3561     // Try to fold constant and into select arguments.
3562     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3563       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3564         return R;
3565     if (isa<PHINode>(Op0))
3566       if (Instruction *NV = FoldOpIntoPhi(I))
3567         return NV;
3568   }
3569
3570   Value *A = 0, *B = 0;
3571   ConstantInt *C1 = 0, *C2 = 0;
3572
3573   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3574     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3575       return ReplaceInstUsesWith(I, Op1);
3576   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3577     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3578       return ReplaceInstUsesWith(I, Op0);
3579
3580   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3581   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3582   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3583       match(Op1, m_Or(m_Value(), m_Value())) ||
3584       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3585        match(Op1, m_Shift(m_Value(), m_Value())))) {
3586     if (Instruction *BSwap = MatchBSwap(I))
3587       return BSwap;
3588   }
3589   
3590   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3591   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3592       MaskedValueIsZero(Op1, C1->getZExtValue())) {
3593     Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3594     Op0->setName("");
3595     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3596   }
3597
3598   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3599   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3600       MaskedValueIsZero(Op0, C1->getZExtValue())) {
3601     Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3602     Op0->setName("");
3603     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3604   }
3605
3606   // (A & C1)|(B & C2)
3607   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3608       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3609
3610     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3611       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3612
3613
3614     // If we have: ((V + N) & C1) | (V & C2)
3615     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3616     // replace with V+N.
3617     if (C1 == ConstantExpr::getNot(C2)) {
3618       Value *V1 = 0, *V2 = 0;
3619       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3620           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3621         // Add commutes, try both ways.
3622         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3623           return ReplaceInstUsesWith(I, A);
3624         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3625           return ReplaceInstUsesWith(I, A);
3626       }
3627       // Or commutes, try both ways.
3628       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3629           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3630         // Add commutes, try both ways.
3631         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3632           return ReplaceInstUsesWith(I, B);
3633         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3634           return ReplaceInstUsesWith(I, B);
3635       }
3636     }
3637   }
3638   
3639   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3640   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3641     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3642       if (SI0->getOpcode() == SI1->getOpcode() && 
3643           SI0->getOperand(1) == SI1->getOperand(1) &&
3644           (SI0->hasOneUse() || SI1->hasOneUse())) {
3645         Instruction *NewOp =
3646         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3647                                                      SI1->getOperand(0),
3648                                                      SI0->getName()), I);
3649         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3650       }
3651   }
3652
3653   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3654     if (A == Op1)   // ~A | A == -1
3655       return ReplaceInstUsesWith(I,
3656                                 ConstantInt::getAllOnesValue(I.getType()));
3657   } else {
3658     A = 0;
3659   }
3660   // Note, A is still live here!
3661   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3662     if (Op0 == B)
3663       return ReplaceInstUsesWith(I,
3664                                 ConstantInt::getAllOnesValue(I.getType()));
3665
3666     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3667     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3668       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3669                                               I.getName()+".demorgan"), I);
3670       return BinaryOperator::createNot(And);
3671     }
3672   }
3673
3674   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3675   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3676     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3677       return R;
3678
3679     Value *LHSVal, *RHSVal;
3680     ConstantInt *LHSCst, *RHSCst;
3681     ICmpInst::Predicate LHSCC, RHSCC;
3682     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3683       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3684         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
3685             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3686             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3687             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3688             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3689             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3690           // Ensure that the larger constant is on the RHS.
3691           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3692             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3693           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3694           ICmpInst *LHS = cast<ICmpInst>(Op0);
3695           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3696             std::swap(LHS, RHS);
3697             std::swap(LHSCst, RHSCst);
3698             std::swap(LHSCC, RHSCC);
3699           }
3700
3701           // At this point, we know we have have two icmp instructions
3702           // comparing a value against two constants and or'ing the result
3703           // together.  Because of the above check, we know that we only have
3704           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3705           // FoldICmpLogical check above), that the two constants are not
3706           // equal.
3707           assert(LHSCst != RHSCst && "Compares not folded above?");
3708
3709           switch (LHSCC) {
3710           default: assert(0 && "Unknown integer condition code!");
3711           case ICmpInst::ICMP_EQ:
3712             switch (RHSCC) {
3713             default: assert(0 && "Unknown integer condition code!");
3714             case ICmpInst::ICMP_EQ:
3715               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3716                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3717                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3718                                                       LHSVal->getName()+".off");
3719                 InsertNewInstBefore(Add, I);
3720                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3721                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3722               }
3723               break;                         // (X == 13 | X == 15) -> no change
3724             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
3725             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
3726               break;
3727             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
3728             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
3729             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
3730               return ReplaceInstUsesWith(I, RHS);
3731             }
3732             break;
3733           case ICmpInst::ICMP_NE:
3734             switch (RHSCC) {
3735             default: assert(0 && "Unknown integer condition code!");
3736             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
3737             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
3738             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
3739               return ReplaceInstUsesWith(I, LHS);
3740             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
3741             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
3742             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
3743               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3744             }
3745             break;
3746           case ICmpInst::ICMP_ULT:
3747             switch (RHSCC) {
3748             default: assert(0 && "Unknown integer condition code!");
3749             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
3750               break;
3751             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
3752               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
3753                                      false, I);
3754             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
3755               break;
3756             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
3757             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
3758               return ReplaceInstUsesWith(I, RHS);
3759             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
3760               break;
3761             }
3762             break;
3763           case ICmpInst::ICMP_SLT:
3764             switch (RHSCC) {
3765             default: assert(0 && "Unknown integer condition code!");
3766             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
3767               break;
3768             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
3769               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
3770                                      false, I);
3771             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
3772               break;
3773             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
3774             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
3775               return ReplaceInstUsesWith(I, RHS);
3776             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
3777               break;
3778             }
3779             break;
3780           case ICmpInst::ICMP_UGT:
3781             switch (RHSCC) {
3782             default: assert(0 && "Unknown integer condition code!");
3783             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
3784             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
3785               return ReplaceInstUsesWith(I, LHS);
3786             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
3787               break;
3788             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
3789             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
3790               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3791             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
3792               break;
3793             }
3794             break;
3795           case ICmpInst::ICMP_SGT:
3796             switch (RHSCC) {
3797             default: assert(0 && "Unknown integer condition code!");
3798             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
3799             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
3800               return ReplaceInstUsesWith(I, LHS);
3801             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
3802               break;
3803             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
3804             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
3805               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3806             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
3807               break;
3808             }
3809             break;
3810           }
3811         }
3812   }
3813     
3814   // fold (or (cast A), (cast B)) -> (cast (or A, B))
3815   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3816     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3817       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3818         const Type *SrcTy = Op0C->getOperand(0)->getType();
3819         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3820             // Only do this if the casts both really cause code to be generated.
3821             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3822                               I.getType(), TD) &&
3823             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3824                               I.getType(), TD)) {
3825           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3826                                                         Op1C->getOperand(0),
3827                                                         I.getName());
3828           InsertNewInstBefore(NewOp, I);
3829           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3830         }
3831       }
3832       
3833
3834   return Changed ? &I : 0;
3835 }
3836
3837 // XorSelf - Implements: X ^ X --> 0
3838 struct XorSelf {
3839   Value *RHS;
3840   XorSelf(Value *rhs) : RHS(rhs) {}
3841   bool shouldApply(Value *LHS) const { return LHS == RHS; }
3842   Instruction *apply(BinaryOperator &Xor) const {
3843     return &Xor;
3844   }
3845 };
3846
3847
3848 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3849   bool Changed = SimplifyCommutative(I);
3850   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3851
3852   if (isa<UndefValue>(Op1))
3853     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
3854
3855   // xor X, X = 0, even if X is nested in a sequence of Xor's.
3856   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3857     assert(Result == &I && "AssociativeOpt didn't work?");
3858     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3859   }
3860   
3861   // See if we can simplify any instructions used by the instruction whose sole 
3862   // purpose is to compute bits we don't care about.
3863   uint64_t KnownZero, KnownOne;
3864   if (!isa<PackedType>(I.getType()) &&
3865       SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
3866                            KnownZero, KnownOne))
3867     return &I;
3868
3869   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3870     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3871     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3872       if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
3873         return new ICmpInst(ICI->getInversePredicate(),
3874                             ICI->getOperand(0), ICI->getOperand(1));
3875
3876     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3877       // ~(c-X) == X-c-1 == X+(-c-1)
3878       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3879         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3880           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3881           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3882                                               ConstantInt::get(I.getType(), 1));
3883           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3884         }
3885
3886       // ~(~X & Y) --> (X | ~Y)
3887       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3888         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3889         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3890           Instruction *NotY =
3891             BinaryOperator::createNot(Op0I->getOperand(1),
3892                                       Op0I->getOperand(1)->getName()+".not");
3893           InsertNewInstBefore(NotY, I);
3894           return BinaryOperator::createOr(Op0NotVal, NotY);
3895         }
3896       }
3897
3898       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3899         if (Op0I->getOpcode() == Instruction::Add) {
3900           // ~(X-c) --> (-c-1)-X
3901           if (RHS->isAllOnesValue()) {
3902             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3903             return BinaryOperator::createSub(
3904                            ConstantExpr::getSub(NegOp0CI,
3905                                              ConstantInt::get(I.getType(), 1)),
3906                                           Op0I->getOperand(0));
3907           }
3908         } else if (Op0I->getOpcode() == Instruction::Or) {
3909           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3910           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3911             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3912             // Anything in both C1 and C2 is known to be zero, remove it from
3913             // NewRHS.
3914             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3915             NewRHS = ConstantExpr::getAnd(NewRHS, 
3916                                           ConstantExpr::getNot(CommonBits));
3917             WorkList.push_back(Op0I);
3918             I.setOperand(0, Op0I->getOperand(0));
3919             I.setOperand(1, NewRHS);
3920             return &I;
3921           }
3922         }
3923     }
3924
3925     // Try to fold constant and into select arguments.
3926     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3927       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3928         return R;
3929     if (isa<PHINode>(Op0))
3930       if (Instruction *NV = FoldOpIntoPhi(I))
3931         return NV;
3932   }
3933
3934   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
3935     if (X == Op1)
3936       return ReplaceInstUsesWith(I,
3937                                 ConstantInt::getAllOnesValue(I.getType()));
3938
3939   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
3940     if (X == Op0)
3941       return ReplaceInstUsesWith(I,
3942                                 ConstantInt::getAllOnesValue(I.getType()));
3943
3944   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3945     if (Op1I->getOpcode() == Instruction::Or) {
3946       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
3947         Op1I->swapOperands();
3948         I.swapOperands();
3949         std::swap(Op0, Op1);
3950       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
3951         I.swapOperands();     // Simplified below.
3952         std::swap(Op0, Op1);
3953       }
3954     } else if (Op1I->getOpcode() == Instruction::Xor) {
3955       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
3956         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3957       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
3958         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3959     } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3960       if (Op1I->getOperand(0) == Op0)                      // A^(A&B) -> A^(B&A)
3961         Op1I->swapOperands();
3962       if (Op0 == Op1I->getOperand(1)) {                    // A^(B&A) -> (B&A)^A
3963         I.swapOperands();     // Simplified below.
3964         std::swap(Op0, Op1);
3965       }
3966     }
3967
3968   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3969     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3970       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
3971         Op0I->swapOperands();
3972       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
3973         Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3974         InsertNewInstBefore(NotB, I);
3975         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3976       }
3977     } else if (Op0I->getOpcode() == Instruction::Xor) {
3978       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
3979         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3980       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
3981         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3982     } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3983       if (Op0I->getOperand(0) == Op1)                      // (A&B)^A -> (B&A)^A
3984         Op0I->swapOperands();
3985       if (Op0I->getOperand(1) == Op1 &&                    // (B&A)^A == ~B & A
3986           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
3987         Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3988         InsertNewInstBefore(N, I);
3989         return BinaryOperator::createAnd(N, Op1);
3990       }
3991     }
3992
3993   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
3994   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
3995     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3996       return R;
3997
3998   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3999   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4000     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4001       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4002         const Type *SrcTy = Op0C->getOperand(0)->getType();
4003         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4004             // Only do this if the casts both really cause code to be generated.
4005             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4006                               I.getType(), TD) &&
4007             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4008                               I.getType(), TD)) {
4009           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4010                                                          Op1C->getOperand(0),
4011                                                          I.getName());
4012           InsertNewInstBefore(NewOp, I);
4013           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4014         }
4015       }
4016
4017   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4018   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4019     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4020       if (SI0->getOpcode() == SI1->getOpcode() && 
4021           SI0->getOperand(1) == SI1->getOperand(1) &&
4022           (SI0->hasOneUse() || SI1->hasOneUse())) {
4023         Instruction *NewOp =
4024         InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4025                                                       SI1->getOperand(0),
4026                                                       SI0->getName()), I);
4027         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4028       }
4029   }
4030     
4031   return Changed ? &I : 0;
4032 }
4033
4034 static bool isPositive(ConstantInt *C) {
4035   return C->getSExtValue() >= 0;
4036 }
4037
4038 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4039 /// overflowed for this type.
4040 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4041                             ConstantInt *In2) {
4042   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4043
4044   return cast<ConstantInt>(Result)->getZExtValue() <
4045          cast<ConstantInt>(In1)->getZExtValue();
4046 }
4047
4048 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4049 /// code necessary to compute the offset from the base pointer (without adding
4050 /// in the base pointer).  Return the result as a signed integer of intptr size.
4051 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4052   TargetData &TD = IC.getTargetData();
4053   gep_type_iterator GTI = gep_type_begin(GEP);
4054   const Type *IntPtrTy = TD.getIntPtrType();
4055   Value *Result = Constant::getNullValue(IntPtrTy);
4056
4057   // Build a mask for high order bits.
4058   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4059
4060   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4061     Value *Op = GEP->getOperand(i);
4062     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4063     Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4064     if (Constant *OpC = dyn_cast<Constant>(Op)) {
4065       if (!OpC->isNullValue()) {
4066         OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4067         Scale = ConstantExpr::getMul(OpC, Scale);
4068         if (Constant *RC = dyn_cast<Constant>(Result))
4069           Result = ConstantExpr::getAdd(RC, Scale);
4070         else {
4071           // Emit an add instruction.
4072           Result = IC.InsertNewInstBefore(
4073              BinaryOperator::createAdd(Result, Scale,
4074                                        GEP->getName()+".offs"), I);
4075         }
4076       }
4077     } else {
4078       // Convert to correct type.
4079       Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4080                                                Op->getName()+".c"), I);
4081       if (Size != 1)
4082         // We'll let instcombine(mul) convert this to a shl if possible.
4083         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4084                                                     GEP->getName()+".idx"), I);
4085
4086       // Emit an add instruction.
4087       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4088                                                     GEP->getName()+".offs"), I);
4089     }
4090   }
4091   return Result;
4092 }
4093
4094 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4095 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4096 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4097                                        ICmpInst::Predicate Cond,
4098                                        Instruction &I) {
4099   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4100
4101   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4102     if (isa<PointerType>(CI->getOperand(0)->getType()))
4103       RHS = CI->getOperand(0);
4104
4105   Value *PtrBase = GEPLHS->getOperand(0);
4106   if (PtrBase == RHS) {
4107     // As an optimization, we don't actually have to compute the actual value of
4108     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4109     // each index is zero or not.
4110     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4111       Instruction *InVal = 0;
4112       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4113       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4114         bool EmitIt = true;
4115         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4116           if (isa<UndefValue>(C))  // undef index -> undef.
4117             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4118           if (C->isNullValue())
4119             EmitIt = false;
4120           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4121             EmitIt = false;  // This is indexing into a zero sized array?
4122           } else if (isa<ConstantInt>(C))
4123             return ReplaceInstUsesWith(I, // No comparison is needed here.
4124                                  ConstantInt::get(Type::Int1Ty, 
4125                                                   Cond == ICmpInst::ICMP_NE));
4126         }
4127
4128         if (EmitIt) {
4129           Instruction *Comp =
4130             new ICmpInst(Cond, GEPLHS->getOperand(i),
4131                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4132           if (InVal == 0)
4133             InVal = Comp;
4134           else {
4135             InVal = InsertNewInstBefore(InVal, I);
4136             InsertNewInstBefore(Comp, I);
4137             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4138               InVal = BinaryOperator::createOr(InVal, Comp);
4139             else                              // True if all are equal
4140               InVal = BinaryOperator::createAnd(InVal, Comp);
4141           }
4142         }
4143       }
4144
4145       if (InVal)
4146         return InVal;
4147       else
4148         // No comparison is needed here, all indexes = 0
4149         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4150                                                 Cond == ICmpInst::ICMP_EQ));
4151     }
4152
4153     // Only lower this if the icmp is the only user of the GEP or if we expect
4154     // the result to fold to a constant!
4155     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4156       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4157       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4158       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4159                           Constant::getNullValue(Offset->getType()));
4160     }
4161   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4162     // If the base pointers are different, but the indices are the same, just
4163     // compare the base pointer.
4164     if (PtrBase != GEPRHS->getOperand(0)) {
4165       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4166       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4167                         GEPRHS->getOperand(0)->getType();
4168       if (IndicesTheSame)
4169         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4170           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4171             IndicesTheSame = false;
4172             break;
4173           }
4174
4175       // If all indices are the same, just compare the base pointers.
4176       if (IndicesTheSame)
4177         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4178                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4179
4180       // Otherwise, the base pointers are different and the indices are
4181       // different, bail out.
4182       return 0;
4183     }
4184
4185     // If one of the GEPs has all zero indices, recurse.
4186     bool AllZeros = true;
4187     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4188       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4189           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4190         AllZeros = false;
4191         break;
4192       }
4193     if (AllZeros)
4194       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4195                           ICmpInst::getSwappedPredicate(Cond), I);
4196
4197     // If the other GEP has all zero indices, recurse.
4198     AllZeros = true;
4199     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4200       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4201           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4202         AllZeros = false;
4203         break;
4204       }
4205     if (AllZeros)
4206       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4207
4208     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4209       // If the GEPs only differ by one index, compare it.
4210       unsigned NumDifferences = 0;  // Keep track of # differences.
4211       unsigned DiffOperand = 0;     // The operand that differs.
4212       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4213         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4214           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4215                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4216             // Irreconcilable differences.
4217             NumDifferences = 2;
4218             break;
4219           } else {
4220             if (NumDifferences++) break;
4221             DiffOperand = i;
4222           }
4223         }
4224
4225       if (NumDifferences == 0)   // SAME GEP?
4226         return ReplaceInstUsesWith(I, // No comparison is needed here.
4227                                    ConstantInt::get(Type::Int1Ty, 
4228                                                     Cond == ICmpInst::ICMP_EQ));
4229       else if (NumDifferences == 1) {
4230         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4231         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4232         // Make sure we do a signed comparison here.
4233         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4234       }
4235     }
4236
4237     // Only lower this if the icmp is the only user of the GEP or if we expect
4238     // the result to fold to a constant!
4239     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4240         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4241       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4242       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4243       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4244       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4245     }
4246   }
4247   return 0;
4248 }
4249
4250 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4251   bool Changed = SimplifyCompare(I);
4252   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4253
4254   // Fold trivial predicates.
4255   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4256     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4257   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4258     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4259   
4260   // Simplify 'fcmp pred X, X'
4261   if (Op0 == Op1) {
4262     switch (I.getPredicate()) {
4263     default: assert(0 && "Unknown predicate!");
4264     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4265     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4266     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4267       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4268     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4269     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4270     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4271       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4272       
4273     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4274     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4275     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4276     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4277       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4278       I.setPredicate(FCmpInst::FCMP_UNO);
4279       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4280       return &I;
4281       
4282     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4283     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4284     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4285     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4286       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4287       I.setPredicate(FCmpInst::FCMP_ORD);
4288       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4289       return &I;
4290     }
4291   }
4292     
4293   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4294     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4295
4296   // Handle fcmp with constant RHS
4297   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4298     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4299       switch (LHSI->getOpcode()) {
4300       case Instruction::PHI:
4301         if (Instruction *NV = FoldOpIntoPhi(I))
4302           return NV;
4303         break;
4304       case Instruction::Select:
4305         // If either operand of the select is a constant, we can fold the
4306         // comparison into the select arms, which will cause one to be
4307         // constant folded and the select turned into a bitwise or.
4308         Value *Op1 = 0, *Op2 = 0;
4309         if (LHSI->hasOneUse()) {
4310           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4311             // Fold the known value into the constant operand.
4312             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4313             // Insert a new FCmp of the other select operand.
4314             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4315                                                       LHSI->getOperand(2), RHSC,
4316                                                       I.getName()), I);
4317           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4318             // Fold the known value into the constant operand.
4319             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4320             // Insert a new FCmp of the other select operand.
4321             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4322                                                       LHSI->getOperand(1), RHSC,
4323                                                       I.getName()), I);
4324           }
4325         }
4326
4327         if (Op1)
4328           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4329         break;
4330       }
4331   }
4332
4333   return Changed ? &I : 0;
4334 }
4335
4336 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4337   bool Changed = SimplifyCompare(I);
4338   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4339   const Type *Ty = Op0->getType();
4340
4341   // icmp X, X
4342   if (Op0 == Op1)
4343     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4344                                                    isTrueWhenEqual(I)));
4345
4346   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4347     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4348
4349   // icmp of GlobalValues can never equal each other as long as they aren't
4350   // external weak linkage type.
4351   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4352     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4353       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4354         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4355                                                        !isTrueWhenEqual(I)));
4356
4357   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4358   // addresses never equal each other!  We already know that Op0 != Op1.
4359   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4360        isa<ConstantPointerNull>(Op0)) &&
4361       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4362        isa<ConstantPointerNull>(Op1)))
4363     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4364                                                    !isTrueWhenEqual(I)));
4365
4366   // icmp's with boolean values can always be turned into bitwise operations
4367   if (Ty == Type::Int1Ty) {
4368     switch (I.getPredicate()) {
4369     default: assert(0 && "Invalid icmp instruction!");
4370     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4371       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4372       InsertNewInstBefore(Xor, I);
4373       return BinaryOperator::createNot(Xor);
4374     }
4375     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4376       return BinaryOperator::createXor(Op0, Op1);
4377
4378     case ICmpInst::ICMP_UGT:
4379     case ICmpInst::ICMP_SGT:
4380       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4381       // FALL THROUGH
4382     case ICmpInst::ICMP_ULT:
4383     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4384       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4385       InsertNewInstBefore(Not, I);
4386       return BinaryOperator::createAnd(Not, Op1);
4387     }
4388     case ICmpInst::ICMP_UGE:
4389     case ICmpInst::ICMP_SGE:
4390       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4391       // FALL THROUGH
4392     case ICmpInst::ICMP_ULE:
4393     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4394       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4395       InsertNewInstBefore(Not, I);
4396       return BinaryOperator::createOr(Not, Op1);
4397     }
4398     }
4399   }
4400
4401   // See if we are doing a comparison between a constant and an instruction that
4402   // can be folded into the comparison.
4403   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4404     switch (I.getPredicate()) {
4405     default: break;
4406     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4407       if (CI->isMinValue(false))
4408         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4409       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4410         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4411       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4412         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4413       break;
4414
4415     case ICmpInst::ICMP_SLT:
4416       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4417         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4418       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4419         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4420       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4421         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4422       break;
4423
4424     case ICmpInst::ICMP_UGT:
4425       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4426         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4427       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4428         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4429       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4430         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4431       break;
4432
4433     case ICmpInst::ICMP_SGT:
4434       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4435         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4436       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4437         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4438       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4439         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4440       break;
4441
4442     case ICmpInst::ICMP_ULE:
4443       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4444         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4445       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4446         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4447       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4448         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4449       break;
4450
4451     case ICmpInst::ICMP_SLE:
4452       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4453         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4454       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4455         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4456       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4457         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4458       break;
4459
4460     case ICmpInst::ICMP_UGE:
4461       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4462         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4463       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4464         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4465       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4466         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4467       break;
4468
4469     case ICmpInst::ICMP_SGE:
4470       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4471         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4472       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4473         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4474       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4475         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4476       break;
4477     }
4478
4479     // If we still have a icmp le or icmp ge instruction, turn it into the
4480     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4481     // already been handled above, this requires little checking.
4482     //
4483     if (I.getPredicate() == ICmpInst::ICMP_ULE)
4484       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4485     if (I.getPredicate() == ICmpInst::ICMP_SLE)
4486       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4487     if (I.getPredicate() == ICmpInst::ICMP_UGE)
4488       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4489     if (I.getPredicate() == ICmpInst::ICMP_SGE)
4490       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4491     
4492     // See if we can fold the comparison based on bits known to be zero or one
4493     // in the input.
4494     uint64_t KnownZero, KnownOne;
4495     if (SimplifyDemandedBits(Op0, Ty->getIntegerTypeMask(),
4496                              KnownZero, KnownOne, 0))
4497       return &I;
4498         
4499     // Given the known and unknown bits, compute a range that the LHS could be
4500     // in.
4501     if (KnownOne | KnownZero) {
4502       // Compute the Min, Max and RHS values based on the known bits. For the
4503       // EQ and NE we use unsigned values.
4504       uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4505       int64_t SMin = 0, SMax = 0, SRHSVal = 0;
4506       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4507         SRHSVal = CI->getSExtValue();
4508         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin, 
4509                                                SMax);
4510       } else {
4511         URHSVal = CI->getZExtValue();
4512         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin, 
4513                                                  UMax);
4514       }
4515       switch (I.getPredicate()) {  // LE/GE have been folded already.
4516       default: assert(0 && "Unknown icmp opcode!");
4517       case ICmpInst::ICMP_EQ:
4518         if (UMax < URHSVal || UMin > URHSVal)
4519           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4520         break;
4521       case ICmpInst::ICMP_NE:
4522         if (UMax < URHSVal || UMin > URHSVal)
4523           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4524         break;
4525       case ICmpInst::ICMP_ULT:
4526         if (UMax < URHSVal)
4527           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4528         if (UMin > URHSVal)
4529           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4530         break;
4531       case ICmpInst::ICMP_UGT:
4532         if (UMin > URHSVal)
4533           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4534         if (UMax < URHSVal)
4535           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4536         break;
4537       case ICmpInst::ICMP_SLT:
4538         if (SMax < SRHSVal)
4539           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4540         if (SMin > SRHSVal)
4541           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4542         break;
4543       case ICmpInst::ICMP_SGT: 
4544         if (SMin > SRHSVal)
4545           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4546         if (SMax < SRHSVal)
4547           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4548         break;
4549       }
4550     }
4551           
4552     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
4553     // instruction, see if that instruction also has constants so that the 
4554     // instruction can be folded into the icmp 
4555     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4556       switch (LHSI->getOpcode()) {
4557       case Instruction::And:
4558         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4559             LHSI->getOperand(0)->hasOneUse()) {
4560           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4561
4562           // If the LHS is an AND of a truncating cast, we can widen the
4563           // and/compare to be the input width without changing the value
4564           // produced, eliminating a cast.
4565           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4566             // We can do this transformation if either the AND constant does not
4567             // have its sign bit set or if it is an equality comparison. 
4568             // Extending a relational comparison when we're checking the sign
4569             // bit would not work.
4570             if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4571                 (I.isEquality() ||
4572                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4573                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4574               ConstantInt *NewCST;
4575               ConstantInt *NewCI;
4576               NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4577                                          AndCST->getZExtValue());
4578               NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4579                                         CI->getZExtValue());
4580               Instruction *NewAnd = 
4581                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4582                                           LHSI->getName());
4583               InsertNewInstBefore(NewAnd, I);
4584               return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
4585             }
4586           }
4587           
4588           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4589           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4590           // happens a LOT in code produced by the C front-end, for bitfield
4591           // access.
4592           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4593
4594           // Check to see if there is a noop-cast between the shift and the and.
4595           if (!Shift) {
4596             if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4597               if (CI->getOpcode() == Instruction::BitCast)
4598                 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4599           }
4600
4601           ConstantInt *ShAmt;
4602           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4603           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4604           const Type *AndTy = AndCST->getType();          // Type of the and.
4605
4606           // We can fold this as long as we can't shift unknown bits
4607           // into the mask.  This can only happen with signed shift
4608           // rights, as they sign-extend.
4609           if (ShAmt) {
4610             bool CanFold = Shift->isLogicalShift();
4611             if (!CanFold) {
4612               // To test for the bad case of the signed shr, see if any
4613               // of the bits shifted in could be tested after the mask.
4614               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4615               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4616
4617               Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
4618               Constant *ShVal =
4619                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4620                                      OShAmt);
4621               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4622                 CanFold = true;
4623             }
4624
4625             if (CanFold) {
4626               Constant *NewCst;
4627               if (Shift->getOpcode() == Instruction::Shl)
4628                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4629               else
4630                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4631
4632               // Check to see if we are shifting out any of the bits being
4633               // compared.
4634               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4635                 // If we shifted bits out, the fold is not going to work out.
4636                 // As a special case, check to see if this means that the
4637                 // result is always true or false now.
4638                 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4639                   return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4640                 if (I.getPredicate() == ICmpInst::ICMP_NE)
4641                   return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4642               } else {
4643                 I.setOperand(1, NewCst);
4644                 Constant *NewAndCST;
4645                 if (Shift->getOpcode() == Instruction::Shl)
4646                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4647                 else
4648                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4649                 LHSI->setOperand(1, NewAndCST);
4650                 LHSI->setOperand(0, Shift->getOperand(0));
4651                 WorkList.push_back(Shift); // Shift is dead.
4652                 AddUsesToWorkList(I);
4653                 return &I;
4654               }
4655             }
4656           }
4657           
4658           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4659           // preferable because it allows the C<<Y expression to be hoisted out
4660           // of a loop if Y is invariant and X is not.
4661           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4662               I.isEquality() && !Shift->isArithmeticShift() &&
4663               isa<Instruction>(Shift->getOperand(0))) {
4664             // Compute C << Y.
4665             Value *NS;
4666             if (Shift->getOpcode() == Instruction::LShr) {
4667               NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4668                                  "tmp");
4669             } else {
4670               // Insert a logical shift.
4671               NS = new ShiftInst(Instruction::LShr, AndCST,
4672                                  Shift->getOperand(1), "tmp");
4673             }
4674             InsertNewInstBefore(cast<Instruction>(NS), I);
4675
4676             // Compute X & (C << Y).
4677             Instruction *NewAnd = BinaryOperator::createAnd(
4678                 Shift->getOperand(0), NS, LHSI->getName());
4679             InsertNewInstBefore(NewAnd, I);
4680             
4681             I.setOperand(0, NewAnd);
4682             return &I;
4683           }
4684         }
4685         break;
4686
4687       case Instruction::Shl:         // (icmp pred (shl X, ShAmt), CI)
4688         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4689           if (I.isEquality()) {
4690             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4691
4692             // Check that the shift amount is in range.  If not, don't perform
4693             // undefined shifts.  When the shift is visited it will be
4694             // simplified.
4695             if (ShAmt->getZExtValue() >= TypeBits)
4696               break;
4697
4698             // If we are comparing against bits always shifted out, the
4699             // comparison cannot succeed.
4700             Constant *Comp =
4701               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4702             if (Comp != CI) {// Comparing against a bit that we know is zero.
4703               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4704               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4705               return ReplaceInstUsesWith(I, Cst);
4706             }
4707
4708             if (LHSI->hasOneUse()) {
4709               // Otherwise strength reduce the shift into an and.
4710               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4711               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4712               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4713
4714               Instruction *AndI =
4715                 BinaryOperator::createAnd(LHSI->getOperand(0),
4716                                           Mask, LHSI->getName()+".mask");
4717               Value *And = InsertNewInstBefore(AndI, I);
4718               return new ICmpInst(I.getPredicate(), And,
4719                                      ConstantExpr::getLShr(CI, ShAmt));
4720             }
4721           }
4722         }
4723         break;
4724
4725       case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
4726       case Instruction::AShr:
4727         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4728           if (I.isEquality()) {
4729             // Check that the shift amount is in range.  If not, don't perform
4730             // undefined shifts.  When the shift is visited it will be
4731             // simplified.
4732             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4733             if (ShAmt->getZExtValue() >= TypeBits)
4734               break;
4735
4736             // If we are comparing against bits always shifted out, the
4737             // comparison cannot succeed.
4738             Constant *Comp;
4739             if (LHSI->getOpcode() == Instruction::LShr) 
4740               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
4741                                            ShAmt);
4742             else
4743               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
4744                                            ShAmt);
4745
4746             if (Comp != CI) {// Comparing against a bit that we know is zero.
4747               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4748               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4749               return ReplaceInstUsesWith(I, Cst);
4750             }
4751
4752             if (LHSI->hasOneUse() || CI->isNullValue()) {
4753               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4754
4755               // Otherwise strength reduce the shift into an and.
4756               uint64_t Val = ~0ULL;          // All ones.
4757               Val <<= ShAmtVal;              // Shift over to the right spot.
4758               Val &= ~0ULL >> (64-TypeBits);
4759               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4760
4761               Instruction *AndI =
4762                 BinaryOperator::createAnd(LHSI->getOperand(0),
4763                                           Mask, LHSI->getName()+".mask");
4764               Value *And = InsertNewInstBefore(AndI, I);
4765               return new ICmpInst(I.getPredicate(), And,
4766                                      ConstantExpr::getShl(CI, ShAmt));
4767             }
4768           }
4769         }
4770         break;
4771
4772       case Instruction::SDiv:
4773       case Instruction::UDiv:
4774         // Fold: icmp pred ([us]div X, C1), C2 -> range test
4775         // Fold this div into the comparison, producing a range check. 
4776         // Determine, based on the divide type, what the range is being 
4777         // checked.  If there is an overflow on the low or high side, remember 
4778         // it, otherwise compute the range [low, hi) bounding the new value.
4779         // See: InsertRangeTest above for the kinds of replacements possible.
4780         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4781           // FIXME: If the operand types don't match the type of the divide 
4782           // then don't attempt this transform. The code below doesn't have the
4783           // logic to deal with a signed divide and an unsigned compare (and
4784           // vice versa). This is because (x /s C1) <s C2  produces different 
4785           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4786           // (x /u C1) <u C2.  Simply casting the operands and result won't 
4787           // work. :(  The if statement below tests that condition and bails 
4788           // if it finds it. 
4789           bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4790           if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
4791             break;
4792
4793           // Initialize the variables that will indicate the nature of the
4794           // range check.
4795           bool LoOverflow = false, HiOverflow = false;
4796           ConstantInt *LoBound = 0, *HiBound = 0;
4797
4798           // Compute Prod = CI * DivRHS. We are essentially solving an equation
4799           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
4800           // C2 (CI). By solving for X we can turn this into a range check 
4801           // instead of computing a divide. 
4802           ConstantInt *Prod = 
4803             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4804
4805           // Determine if the product overflows by seeing if the product is
4806           // not equal to the divide. Make sure we do the same kind of divide
4807           // as in the LHS instruction that we're folding. 
4808           bool ProdOV = !DivRHS->isNullValue() && 
4809             (DivIsSigned ?  ConstantExpr::getSDiv(Prod, DivRHS) :
4810               ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4811
4812           // Get the ICmp opcode
4813           ICmpInst::Predicate predicate = I.getPredicate();
4814
4815           if (DivRHS->isNullValue()) {  
4816             // Don't hack on divide by zeros!
4817           } else if (!DivIsSigned) {  // udiv
4818             LoBound = Prod;
4819             LoOverflow = ProdOV;
4820             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4821           } else if (isPositive(DivRHS)) { // Divisor is > 0.
4822             if (CI->isNullValue()) {       // (X / pos) op 0
4823               // Can't overflow.
4824               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4825               HiBound = DivRHS;
4826             } else if (isPositive(CI)) {   // (X / pos) op pos
4827               LoBound = Prod;
4828               LoOverflow = ProdOV;
4829               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4830             } else {                       // (X / pos) op neg
4831               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4832               LoOverflow = AddWithOverflow(LoBound, Prod,
4833                                            cast<ConstantInt>(DivRHSH));
4834               HiBound = Prod;
4835               HiOverflow = ProdOV;
4836             }
4837           } else {                         // Divisor is < 0.
4838             if (CI->isNullValue()) {       // (X / neg) op 0
4839               LoBound = AddOne(DivRHS);
4840               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4841               if (HiBound == DivRHS)
4842                 LoBound = 0;               // - INTMIN = INTMIN
4843             } else if (isPositive(CI)) {   // (X / neg) op pos
4844               HiOverflow = LoOverflow = ProdOV;
4845               if (!LoOverflow)
4846                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4847               HiBound = AddOne(Prod);
4848             } else {                       // (X / neg) op neg
4849               LoBound = Prod;
4850               LoOverflow = HiOverflow = ProdOV;
4851               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4852             }
4853
4854             // Dividing by a negate swaps the condition.
4855             predicate = ICmpInst::getSwappedPredicate(predicate);
4856           }
4857
4858           if (LoBound) {
4859             Value *X = LHSI->getOperand(0);
4860             switch (predicate) {
4861             default: assert(0 && "Unhandled icmp opcode!");
4862             case ICmpInst::ICMP_EQ:
4863               if (LoOverflow && HiOverflow)
4864                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4865               else if (HiOverflow)
4866                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SGE : 
4867                                     ICmpInst::ICMP_UGE, X, LoBound);
4868               else if (LoOverflow)
4869                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
4870                                     ICmpInst::ICMP_ULT, X, HiBound);
4871               else
4872                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4873                                        true, I);
4874             case ICmpInst::ICMP_NE:
4875               if (LoOverflow && HiOverflow)
4876                 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4877               else if (HiOverflow)
4878                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SLT : 
4879                                     ICmpInst::ICMP_ULT, X, LoBound);
4880               else if (LoOverflow)
4881                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
4882                                     ICmpInst::ICMP_UGE, X, HiBound);
4883               else
4884                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4885                                        false, I);
4886             case ICmpInst::ICMP_ULT:
4887             case ICmpInst::ICMP_SLT:
4888               if (LoOverflow)
4889                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4890               return new ICmpInst(predicate, X, LoBound);
4891             case ICmpInst::ICMP_UGT:
4892             case ICmpInst::ICMP_SGT:
4893               if (HiOverflow)
4894                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4895               if (predicate == ICmpInst::ICMP_UGT)
4896                 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4897               else
4898                 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
4899             }
4900           }
4901         }
4902         break;
4903       }
4904
4905     // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
4906     if (I.isEquality()) {
4907       bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4908
4909       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
4910       // the second operand is a constant, simplify a bit.
4911       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4912         switch (BO->getOpcode()) {
4913         case Instruction::SRem:
4914           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4915           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4916               BO->hasOneUse()) {
4917             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4918             if (V > 1 && isPowerOf2_64(V)) {
4919               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4920                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4921               return new ICmpInst(I.getPredicate(), NewRem, 
4922                                   Constant::getNullValue(BO->getType()));
4923             }
4924           }
4925           break;
4926         case Instruction::Add:
4927           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4928           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4929             if (BO->hasOneUse())
4930               return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4931                                   ConstantExpr::getSub(CI, BOp1C));
4932           } else if (CI->isNullValue()) {
4933             // Replace ((add A, B) != 0) with (A != -B) if A or B is
4934             // efficiently invertible, or if the add has just this one use.
4935             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4936
4937             if (Value *NegVal = dyn_castNegVal(BOp1))
4938               return new ICmpInst(I.getPredicate(), BOp0, NegVal);
4939             else if (Value *NegVal = dyn_castNegVal(BOp0))
4940               return new ICmpInst(I.getPredicate(), NegVal, BOp1);
4941             else if (BO->hasOneUse()) {
4942               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4943               BO->setName("");
4944               InsertNewInstBefore(Neg, I);
4945               return new ICmpInst(I.getPredicate(), BOp0, Neg);
4946             }
4947           }
4948           break;
4949         case Instruction::Xor:
4950           // For the xor case, we can xor two constants together, eliminating
4951           // the explicit xor.
4952           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4953             return new ICmpInst(I.getPredicate(), BO->getOperand(0), 
4954                                 ConstantExpr::getXor(CI, BOC));
4955
4956           // FALLTHROUGH
4957         case Instruction::Sub:
4958           // Replace (([sub|xor] A, B) != 0) with (A != B)
4959           if (CI->isNullValue())
4960             return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4961                                 BO->getOperand(1));
4962           break;
4963
4964         case Instruction::Or:
4965           // If bits are being or'd in that are not present in the constant we
4966           // are comparing against, then the comparison could never succeed!
4967           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4968             Constant *NotCI = ConstantExpr::getNot(CI);
4969             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4970               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4971                                                              isICMP_NE));
4972           }
4973           break;
4974
4975         case Instruction::And:
4976           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4977             // If bits are being compared against that are and'd out, then the
4978             // comparison can never succeed!
4979             if (!ConstantExpr::getAnd(CI,
4980                                       ConstantExpr::getNot(BOC))->isNullValue())
4981               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4982                                                              isICMP_NE));
4983
4984             // If we have ((X & C) == C), turn it into ((X & C) != 0).
4985             if (CI == BOC && isOneBitSet(CI))
4986               return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4987                                   ICmpInst::ICMP_NE, Op0,
4988                                   Constant::getNullValue(CI->getType()));
4989
4990             // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
4991             if (isSignBit(BOC)) {
4992               Value *X = BO->getOperand(0);
4993               Constant *Zero = Constant::getNullValue(X->getType());
4994               ICmpInst::Predicate pred = isICMP_NE ? 
4995                 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
4996               return new ICmpInst(pred, X, Zero);
4997             }
4998
4999             // ((X & ~7) == 0) --> X < 8
5000             if (CI->isNullValue() && isHighOnes(BOC)) {
5001               Value *X = BO->getOperand(0);
5002               Constant *NegX = ConstantExpr::getNeg(BOC);
5003               ICmpInst::Predicate pred = isICMP_NE ? 
5004                 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5005               return new ICmpInst(pred, X, NegX);
5006             }
5007
5008           }
5009         default: break;
5010         }
5011       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5012         // Handle set{eq|ne} <intrinsic>, intcst.
5013         switch (II->getIntrinsicID()) {
5014         default: break;
5015         case Intrinsic::bswap_i16: 
5016           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5017           WorkList.push_back(II);  // Dead?
5018           I.setOperand(0, II->getOperand(1));
5019           I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5020                                            ByteSwap_16(CI->getZExtValue())));
5021           return &I;
5022         case Intrinsic::bswap_i32:   
5023           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5024           WorkList.push_back(II);  // Dead?
5025           I.setOperand(0, II->getOperand(1));
5026           I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5027                                            ByteSwap_32(CI->getZExtValue())));
5028           return &I;
5029         case Intrinsic::bswap_i64:   
5030           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5031           WorkList.push_back(II);  // Dead?
5032           I.setOperand(0, II->getOperand(1));
5033           I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5034                                            ByteSwap_64(CI->getZExtValue())));
5035           return &I;
5036         }
5037       }
5038     } else {  // Not a ICMP_EQ/ICMP_NE
5039       // If the LHS is a cast from an integral value of the same size, then 
5040       // since we know the RHS is a constant, try to simlify.
5041       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5042         Value *CastOp = Cast->getOperand(0);
5043         const Type *SrcTy = CastOp->getType();
5044         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5045         if (SrcTy->isInteger() && 
5046             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5047           // If this is an unsigned comparison, try to make the comparison use
5048           // smaller constant values.
5049           switch (I.getPredicate()) {
5050             default: break;
5051             case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5052               ConstantInt *CUI = cast<ConstantInt>(CI);
5053               if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5054                 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5055                                     ConstantInt::get(SrcTy, -1));
5056               break;
5057             }
5058             case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5059               ConstantInt *CUI = cast<ConstantInt>(CI);
5060               if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5061                 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5062                                     Constant::getNullValue(SrcTy));
5063               break;
5064             }
5065           }
5066
5067         }
5068       }
5069     }
5070   }
5071
5072   // Handle icmp with constant RHS
5073   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5074     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5075       switch (LHSI->getOpcode()) {
5076       case Instruction::GetElementPtr:
5077         if (RHSC->isNullValue()) {
5078           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5079           bool isAllZeros = true;
5080           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5081             if (!isa<Constant>(LHSI->getOperand(i)) ||
5082                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5083               isAllZeros = false;
5084               break;
5085             }
5086           if (isAllZeros)
5087             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5088                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5089         }
5090         break;
5091
5092       case Instruction::PHI:
5093         if (Instruction *NV = FoldOpIntoPhi(I))
5094           return NV;
5095         break;
5096       case Instruction::Select:
5097         // If either operand of the select is a constant, we can fold the
5098         // comparison into the select arms, which will cause one to be
5099         // constant folded and the select turned into a bitwise or.
5100         Value *Op1 = 0, *Op2 = 0;
5101         if (LHSI->hasOneUse()) {
5102           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5103             // Fold the known value into the constant operand.
5104             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5105             // Insert a new ICmp of the other select operand.
5106             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5107                                                    LHSI->getOperand(2), RHSC,
5108                                                    I.getName()), I);
5109           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5110             // Fold the known value into the constant operand.
5111             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5112             // Insert a new ICmp of the other select operand.
5113             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5114                                                    LHSI->getOperand(1), RHSC,
5115                                                    I.getName()), I);
5116           }
5117         }
5118
5119         if (Op1)
5120           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5121         break;
5122       }
5123   }
5124
5125   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5126   if (User *GEP = dyn_castGetElementPtr(Op0))
5127     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5128       return NI;
5129   if (User *GEP = dyn_castGetElementPtr(Op1))
5130     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5131                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5132       return NI;
5133
5134   // Test to see if the operands of the icmp are casted versions of other
5135   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5136   // now.
5137   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5138     if (isa<PointerType>(Op0->getType()) && 
5139         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5140       // We keep moving the cast from the left operand over to the right
5141       // operand, where it can often be eliminated completely.
5142       Op0 = CI->getOperand(0);
5143
5144       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5145       // so eliminate it as well.
5146       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5147         Op1 = CI2->getOperand(0);
5148
5149       // If Op1 is a constant, we can fold the cast into the constant.
5150       if (Op0->getType() != Op1->getType())
5151         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5152           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5153         } else {
5154           // Otherwise, cast the RHS right before the icmp
5155           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5156         }
5157       return new ICmpInst(I.getPredicate(), Op0, Op1);
5158     }
5159   }
5160   
5161   if (isa<CastInst>(Op0)) {
5162     // Handle the special case of: icmp (cast bool to X), <cst>
5163     // This comes up when you have code like
5164     //   int X = A < B;
5165     //   if (X) ...
5166     // For generality, we handle any zero-extension of any operand comparison
5167     // with a constant or another cast from the same type.
5168     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5169       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5170         return R;
5171   }
5172   
5173   if (I.isEquality()) {
5174     Value *A, *B, *C, *D;
5175     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5176       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5177         Value *OtherVal = A == Op1 ? B : A;
5178         return new ICmpInst(I.getPredicate(), OtherVal,
5179                             Constant::getNullValue(A->getType()));
5180       }
5181
5182       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5183         // A^c1 == C^c2 --> A == C^(c1^c2)
5184         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5185           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5186             if (Op1->hasOneUse()) {
5187               Constant *NC = ConstantExpr::getXor(C1, C2);
5188               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5189               return new ICmpInst(I.getPredicate(), A,
5190                                   InsertNewInstBefore(Xor, I));
5191             }
5192         
5193         // A^B == A^D -> B == D
5194         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5195         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5196         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5197         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5198       }
5199     }
5200     
5201     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5202         (A == Op0 || B == Op0)) {
5203       // A == (A^B)  ->  B == 0
5204       Value *OtherVal = A == Op0 ? B : A;
5205       return new ICmpInst(I.getPredicate(), OtherVal,
5206                           Constant::getNullValue(A->getType()));
5207     }
5208     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5209       // (A-B) == A  ->  B == 0
5210       return new ICmpInst(I.getPredicate(), B,
5211                           Constant::getNullValue(B->getType()));
5212     }
5213     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5214       // A == (A-B)  ->  B == 0
5215       return new ICmpInst(I.getPredicate(), B,
5216                           Constant::getNullValue(B->getType()));
5217     }
5218     
5219     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5220     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5221         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5222         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5223       Value *X = 0, *Y = 0, *Z = 0;
5224       
5225       if (A == C) {
5226         X = B; Y = D; Z = A;
5227       } else if (A == D) {
5228         X = B; Y = C; Z = A;
5229       } else if (B == C) {
5230         X = A; Y = D; Z = B;
5231       } else if (B == D) {
5232         X = A; Y = C; Z = B;
5233       }
5234       
5235       if (X) {   // Build (X^Y) & Z
5236         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5237         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5238         I.setOperand(0, Op1);
5239         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5240         return &I;
5241       }
5242     }
5243   }
5244   return Changed ? &I : 0;
5245 }
5246
5247 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5248 // We only handle extending casts so far.
5249 //
5250 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5251   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5252   Value *LHSCIOp        = LHSCI->getOperand(0);
5253   const Type *SrcTy     = LHSCIOp->getType();
5254   const Type *DestTy    = LHSCI->getType();
5255   Value *RHSCIOp;
5256
5257   // We only handle extension cast instructions, so far. Enforce this.
5258   if (LHSCI->getOpcode() != Instruction::ZExt &&
5259       LHSCI->getOpcode() != Instruction::SExt)
5260     return 0;
5261
5262   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5263   bool isSignedCmp = ICI.isSignedPredicate();
5264
5265   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5266     // Not an extension from the same type?
5267     RHSCIOp = CI->getOperand(0);
5268     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5269       return 0;
5270     
5271     // If the signedness of the two compares doesn't agree (i.e. one is a sext
5272     // and the other is a zext), then we can't handle this.
5273     if (CI->getOpcode() != LHSCI->getOpcode())
5274       return 0;
5275
5276     // Likewise, if the signedness of the [sz]exts and the compare don't match, 
5277     // then we can't handle this.
5278     if (isSignedExt != isSignedCmp && !ICI.isEquality())
5279       return 0;
5280     
5281     // Okay, just insert a compare of the reduced operands now!
5282     return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5283   }
5284
5285   // If we aren't dealing with a constant on the RHS, exit early
5286   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5287   if (!CI)
5288     return 0;
5289
5290   // Compute the constant that would happen if we truncated to SrcTy then
5291   // reextended to DestTy.
5292   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5293   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5294
5295   // If the re-extended constant didn't change...
5296   if (Res2 == CI) {
5297     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5298     // For example, we might have:
5299     //    %A = sext short %X to uint
5300     //    %B = icmp ugt uint %A, 1330
5301     // It is incorrect to transform this into 
5302     //    %B = icmp ugt short %X, 1330 
5303     // because %A may have negative value. 
5304     //
5305     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5306     // OR operation is EQ/NE.
5307     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5308       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5309     else
5310       return 0;
5311   }
5312
5313   // The re-extended constant changed so the constant cannot be represented 
5314   // in the shorter type. Consequently, we cannot emit a simple comparison.
5315
5316   // First, handle some easy cases. We know the result cannot be equal at this
5317   // point so handle the ICI.isEquality() cases
5318   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5319     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5320   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5321     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5322
5323   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5324   // should have been folded away previously and not enter in here.
5325   Value *Result;
5326   if (isSignedCmp) {
5327     // We're performing a signed comparison.
5328     if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5329       Result = ConstantInt::getFalse();          // X < (small) --> false
5330     else
5331       Result = ConstantInt::getTrue();           // X < (large) --> true
5332   } else {
5333     // We're performing an unsigned comparison.
5334     if (isSignedExt) {
5335       // We're performing an unsigned comp with a sign extended value.
5336       // This is true if the input is >= 0. [aka >s -1]
5337       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5338       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5339                                    NegOne, ICI.getName()), ICI);
5340     } else {
5341       // Unsigned extend & unsigned compare -> always true.
5342       Result = ConstantInt::getTrue();
5343     }
5344   }
5345
5346   // Finally, return the value computed.
5347   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5348       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5349     return ReplaceInstUsesWith(ICI, Result);
5350   } else {
5351     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5352             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5353            "ICmp should be folded!");
5354     if (Constant *CI = dyn_cast<Constant>(Result))
5355       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5356     else
5357       return BinaryOperator::createNot(Result);
5358   }
5359 }
5360
5361 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
5362   assert(I.getOperand(1)->getType() == Type::Int8Ty);
5363   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5364
5365   // shl X, 0 == X and shr X, 0 == X
5366   // shl 0, X == 0 and shr 0, X == 0
5367   if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
5368       Op0 == Constant::getNullValue(Op0->getType()))
5369     return ReplaceInstUsesWith(I, Op0);
5370   
5371   if (isa<UndefValue>(Op0)) {            
5372     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5373       return ReplaceInstUsesWith(I, Op0);
5374     else                                    // undef << X -> 0, undef >>u X -> 0
5375       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5376   }
5377   if (isa<UndefValue>(Op1)) {
5378     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5379       return ReplaceInstUsesWith(I, Op0);          
5380     else                                     // X << undef, X >>u undef -> 0
5381       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5382   }
5383
5384   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5385   if (I.getOpcode() == Instruction::AShr)
5386     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5387       if (CSI->isAllOnesValue())
5388         return ReplaceInstUsesWith(I, CSI);
5389
5390   // Try to fold constant and into select arguments.
5391   if (isa<Constant>(Op0))
5392     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5393       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5394         return R;
5395
5396   // See if we can turn a signed shr into an unsigned shr.
5397   if (I.isArithmeticShift()) {
5398     if (MaskedValueIsZero(Op0,
5399                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5400       return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
5401     }
5402   }
5403
5404   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5405     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5406       return Res;
5407   return 0;
5408 }
5409
5410 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5411                                                ShiftInst &I) {
5412   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5413   bool isSignedShift  = I.getOpcode() == Instruction::AShr;
5414   bool isUnsignedShift = !isSignedShift;
5415
5416   // See if we can simplify any instructions used by the instruction whose sole 
5417   // purpose is to compute bits we don't care about.
5418   uint64_t KnownZero, KnownOne;
5419   if (SimplifyDemandedBits(&I, I.getType()->getIntegerTypeMask(),
5420                            KnownZero, KnownOne))
5421     return &I;
5422   
5423   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5424   // of a signed value.
5425   //
5426   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5427   if (Op1->getZExtValue() >= TypeBits) {
5428     if (isUnsignedShift || isLeftShift)
5429       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5430     else {
5431       I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
5432       return &I;
5433     }
5434   }
5435   
5436   // ((X*C1) << C2) == (X * (C1 << C2))
5437   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5438     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5439       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5440         return BinaryOperator::createMul(BO->getOperand(0),
5441                                          ConstantExpr::getShl(BOOp, Op1));
5442   
5443   // Try to fold constant and into select arguments.
5444   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5445     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5446       return R;
5447   if (isa<PHINode>(Op0))
5448     if (Instruction *NV = FoldOpIntoPhi(I))
5449       return NV;
5450   
5451   if (Op0->hasOneUse()) {
5452     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5453       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5454       Value *V1, *V2;
5455       ConstantInt *CC;
5456       switch (Op0BO->getOpcode()) {
5457         default: break;
5458         case Instruction::Add:
5459         case Instruction::And:
5460         case Instruction::Or:
5461         case Instruction::Xor:
5462           // These operators commute.
5463           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5464           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5465               match(Op0BO->getOperand(1),
5466                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5467             Instruction *YS = new ShiftInst(Instruction::Shl, 
5468                                             Op0BO->getOperand(0), Op1,
5469                                             Op0BO->getName());
5470             InsertNewInstBefore(YS, I); // (Y << C)
5471             Instruction *X = 
5472               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5473                                      Op0BO->getOperand(1)->getName());
5474             InsertNewInstBefore(X, I);  // (X + (Y << C))
5475             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5476             C2 = ConstantExpr::getShl(C2, Op1);
5477             return BinaryOperator::createAnd(X, C2);
5478           }
5479           
5480           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5481           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5482               match(Op0BO->getOperand(1),
5483                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5484                           m_ConstantInt(CC))) && V2 == Op1 &&
5485       cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5486             Instruction *YS = new ShiftInst(Instruction::Shl, 
5487                                             Op0BO->getOperand(0), Op1,
5488                                             Op0BO->getName());
5489             InsertNewInstBefore(YS, I); // (Y << C)
5490             Instruction *XM =
5491               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5492                                         V1->getName()+".mask");
5493             InsertNewInstBefore(XM, I); // X & (CC << C)
5494             
5495             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5496           }
5497           
5498           // FALL THROUGH.
5499         case Instruction::Sub:
5500           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5501           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5502               match(Op0BO->getOperand(0),
5503                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5504             Instruction *YS = new ShiftInst(Instruction::Shl, 
5505                                             Op0BO->getOperand(1), Op1,
5506                                             Op0BO->getName());
5507             InsertNewInstBefore(YS, I); // (Y << C)
5508             Instruction *X =
5509               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5510                                      Op0BO->getOperand(0)->getName());
5511             InsertNewInstBefore(X, I);  // (X + (Y << C))
5512             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5513             C2 = ConstantExpr::getShl(C2, Op1);
5514             return BinaryOperator::createAnd(X, C2);
5515           }
5516           
5517           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5518           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5519               match(Op0BO->getOperand(0),
5520                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5521                           m_ConstantInt(CC))) && V2 == Op1 &&
5522               cast<BinaryOperator>(Op0BO->getOperand(0))
5523                   ->getOperand(0)->hasOneUse()) {
5524             Instruction *YS = new ShiftInst(Instruction::Shl, 
5525                                             Op0BO->getOperand(1), Op1,
5526                                             Op0BO->getName());
5527             InsertNewInstBefore(YS, I); // (Y << C)
5528             Instruction *XM =
5529               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5530                                         V1->getName()+".mask");
5531             InsertNewInstBefore(XM, I); // X & (CC << C)
5532             
5533             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5534           }
5535           
5536           break;
5537       }
5538       
5539       
5540       // If the operand is an bitwise operator with a constant RHS, and the
5541       // shift is the only use, we can pull it out of the shift.
5542       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5543         bool isValid = true;     // Valid only for And, Or, Xor
5544         bool highBitSet = false; // Transform if high bit of constant set?
5545         
5546         switch (Op0BO->getOpcode()) {
5547           default: isValid = false; break;   // Do not perform transform!
5548           case Instruction::Add:
5549             isValid = isLeftShift;
5550             break;
5551           case Instruction::Or:
5552           case Instruction::Xor:
5553             highBitSet = false;
5554             break;
5555           case Instruction::And:
5556             highBitSet = true;
5557             break;
5558         }
5559         
5560         // If this is a signed shift right, and the high bit is modified
5561         // by the logical operation, do not perform the transformation.
5562         // The highBitSet boolean indicates the value of the high bit of
5563         // the constant which would cause it to be modified for this
5564         // operation.
5565         //
5566         if (isValid && !isLeftShift && isSignedShift) {
5567           uint64_t Val = Op0C->getZExtValue();
5568           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5569         }
5570         
5571         if (isValid) {
5572           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5573           
5574           Instruction *NewShift =
5575             new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5576                           Op0BO->getName());
5577           Op0BO->setName("");
5578           InsertNewInstBefore(NewShift, I);
5579           
5580           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5581                                         NewRHS);
5582         }
5583       }
5584     }
5585   }
5586   
5587   // Find out if this is a shift of a shift by a constant.
5588   ShiftInst *ShiftOp = 0;
5589   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5590     ShiftOp = Op0SI;
5591   else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5592     // If this is a noop-integer cast of a shift instruction, use the shift.
5593     if (isa<ShiftInst>(CI->getOperand(0))) {
5594       ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5595     }
5596   }
5597   
5598   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5599     // Find the operands and properties of the input shift.  Note that the
5600     // signedness of the input shift may differ from the current shift if there
5601     // is a noop cast between the two.
5602     bool isShiftOfLeftShift   = ShiftOp->getOpcode() == Instruction::Shl;
5603     bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
5604     bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5605     
5606     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5607
5608     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5609     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5610     
5611     // Check for (A << c1) << c2   and   (A >> c1) >> c2.
5612     if (isLeftShift == isShiftOfLeftShift) {
5613       // Do not fold these shifts if the first one is signed and the second one
5614       // is unsigned and this is a right shift.  Further, don't do any folding
5615       // on them.
5616       if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5617         return 0;
5618       
5619       unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5620       if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5621         Amt = Op0->getType()->getPrimitiveSizeInBits();
5622       
5623       Value *Op = ShiftOp->getOperand(0);
5624       ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
5625                                           ConstantInt::get(Type::Int8Ty, Amt));
5626       if (I.getType() == ShiftResult->getType())
5627         return ShiftResult;
5628       InsertNewInstBefore(ShiftResult, I);
5629       return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
5630     }
5631     
5632     // Check for (A << c1) >> c2 or (A >> c1) << c2.  If we are dealing with
5633     // signed types, we can only support the (A >> c1) << c2 configuration,
5634     // because it can not turn an arbitrary bit of A into a sign bit.
5635     if (isUnsignedShift || isLeftShift) {
5636       // Calculate bitmask for what gets shifted off the edge.
5637       Constant *C = ConstantInt::getAllOnesValue(I.getType());
5638       if (isLeftShift)
5639         C = ConstantExpr::getShl(C, ShiftAmt1C);
5640       else
5641         C = ConstantExpr::getLShr(C, ShiftAmt1C);
5642       
5643       Value *Op = ShiftOp->getOperand(0);
5644       
5645       Instruction *Mask =
5646         BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5647       InsertNewInstBefore(Mask, I);
5648       
5649       // Figure out what flavor of shift we should use...
5650       if (ShiftAmt1 == ShiftAmt2) {
5651         return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
5652       } else if (ShiftAmt1 < ShiftAmt2) {
5653         return new ShiftInst(I.getOpcode(), Mask,
5654                          ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
5655       } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5656         if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5657           return new ShiftInst(Instruction::LShr, Mask, 
5658             ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5659         } else {
5660           return new ShiftInst(ShiftOp->getOpcode(), Mask,
5661                     ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5662         }
5663       } else {
5664         // (X >>s C1) << C2  where C1 > C2  === (X >>s (C1-C2)) & mask
5665         Instruction *Shift =
5666           new ShiftInst(ShiftOp->getOpcode(), Mask,
5667                         ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5668         InsertNewInstBefore(Shift, I);
5669         
5670         C = ConstantInt::getAllOnesValue(Shift->getType());
5671         C = ConstantExpr::getShl(C, Op1);
5672         return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5673       }
5674     } else {
5675       // We can handle signed (X << C1) >>s C2 if it's a sign extend.  In
5676       // this case, C1 == C2 and C1 is 8, 16, or 32.
5677       if (ShiftAmt1 == ShiftAmt2) {
5678         const Type *SExtType = 0;
5679         switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5680         case 8 : SExtType = Type::Int8Ty; break;
5681         case 16: SExtType = Type::Int16Ty; break;
5682         case 32: SExtType = Type::Int32Ty; break;
5683         }
5684         
5685         if (SExtType) {
5686           Instruction *NewTrunc = 
5687             new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
5688           InsertNewInstBefore(NewTrunc, I);
5689           return new SExtInst(NewTrunc, I.getType());
5690         }
5691       }
5692     }
5693   }
5694   return 0;
5695 }
5696
5697
5698 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5699 /// expression.  If so, decompose it, returning some value X, such that Val is
5700 /// X*Scale+Offset.
5701 ///
5702 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5703                                         unsigned &Offset) {
5704   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
5705   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5706     Offset = CI->getZExtValue();
5707     Scale  = 1;
5708     return ConstantInt::get(Type::Int32Ty, 0);
5709   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5710     if (I->getNumOperands() == 2) {
5711       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5712         if (I->getOpcode() == Instruction::Shl) {
5713           // This is a value scaled by '1 << the shift amt'.
5714           Scale = 1U << CUI->getZExtValue();
5715           Offset = 0;
5716           return I->getOperand(0);
5717         } else if (I->getOpcode() == Instruction::Mul) {
5718           // This value is scaled by 'CUI'.
5719           Scale = CUI->getZExtValue();
5720           Offset = 0;
5721           return I->getOperand(0);
5722         } else if (I->getOpcode() == Instruction::Add) {
5723           // We have X+C.  Check to see if we really have (X*C2)+C1, 
5724           // where C1 is divisible by C2.
5725           unsigned SubScale;
5726           Value *SubVal = 
5727             DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5728           Offset += CUI->getZExtValue();
5729           if (SubScale > 1 && (Offset % SubScale == 0)) {
5730             Scale = SubScale;
5731             return SubVal;
5732           }
5733         }
5734       }
5735     }
5736   }
5737
5738   // Otherwise, we can't look past this.
5739   Scale = 1;
5740   Offset = 0;
5741   return Val;
5742 }
5743
5744
5745 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5746 /// try to eliminate the cast by moving the type information into the alloc.
5747 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5748                                                    AllocationInst &AI) {
5749   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5750   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
5751   
5752   // Remove any uses of AI that are dead.
5753   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5754   std::vector<Instruction*> DeadUsers;
5755   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5756     Instruction *User = cast<Instruction>(*UI++);
5757     if (isInstructionTriviallyDead(User)) {
5758       while (UI != E && *UI == User)
5759         ++UI; // If this instruction uses AI more than once, don't break UI.
5760       
5761       // Add operands to the worklist.
5762       AddUsesToWorkList(*User);
5763       ++NumDeadInst;
5764       DOUT << "IC: DCE: " << *User;
5765       
5766       User->eraseFromParent();
5767       removeFromWorkList(User);
5768     }
5769   }
5770   
5771   // Get the type really allocated and the type casted to.
5772   const Type *AllocElTy = AI.getAllocatedType();
5773   const Type *CastElTy = PTy->getElementType();
5774   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5775
5776   unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5777   unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5778   if (CastElTyAlign < AllocElTyAlign) return 0;
5779
5780   // If the allocation has multiple uses, only promote it if we are strictly
5781   // increasing the alignment of the resultant allocation.  If we keep it the
5782   // same, we open the door to infinite loops of various kinds.
5783   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5784
5785   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5786   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5787   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5788
5789   // See if we can satisfy the modulus by pulling a scale out of the array
5790   // size argument.
5791   unsigned ArraySizeScale, ArrayOffset;
5792   Value *NumElements = // See if the array size is a decomposable linear expr.
5793     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5794  
5795   // If we can now satisfy the modulus, by using a non-1 scale, we really can
5796   // do the xform.
5797   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5798       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
5799
5800   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5801   Value *Amt = 0;
5802   if (Scale == 1) {
5803     Amt = NumElements;
5804   } else {
5805     // If the allocation size is constant, form a constant mul expression
5806     Amt = ConstantInt::get(Type::Int32Ty, Scale);
5807     if (isa<ConstantInt>(NumElements))
5808       Amt = ConstantExpr::getMul(
5809               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5810     // otherwise multiply the amount and the number of elements
5811     else if (Scale != 1) {
5812       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5813       Amt = InsertNewInstBefore(Tmp, AI);
5814     }
5815   }
5816   
5817   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5818     Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
5819     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5820     Amt = InsertNewInstBefore(Tmp, AI);
5821   }
5822   
5823   std::string Name = AI.getName(); AI.setName("");
5824   AllocationInst *New;
5825   if (isa<MallocInst>(AI))
5826     New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5827   else
5828     New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5829   InsertNewInstBefore(New, AI);
5830   
5831   // If the allocation has multiple uses, insert a cast and change all things
5832   // that used it to use the new cast.  This will also hack on CI, but it will
5833   // die soon.
5834   if (!AI.hasOneUse()) {
5835     AddUsesToWorkList(AI);
5836     // New is the allocation instruction, pointer typed. AI is the original
5837     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5838     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
5839     InsertNewInstBefore(NewCast, AI);
5840     AI.replaceAllUsesWith(NewCast);
5841   }
5842   return ReplaceInstUsesWith(CI, New);
5843 }
5844
5845 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5846 /// and return it without inserting any new casts.  This is used by code that
5847 /// tries to decide whether promoting or shrinking integer operations to wider
5848 /// or smaller types will allow us to eliminate a truncate or extend.
5849 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5850                                        int &NumCastsRemoved) {
5851   if (isa<Constant>(V)) return true;
5852   
5853   Instruction *I = dyn_cast<Instruction>(V);
5854   if (!I || !I->hasOneUse()) return false;
5855   
5856   switch (I->getOpcode()) {
5857   case Instruction::And:
5858   case Instruction::Or:
5859   case Instruction::Xor:
5860     // These operators can all arbitrarily be extended or truncated.
5861     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5862            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5863   case Instruction::AShr:
5864   case Instruction::LShr:
5865   case Instruction::Shl:
5866     // If this is just a bitcast changing the sign of the operation, we can
5867     // convert if the operand can be converted.
5868     if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5869       return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5870     break;
5871   case Instruction::Trunc:
5872   case Instruction::ZExt:
5873   case Instruction::SExt:
5874   case Instruction::BitCast:
5875     // If this is a cast from the destination type, we can trivially eliminate
5876     // it, and this will remove a cast overall.
5877     if (I->getOperand(0)->getType() == Ty) {
5878       // If the first operand is itself a cast, and is eliminable, do not count
5879       // this as an eliminable cast.  We would prefer to eliminate those two
5880       // casts first.
5881       if (isa<CastInst>(I->getOperand(0)))
5882         return true;
5883       
5884       ++NumCastsRemoved;
5885       return true;
5886     }
5887     break;
5888   default:
5889     // TODO: Can handle more cases here.
5890     break;
5891   }
5892   
5893   return false;
5894 }
5895
5896 /// EvaluateInDifferentType - Given an expression that 
5897 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5898 /// evaluate the expression.
5899 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
5900                                              bool isSigned ) {
5901   if (Constant *C = dyn_cast<Constant>(V))
5902     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
5903
5904   // Otherwise, it must be an instruction.
5905   Instruction *I = cast<Instruction>(V);
5906   Instruction *Res = 0;
5907   switch (I->getOpcode()) {
5908   case Instruction::And:
5909   case Instruction::Or:
5910   case Instruction::Xor: {
5911     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5912     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
5913     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5914                                  LHS, RHS, I->getName());
5915     break;
5916   }
5917   case Instruction::AShr:
5918   case Instruction::LShr:
5919   case Instruction::Shl: {
5920     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5921     Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5922                         I->getOperand(1), I->getName());
5923     break;
5924   }    
5925   case Instruction::Trunc:
5926   case Instruction::ZExt:
5927   case Instruction::SExt:
5928   case Instruction::BitCast:
5929     // If the source type of the cast is the type we're trying for then we can
5930     // just return the source. There's no need to insert it because its not new.
5931     if (I->getOperand(0)->getType() == Ty)
5932       return I->getOperand(0);
5933     
5934     // Some other kind of cast, which shouldn't happen, so just ..
5935     // FALL THROUGH
5936   default: 
5937     // TODO: Can handle more cases here.
5938     assert(0 && "Unreachable!");
5939     break;
5940   }
5941   
5942   return InsertNewInstBefore(Res, *I);
5943 }
5944
5945 /// @brief Implement the transforms common to all CastInst visitors.
5946 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
5947   Value *Src = CI.getOperand(0);
5948
5949   // Casting undef to anything results in undef so might as just replace it and
5950   // get rid of the cast.
5951   if (isa<UndefValue>(Src))   // cast undef -> undef
5952     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5953
5954   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5955   // eliminate it now.
5956   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
5957     if (Instruction::CastOps opc = 
5958         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5959       // The first cast (CSrc) is eliminable so we need to fix up or replace
5960       // the second cast (CI). CSrc will then have a good chance of being dead.
5961       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
5962     }
5963   }
5964
5965   // If casting the result of a getelementptr instruction with no offset, turn
5966   // this into a cast of the original pointer!
5967   //
5968   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5969     bool AllZeroOperands = true;
5970     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5971       if (!isa<Constant>(GEP->getOperand(i)) ||
5972           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5973         AllZeroOperands = false;
5974         break;
5975       }
5976     if (AllZeroOperands) {
5977       // Changing the cast operand is usually not a good idea but it is safe
5978       // here because the pointer operand is being replaced with another 
5979       // pointer operand so the opcode doesn't need to change.
5980       CI.setOperand(0, GEP->getOperand(0));
5981       return &CI;
5982     }
5983   }
5984     
5985   // If we are casting a malloc or alloca to a pointer to a type of the same
5986   // size, rewrite the allocation instruction to allocate the "right" type.
5987   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5988     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5989       return V;
5990
5991   // If we are casting a select then fold the cast into the select
5992   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5993     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5994       return NV;
5995
5996   // If we are casting a PHI then fold the cast into the PHI
5997   if (isa<PHINode>(Src))
5998     if (Instruction *NV = FoldOpIntoPhi(CI))
5999       return NV;
6000   
6001   return 0;
6002 }
6003
6004 /// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
6005 /// integers. This function implements the common transforms for all those
6006 /// cases.
6007 /// @brief Implement the transforms common to CastInst with integer operands
6008 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6009   if (Instruction *Result = commonCastTransforms(CI))
6010     return Result;
6011
6012   Value *Src = CI.getOperand(0);
6013   const Type *SrcTy = Src->getType();
6014   const Type *DestTy = CI.getType();
6015   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6016   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6017
6018   // See if we can simplify any instructions used by the LHS whose sole 
6019   // purpose is to compute bits we don't care about.
6020   uint64_t KnownZero = 0, KnownOne = 0;
6021   if (SimplifyDemandedBits(&CI, DestTy->getIntegerTypeMask(),
6022                            KnownZero, KnownOne))
6023     return &CI;
6024
6025   // If the source isn't an instruction or has more than one use then we
6026   // can't do anything more. 
6027   Instruction *SrcI = dyn_cast<Instruction>(Src);
6028   if (!SrcI || !Src->hasOneUse())
6029     return 0;
6030
6031   // Attempt to propagate the cast into the instruction.
6032   int NumCastsRemoved = 0;
6033   if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6034     // If this cast is a truncate, evaluting in a different type always
6035     // eliminates the cast, so it is always a win.  If this is a noop-cast
6036     // this just removes a noop cast which isn't pointful, but simplifies
6037     // the code.  If this is a zero-extension, we need to do an AND to
6038     // maintain the clear top-part of the computation, so we require that
6039     // the input have eliminated at least one cast.  If this is a sign
6040     // extension, we insert two new casts (to do the extension) so we
6041     // require that two casts have been eliminated.
6042     bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6043     if (!DoXForm) {
6044       switch (CI.getOpcode()) {
6045         case Instruction::Trunc:
6046           DoXForm = true;
6047           break;
6048         case Instruction::ZExt:
6049           DoXForm = NumCastsRemoved >= 1;
6050           break;
6051         case Instruction::SExt:
6052           DoXForm = NumCastsRemoved >= 2;
6053           break;
6054         case Instruction::BitCast:
6055           DoXForm = false;
6056           break;
6057         default:
6058           // All the others use floating point so we shouldn't actually 
6059           // get here because of the check above.
6060           assert(!"Unknown cast type .. unreachable");
6061           break;
6062       }
6063     }
6064     
6065     if (DoXForm) {
6066       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6067                                            CI.getOpcode() == Instruction::SExt);
6068       assert(Res->getType() == DestTy);
6069       switch (CI.getOpcode()) {
6070       default: assert(0 && "Unknown cast type!");
6071       case Instruction::Trunc:
6072       case Instruction::BitCast:
6073         // Just replace this cast with the result.
6074         return ReplaceInstUsesWith(CI, Res);
6075       case Instruction::ZExt: {
6076         // We need to emit an AND to clear the high bits.
6077         assert(SrcBitSize < DestBitSize && "Not a zext?");
6078         Constant *C = 
6079           ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
6080         if (DestBitSize < 64)
6081           C = ConstantExpr::getTrunc(C, DestTy);
6082         return BinaryOperator::createAnd(Res, C);
6083       }
6084       case Instruction::SExt:
6085         // We need to emit a cast to truncate, then a cast to sext.
6086         return CastInst::create(Instruction::SExt,
6087             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6088                              CI), DestTy);
6089       }
6090     }
6091   }
6092   
6093   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6094   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6095
6096   switch (SrcI->getOpcode()) {
6097   case Instruction::Add:
6098   case Instruction::Mul:
6099   case Instruction::And:
6100   case Instruction::Or:
6101   case Instruction::Xor:
6102     // If we are discarding information, or just changing the sign, 
6103     // rewrite.
6104     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6105       // Don't insert two casts if they cannot be eliminated.  We allow 
6106       // two casts to be inserted if the sizes are the same.  This could 
6107       // only be converting signedness, which is a noop.
6108       if (DestBitSize == SrcBitSize || 
6109           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6110           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6111         Instruction::CastOps opcode = CI.getOpcode();
6112         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6113         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6114         return BinaryOperator::create(
6115             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6116       }
6117     }
6118
6119     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6120     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6121         SrcI->getOpcode() == Instruction::Xor &&
6122         Op1 == ConstantInt::getTrue() &&
6123         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6124       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6125       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6126     }
6127     break;
6128   case Instruction::SDiv:
6129   case Instruction::UDiv:
6130   case Instruction::SRem:
6131   case Instruction::URem:
6132     // If we are just changing the sign, rewrite.
6133     if (DestBitSize == SrcBitSize) {
6134       // Don't insert two casts if they cannot be eliminated.  We allow 
6135       // two casts to be inserted if the sizes are the same.  This could 
6136       // only be converting signedness, which is a noop.
6137       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6138           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6139         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6140                                               Op0, DestTy, SrcI);
6141         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6142                                               Op1, DestTy, SrcI);
6143         return BinaryOperator::create(
6144           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6145       }
6146     }
6147     break;
6148
6149   case Instruction::Shl:
6150     // Allow changing the sign of the source operand.  Do not allow 
6151     // changing the size of the shift, UNLESS the shift amount is a 
6152     // constant.  We must not change variable sized shifts to a smaller 
6153     // size, because it is undefined to shift more bits out than exist 
6154     // in the value.
6155     if (DestBitSize == SrcBitSize ||
6156         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6157       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6158           Instruction::BitCast : Instruction::Trunc);
6159       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6160       return new ShiftInst(Instruction::Shl, Op0c, Op1);
6161     }
6162     break;
6163   case Instruction::AShr:
6164     // If this is a signed shr, and if all bits shifted in are about to be
6165     // truncated off, turn it into an unsigned shr to allow greater
6166     // simplifications.
6167     if (DestBitSize < SrcBitSize &&
6168         isa<ConstantInt>(Op1)) {
6169       unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6170       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6171         // Insert the new logical shift right.
6172         return new ShiftInst(Instruction::LShr, Op0, Op1);
6173       }
6174     }
6175     break;
6176
6177   case Instruction::ICmp:
6178     // If we are just checking for a icmp eq of a single bit and casting it
6179     // to an integer, then shift the bit to the appropriate place and then
6180     // cast to integer to avoid the comparison.
6181     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6182       uint64_t Op1CV = Op1C->getZExtValue();
6183       // cast (X == 0) to int --> X^1      iff X has only the low bit set.
6184       // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6185       // cast (X == 1) to int --> X        iff X has only the low bit set.
6186       // cast (X == 2) to int --> X>>1     iff X has only the 2nd bit set.
6187       // cast (X != 0) to int --> X        iff X has only the low bit set.
6188       // cast (X != 0) to int --> X>>1     iff X has only the 2nd bit set.
6189       // cast (X != 1) to int --> X^1      iff X has only the low bit set.
6190       // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6191       if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6192         // If Op1C some other power of two, convert:
6193         uint64_t KnownZero, KnownOne;
6194         uint64_t TypeMask = Op1->getType()->getIntegerTypeMask();
6195         ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
6196
6197         // This only works for EQ and NE
6198         ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6199         if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6200           break;
6201         
6202         if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
6203           bool isNE = pred == ICmpInst::ICMP_NE;
6204           if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6205             // (X&4) == 2 --> false
6206             // (X&4) != 2 --> true
6207             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6208             Res = ConstantExpr::getZExt(Res, CI.getType());
6209             return ReplaceInstUsesWith(CI, Res);
6210           }
6211           
6212           unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6213           Value *In = Op0;
6214           if (ShiftAmt) {
6215             // Perform a logical shr by shiftamt.
6216             // Insert the shift to put the result in the low bit.
6217             In = InsertNewInstBefore(
6218               new ShiftInst(Instruction::LShr, In,
6219                             ConstantInt::get(Type::Int8Ty, ShiftAmt),
6220                             In->getName()+".lobit"), CI);
6221           }
6222           
6223           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6224             Constant *One = ConstantInt::get(In->getType(), 1);
6225             In = BinaryOperator::createXor(In, One, "tmp");
6226             InsertNewInstBefore(cast<Instruction>(In), CI);
6227           }
6228           
6229           if (CI.getType() == In->getType())
6230             return ReplaceInstUsesWith(CI, In);
6231           else
6232             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6233         }
6234       }
6235     }
6236     break;
6237   }
6238   return 0;
6239 }
6240
6241 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
6242   if (Instruction *Result = commonIntCastTransforms(CI))
6243     return Result;
6244   
6245   Value *Src = CI.getOperand(0);
6246   const Type *Ty = CI.getType();
6247   unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6248   
6249   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6250     switch (SrcI->getOpcode()) {
6251     default: break;
6252     case Instruction::LShr:
6253       // We can shrink lshr to something smaller if we know the bits shifted in
6254       // are already zeros.
6255       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6256         unsigned ShAmt = ShAmtV->getZExtValue();
6257         
6258         // Get a mask for the bits shifting in.
6259         uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
6260         Value* SrcIOp0 = SrcI->getOperand(0);
6261         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6262           if (ShAmt >= DestBitWidth)        // All zeros.
6263             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6264
6265           // Okay, we can shrink this.  Truncate the input, then return a new
6266           // shift.
6267           Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6268           return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6269         }
6270       } else {     // This is a variable shr.
6271         
6272         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6273         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6274         // loop-invariant and CSE'd.
6275         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6276           Value *One = ConstantInt::get(SrcI->getType(), 1);
6277
6278           Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6279                                                        SrcI->getOperand(1),
6280                                                        "tmp"), CI);
6281           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6282                                                             SrcI->getOperand(0),
6283                                                             "tmp"), CI);
6284           Value *Zero = Constant::getNullValue(V->getType());
6285           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6286         }
6287       }
6288       break;
6289     }
6290   }
6291   
6292   return 0;
6293 }
6294
6295 Instruction *InstCombiner::visitZExt(CastInst &CI) {
6296   // If one of the common conversion will work ..
6297   if (Instruction *Result = commonIntCastTransforms(CI))
6298     return Result;
6299
6300   Value *Src = CI.getOperand(0);
6301
6302   // If this is a cast of a cast
6303   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6304     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6305     // types and if the sizes are just right we can convert this into a logical
6306     // 'and' which will be much cheaper than the pair of casts.
6307     if (isa<TruncInst>(CSrc)) {
6308       // Get the sizes of the types involved
6309       Value *A = CSrc->getOperand(0);
6310       unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6311       unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6312       unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6313       // If we're actually extending zero bits and the trunc is a no-op
6314       if (MidSize < DstSize && SrcSize == DstSize) {
6315         // Replace both of the casts with an And of the type mask.
6316         uint64_t AndValue = CSrc->getType()->getIntegerTypeMask();
6317         Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6318         Instruction *And = 
6319           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6320         // Unfortunately, if the type changed, we need to cast it back.
6321         if (And->getType() != CI.getType()) {
6322           And->setName(CSrc->getName()+".mask");
6323           InsertNewInstBefore(And, CI);
6324           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6325         }
6326         return And;
6327       }
6328     }
6329   }
6330
6331   return 0;
6332 }
6333
6334 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6335   return commonIntCastTransforms(CI);
6336 }
6337
6338 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6339   return commonCastTransforms(CI);
6340 }
6341
6342 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6343   return commonCastTransforms(CI);
6344 }
6345
6346 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6347   return commonCastTransforms(CI);
6348 }
6349
6350 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6351   return commonCastTransforms(CI);
6352 }
6353
6354 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6355   return commonCastTransforms(CI);
6356 }
6357
6358 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6359   return commonCastTransforms(CI);
6360 }
6361
6362 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6363   return commonCastTransforms(CI);
6364 }
6365
6366 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6367   return commonCastTransforms(CI);
6368 }
6369
6370 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6371
6372   // If the operands are integer typed then apply the integer transforms,
6373   // otherwise just apply the common ones.
6374   Value *Src = CI.getOperand(0);
6375   const Type *SrcTy = Src->getType();
6376   const Type *DestTy = CI.getType();
6377
6378   if (SrcTy->isInteger() && DestTy->isInteger()) {
6379     if (Instruction *Result = commonIntCastTransforms(CI))
6380       return Result;
6381   } else {
6382     if (Instruction *Result = commonCastTransforms(CI))
6383       return Result;
6384   }
6385
6386
6387   // Get rid of casts from one type to the same type. These are useless and can
6388   // be replaced by the operand.
6389   if (DestTy == Src->getType())
6390     return ReplaceInstUsesWith(CI, Src);
6391
6392   // If the source and destination are pointers, and this cast is equivalent to
6393   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
6394   // This can enhance SROA and other transforms that want type-safe pointers.
6395   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6396     if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6397       const Type *DstElTy = DstPTy->getElementType();
6398       const Type *SrcElTy = SrcPTy->getElementType();
6399       
6400       Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6401       unsigned NumZeros = 0;
6402       while (SrcElTy != DstElTy && 
6403              isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6404              SrcElTy->getNumContainedTypes() /* not "{}" */) {
6405         SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6406         ++NumZeros;
6407       }
6408
6409       // If we found a path from the src to dest, create the getelementptr now.
6410       if (SrcElTy == DstElTy) {
6411         std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6412         return new GetElementPtrInst(Src, Idxs);
6413       }
6414     }
6415   }
6416
6417   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6418     if (SVI->hasOneUse()) {
6419       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
6420       // a bitconvert to a vector with the same # elts.
6421       if (isa<PackedType>(DestTy) && 
6422           cast<PackedType>(DestTy)->getNumElements() == 
6423                 SVI->getType()->getNumElements()) {
6424         CastInst *Tmp;
6425         // If either of the operands is a cast from CI.getType(), then
6426         // evaluating the shuffle in the casted destination's type will allow
6427         // us to eliminate at least one cast.
6428         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
6429              Tmp->getOperand(0)->getType() == DestTy) ||
6430             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
6431              Tmp->getOperand(0)->getType() == DestTy)) {
6432           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6433                                                SVI->getOperand(0), DestTy, &CI);
6434           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6435                                                SVI->getOperand(1), DestTy, &CI);
6436           // Return a new shuffle vector.  Use the same element ID's, as we
6437           // know the vector types match #elts.
6438           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6439         }
6440       }
6441     }
6442   }
6443   return 0;
6444 }
6445
6446 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6447 ///   %C = or %A, %B
6448 ///   %D = select %cond, %C, %A
6449 /// into:
6450 ///   %C = select %cond, %B, 0
6451 ///   %D = or %A, %C
6452 ///
6453 /// Assuming that the specified instruction is an operand to the select, return
6454 /// a bitmask indicating which operands of this instruction are foldable if they
6455 /// equal the other incoming value of the select.
6456 ///
6457 static unsigned GetSelectFoldableOperands(Instruction *I) {
6458   switch (I->getOpcode()) {
6459   case Instruction::Add:
6460   case Instruction::Mul:
6461   case Instruction::And:
6462   case Instruction::Or:
6463   case Instruction::Xor:
6464     return 3;              // Can fold through either operand.
6465   case Instruction::Sub:   // Can only fold on the amount subtracted.
6466   case Instruction::Shl:   // Can only fold on the shift amount.
6467   case Instruction::LShr:
6468   case Instruction::AShr:
6469     return 1;
6470   default:
6471     return 0;              // Cannot fold
6472   }
6473 }
6474
6475 /// GetSelectFoldableConstant - For the same transformation as the previous
6476 /// function, return the identity constant that goes into the select.
6477 static Constant *GetSelectFoldableConstant(Instruction *I) {
6478   switch (I->getOpcode()) {
6479   default: assert(0 && "This cannot happen!"); abort();
6480   case Instruction::Add:
6481   case Instruction::Sub:
6482   case Instruction::Or:
6483   case Instruction::Xor:
6484     return Constant::getNullValue(I->getType());
6485   case Instruction::Shl:
6486   case Instruction::LShr:
6487   case Instruction::AShr:
6488     return Constant::getNullValue(Type::Int8Ty);
6489   case Instruction::And:
6490     return ConstantInt::getAllOnesValue(I->getType());
6491   case Instruction::Mul:
6492     return ConstantInt::get(I->getType(), 1);
6493   }
6494 }
6495
6496 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6497 /// have the same opcode and only one use each.  Try to simplify this.
6498 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6499                                           Instruction *FI) {
6500   if (TI->getNumOperands() == 1) {
6501     // If this is a non-volatile load or a cast from the same type,
6502     // merge.
6503     if (TI->isCast()) {
6504       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6505         return 0;
6506     } else {
6507       return 0;  // unknown unary op.
6508     }
6509
6510     // Fold this by inserting a select from the input values.
6511     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6512                                        FI->getOperand(0), SI.getName()+".v");
6513     InsertNewInstBefore(NewSI, SI);
6514     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
6515                             TI->getType());
6516   }
6517
6518   // Only handle binary, compare and shift operators here.
6519   if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6520     return 0;
6521
6522   // Figure out if the operations have any operands in common.
6523   Value *MatchOp, *OtherOpT, *OtherOpF;
6524   bool MatchIsOpZero;
6525   if (TI->getOperand(0) == FI->getOperand(0)) {
6526     MatchOp  = TI->getOperand(0);
6527     OtherOpT = TI->getOperand(1);
6528     OtherOpF = FI->getOperand(1);
6529     MatchIsOpZero = true;
6530   } else if (TI->getOperand(1) == FI->getOperand(1)) {
6531     MatchOp  = TI->getOperand(1);
6532     OtherOpT = TI->getOperand(0);
6533     OtherOpF = FI->getOperand(0);
6534     MatchIsOpZero = false;
6535   } else if (!TI->isCommutative()) {
6536     return 0;
6537   } else if (TI->getOperand(0) == FI->getOperand(1)) {
6538     MatchOp  = TI->getOperand(0);
6539     OtherOpT = TI->getOperand(1);
6540     OtherOpF = FI->getOperand(0);
6541     MatchIsOpZero = true;
6542   } else if (TI->getOperand(1) == FI->getOperand(0)) {
6543     MatchOp  = TI->getOperand(1);
6544     OtherOpT = TI->getOperand(0);
6545     OtherOpF = FI->getOperand(1);
6546     MatchIsOpZero = true;
6547   } else {
6548     return 0;
6549   }
6550
6551   // If we reach here, they do have operations in common.
6552   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6553                                      OtherOpF, SI.getName()+".v");
6554   InsertNewInstBefore(NewSI, SI);
6555
6556   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6557     if (MatchIsOpZero)
6558       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6559     else
6560       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6561   }
6562
6563   assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6564   if (MatchIsOpZero)
6565     return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6566   else
6567     return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6568 }
6569
6570 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6571   Value *CondVal = SI.getCondition();
6572   Value *TrueVal = SI.getTrueValue();
6573   Value *FalseVal = SI.getFalseValue();
6574
6575   // select true, X, Y  -> X
6576   // select false, X, Y -> Y
6577   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
6578     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
6579
6580   // select C, X, X -> X
6581   if (TrueVal == FalseVal)
6582     return ReplaceInstUsesWith(SI, TrueVal);
6583
6584   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
6585     return ReplaceInstUsesWith(SI, FalseVal);
6586   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
6587     return ReplaceInstUsesWith(SI, TrueVal);
6588   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
6589     if (isa<Constant>(TrueVal))
6590       return ReplaceInstUsesWith(SI, TrueVal);
6591     else
6592       return ReplaceInstUsesWith(SI, FalseVal);
6593   }
6594
6595   if (SI.getType() == Type::Int1Ty) {
6596     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
6597       if (C->getZExtValue()) {
6598         // Change: A = select B, true, C --> A = or B, C
6599         return BinaryOperator::createOr(CondVal, FalseVal);
6600       } else {
6601         // Change: A = select B, false, C --> A = and !B, C
6602         Value *NotCond =
6603           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6604                                              "not."+CondVal->getName()), SI);
6605         return BinaryOperator::createAnd(NotCond, FalseVal);
6606       }
6607     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
6608       if (C->getZExtValue() == false) {
6609         // Change: A = select B, C, false --> A = and B, C
6610         return BinaryOperator::createAnd(CondVal, TrueVal);
6611       } else {
6612         // Change: A = select B, C, true --> A = or !B, C
6613         Value *NotCond =
6614           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6615                                              "not."+CondVal->getName()), SI);
6616         return BinaryOperator::createOr(NotCond, TrueVal);
6617       }
6618     }
6619   }
6620
6621   // Selecting between two integer constants?
6622   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6623     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6624       // select C, 1, 0 -> cast C to int
6625       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6626         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6627       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6628         // select C, 0, 1 -> cast !C to int
6629         Value *NotCond =
6630           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6631                                                "not."+CondVal->getName()), SI);
6632         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6633       }
6634
6635       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
6636
6637         // (x <s 0) ? -1 : 0 -> ashr x, 31
6638         // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
6639         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6640           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6641             bool CanXForm = false;
6642             if (IC->isSignedPredicate())
6643               CanXForm = CmpCst->isNullValue() && 
6644                          IC->getPredicate() == ICmpInst::ICMP_SLT;
6645             else {
6646               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6647               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6648                          IC->getPredicate() == ICmpInst::ICMP_UGT;
6649             }
6650             
6651             if (CanXForm) {
6652               // The comparison constant and the result are not neccessarily the
6653               // same width. Make an all-ones value by inserting a AShr.
6654               Value *X = IC->getOperand(0);
6655               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6656               Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
6657               Instruction *SRA = new ShiftInst(Instruction::AShr, X,
6658                                                ShAmt, "ones");
6659               InsertNewInstBefore(SRA, SI);
6660               
6661               // Finally, convert to the type of the select RHS.  We figure out
6662               // if this requires a SExt, Trunc or BitCast based on the sizes.
6663               Instruction::CastOps opc = Instruction::BitCast;
6664               unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6665               unsigned SISize  = SI.getType()->getPrimitiveSizeInBits();
6666               if (SRASize < SISize)
6667                 opc = Instruction::SExt;
6668               else if (SRASize > SISize)
6669                 opc = Instruction::Trunc;
6670               return CastInst::create(opc, SRA, SI.getType());
6671             }
6672           }
6673
6674
6675         // If one of the constants is zero (we know they can't both be) and we
6676         // have a fcmp instruction with zero, and we have an 'and' with the
6677         // non-constant value, eliminate this whole mess.  This corresponds to
6678         // cases like this: ((X & 27) ? 27 : 0)
6679         if (TrueValC->isNullValue() || FalseValC->isNullValue())
6680           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6681               cast<Constant>(IC->getOperand(1))->isNullValue())
6682             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6683               if (ICA->getOpcode() == Instruction::And &&
6684                   isa<ConstantInt>(ICA->getOperand(1)) &&
6685                   (ICA->getOperand(1) == TrueValC ||
6686                    ICA->getOperand(1) == FalseValC) &&
6687                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6688                 // Okay, now we know that everything is set up, we just don't
6689                 // know whether we have a icmp_ne or icmp_eq and whether the 
6690                 // true or false val is the zero.
6691                 bool ShouldNotVal = !TrueValC->isNullValue();
6692                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
6693                 Value *V = ICA;
6694                 if (ShouldNotVal)
6695                   V = InsertNewInstBefore(BinaryOperator::create(
6696                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
6697                 return ReplaceInstUsesWith(SI, V);
6698               }
6699       }
6700     }
6701
6702   // See if we are selecting two values based on a comparison of the two values.
6703   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6704     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
6705       // Transform (X == Y) ? X : Y  -> Y
6706       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6707         return ReplaceInstUsesWith(SI, FalseVal);
6708       // Transform (X != Y) ? X : Y  -> X
6709       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6710         return ReplaceInstUsesWith(SI, TrueVal);
6711       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6712
6713     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
6714       // Transform (X == Y) ? Y : X  -> X
6715       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6716         return ReplaceInstUsesWith(SI, FalseVal);
6717       // Transform (X != Y) ? Y : X  -> Y
6718       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6719         return ReplaceInstUsesWith(SI, TrueVal);
6720       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6721     }
6722   }
6723
6724   // See if we are selecting two values based on a comparison of the two values.
6725   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6726     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6727       // Transform (X == Y) ? X : Y  -> Y
6728       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6729         return ReplaceInstUsesWith(SI, FalseVal);
6730       // Transform (X != Y) ? X : Y  -> X
6731       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6732         return ReplaceInstUsesWith(SI, TrueVal);
6733       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6734
6735     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6736       // Transform (X == Y) ? Y : X  -> X
6737       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6738         return ReplaceInstUsesWith(SI, FalseVal);
6739       // Transform (X != Y) ? Y : X  -> Y
6740       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6741         return ReplaceInstUsesWith(SI, TrueVal);
6742       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6743     }
6744   }
6745
6746   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6747     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6748       if (TI->hasOneUse() && FI->hasOneUse()) {
6749         Instruction *AddOp = 0, *SubOp = 0;
6750
6751         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6752         if (TI->getOpcode() == FI->getOpcode())
6753           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6754             return IV;
6755
6756         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
6757         // even legal for FP.
6758         if (TI->getOpcode() == Instruction::Sub &&
6759             FI->getOpcode() == Instruction::Add) {
6760           AddOp = FI; SubOp = TI;
6761         } else if (FI->getOpcode() == Instruction::Sub &&
6762                    TI->getOpcode() == Instruction::Add) {
6763           AddOp = TI; SubOp = FI;
6764         }
6765
6766         if (AddOp) {
6767           Value *OtherAddOp = 0;
6768           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6769             OtherAddOp = AddOp->getOperand(1);
6770           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6771             OtherAddOp = AddOp->getOperand(0);
6772           }
6773
6774           if (OtherAddOp) {
6775             // So at this point we know we have (Y -> OtherAddOp):
6776             //        select C, (add X, Y), (sub X, Z)
6777             Value *NegVal;  // Compute -Z
6778             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6779               NegVal = ConstantExpr::getNeg(C);
6780             } else {
6781               NegVal = InsertNewInstBefore(
6782                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6783             }
6784
6785             Value *NewTrueOp = OtherAddOp;
6786             Value *NewFalseOp = NegVal;
6787             if (AddOp != TI)
6788               std::swap(NewTrueOp, NewFalseOp);
6789             Instruction *NewSel =
6790               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6791
6792             NewSel = InsertNewInstBefore(NewSel, SI);
6793             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6794           }
6795         }
6796       }
6797
6798   // See if we can fold the select into one of our operands.
6799   if (SI.getType()->isInteger()) {
6800     // See the comment above GetSelectFoldableOperands for a description of the
6801     // transformation we are doing here.
6802     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6803       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6804           !isa<Constant>(FalseVal))
6805         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6806           unsigned OpToFold = 0;
6807           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6808             OpToFold = 1;
6809           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6810             OpToFold = 2;
6811           }
6812
6813           if (OpToFold) {
6814             Constant *C = GetSelectFoldableConstant(TVI);
6815             std::string Name = TVI->getName(); TVI->setName("");
6816             Instruction *NewSel =
6817               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6818                              Name);
6819             InsertNewInstBefore(NewSel, SI);
6820             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6821               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6822             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6823               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6824             else {
6825               assert(0 && "Unknown instruction!!");
6826             }
6827           }
6828         }
6829
6830     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6831       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6832           !isa<Constant>(TrueVal))
6833         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6834           unsigned OpToFold = 0;
6835           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6836             OpToFold = 1;
6837           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6838             OpToFold = 2;
6839           }
6840
6841           if (OpToFold) {
6842             Constant *C = GetSelectFoldableConstant(FVI);
6843             std::string Name = FVI->getName(); FVI->setName("");
6844             Instruction *NewSel =
6845               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6846                              Name);
6847             InsertNewInstBefore(NewSel, SI);
6848             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6849               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6850             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6851               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6852             else {
6853               assert(0 && "Unknown instruction!!");
6854             }
6855           }
6856         }
6857   }
6858
6859   if (BinaryOperator::isNot(CondVal)) {
6860     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6861     SI.setOperand(1, FalseVal);
6862     SI.setOperand(2, TrueVal);
6863     return &SI;
6864   }
6865
6866   return 0;
6867 }
6868
6869 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6870 /// determine, return it, otherwise return 0.
6871 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6872   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6873     unsigned Align = GV->getAlignment();
6874     if (Align == 0 && TD) 
6875       Align = TD->getTypeAlignment(GV->getType()->getElementType());
6876     return Align;
6877   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6878     unsigned Align = AI->getAlignment();
6879     if (Align == 0 && TD) {
6880       if (isa<AllocaInst>(AI))
6881         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6882       else if (isa<MallocInst>(AI)) {
6883         // Malloc returns maximally aligned memory.
6884         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6885         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6886         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::Int64Ty));
6887       }
6888     }
6889     return Align;
6890   } else if (isa<BitCastInst>(V) ||
6891              (isa<ConstantExpr>(V) && 
6892               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
6893     User *CI = cast<User>(V);
6894     if (isa<PointerType>(CI->getOperand(0)->getType()))
6895       return GetKnownAlignment(CI->getOperand(0), TD);
6896     return 0;
6897   } else if (isa<GetElementPtrInst>(V) ||
6898              (isa<ConstantExpr>(V) && 
6899               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6900     User *GEPI = cast<User>(V);
6901     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6902     if (BaseAlignment == 0) return 0;
6903     
6904     // If all indexes are zero, it is just the alignment of the base pointer.
6905     bool AllZeroOperands = true;
6906     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6907       if (!isa<Constant>(GEPI->getOperand(i)) ||
6908           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6909         AllZeroOperands = false;
6910         break;
6911       }
6912     if (AllZeroOperands)
6913       return BaseAlignment;
6914     
6915     // Otherwise, if the base alignment is >= the alignment we expect for the
6916     // base pointer type, then we know that the resultant pointer is aligned at
6917     // least as much as its type requires.
6918     if (!TD) return 0;
6919
6920     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6921     if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6922         <= BaseAlignment) {
6923       const Type *GEPTy = GEPI->getType();
6924       return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6925     }
6926     return 0;
6927   }
6928   return 0;
6929 }
6930
6931
6932 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
6933 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
6934 /// the heavy lifting.
6935 ///
6936 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6937   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6938   if (!II) return visitCallSite(&CI);
6939   
6940   // Intrinsics cannot occur in an invoke, so handle them here instead of in
6941   // visitCallSite.
6942   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6943     bool Changed = false;
6944
6945     // memmove/cpy/set of zero bytes is a noop.
6946     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6947       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6948
6949       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6950         if (CI->getZExtValue() == 1) {
6951           // Replace the instruction with just byte operations.  We would
6952           // transform other cases to loads/stores, but we don't know if
6953           // alignment is sufficient.
6954         }
6955     }
6956
6957     // If we have a memmove and the source operation is a constant global,
6958     // then the source and dest pointers can't alias, so we can change this
6959     // into a call to memcpy.
6960     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6961       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6962         if (GVSrc->isConstant()) {
6963           Module *M = CI.getParent()->getParent()->getParent();
6964           const char *Name;
6965           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
6966               Type::Int32Ty)
6967             Name = "llvm.memcpy.i32";
6968           else
6969             Name = "llvm.memcpy.i64";
6970           Constant *MemCpy = M->getOrInsertFunction(Name,
6971                                      CI.getCalledFunction()->getFunctionType());
6972           CI.setOperand(0, MemCpy);
6973           Changed = true;
6974         }
6975     }
6976
6977     // If we can determine a pointer alignment that is bigger than currently
6978     // set, update the alignment.
6979     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6980       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6981       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6982       unsigned Align = std::min(Alignment1, Alignment2);
6983       if (MI->getAlignment()->getZExtValue() < Align) {
6984         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
6985         Changed = true;
6986       }
6987     } else if (isa<MemSetInst>(MI)) {
6988       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6989       if (MI->getAlignment()->getZExtValue() < Alignment) {
6990         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
6991         Changed = true;
6992       }
6993     }
6994           
6995     if (Changed) return II;
6996   } else {
6997     switch (II->getIntrinsicID()) {
6998     default: break;
6999     case Intrinsic::ppc_altivec_lvx:
7000     case Intrinsic::ppc_altivec_lvxl:
7001     case Intrinsic::x86_sse_loadu_ps:
7002     case Intrinsic::x86_sse2_loadu_pd:
7003     case Intrinsic::x86_sse2_loadu_dq:
7004       // Turn PPC lvx     -> load if the pointer is known aligned.
7005       // Turn X86 loadups -> load if the pointer is known aligned.
7006       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7007         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7008                                       PointerType::get(II->getType()), CI);
7009         return new LoadInst(Ptr);
7010       }
7011       break;
7012     case Intrinsic::ppc_altivec_stvx:
7013     case Intrinsic::ppc_altivec_stvxl:
7014       // Turn stvx -> store if the pointer is known aligned.
7015       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7016         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7017         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7018                                       OpPtrTy, CI);
7019         return new StoreInst(II->getOperand(1), Ptr);
7020       }
7021       break;
7022     case Intrinsic::x86_sse_storeu_ps:
7023     case Intrinsic::x86_sse2_storeu_pd:
7024     case Intrinsic::x86_sse2_storeu_dq:
7025     case Intrinsic::x86_sse2_storel_dq:
7026       // Turn X86 storeu -> store if the pointer is known aligned.
7027       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7028         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7029         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7030                                       OpPtrTy, CI);
7031         return new StoreInst(II->getOperand(2), Ptr);
7032       }
7033       break;
7034       
7035     case Intrinsic::x86_sse_cvttss2si: {
7036       // These intrinsics only demands the 0th element of its input vector.  If
7037       // we can simplify the input based on that, do so now.
7038       uint64_t UndefElts;
7039       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7040                                                 UndefElts)) {
7041         II->setOperand(1, V);
7042         return II;
7043       }
7044       break;
7045     }
7046       
7047     case Intrinsic::ppc_altivec_vperm:
7048       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7049       if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7050         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7051         
7052         // Check that all of the elements are integer constants or undefs.
7053         bool AllEltsOk = true;
7054         for (unsigned i = 0; i != 16; ++i) {
7055           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7056               !isa<UndefValue>(Mask->getOperand(i))) {
7057             AllEltsOk = false;
7058             break;
7059           }
7060         }
7061         
7062         if (AllEltsOk) {
7063           // Cast the input vectors to byte vectors.
7064           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7065                                         II->getOperand(1), Mask->getType(), CI);
7066           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7067                                         II->getOperand(2), Mask->getType(), CI);
7068           Value *Result = UndefValue::get(Op0->getType());
7069           
7070           // Only extract each element once.
7071           Value *ExtractedElts[32];
7072           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7073           
7074           for (unsigned i = 0; i != 16; ++i) {
7075             if (isa<UndefValue>(Mask->getOperand(i)))
7076               continue;
7077             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7078             Idx &= 31;  // Match the hardware behavior.
7079             
7080             if (ExtractedElts[Idx] == 0) {
7081               Instruction *Elt = 
7082                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7083               InsertNewInstBefore(Elt, CI);
7084               ExtractedElts[Idx] = Elt;
7085             }
7086           
7087             // Insert this value into the result vector.
7088             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7089             InsertNewInstBefore(cast<Instruction>(Result), CI);
7090           }
7091           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7092         }
7093       }
7094       break;
7095
7096     case Intrinsic::stackrestore: {
7097       // If the save is right next to the restore, remove the restore.  This can
7098       // happen when variable allocas are DCE'd.
7099       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7100         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7101           BasicBlock::iterator BI = SS;
7102           if (&*++BI == II)
7103             return EraseInstFromFunction(CI);
7104         }
7105       }
7106       
7107       // If the stack restore is in a return/unwind block and if there are no
7108       // allocas or calls between the restore and the return, nuke the restore.
7109       TerminatorInst *TI = II->getParent()->getTerminator();
7110       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7111         BasicBlock::iterator BI = II;
7112         bool CannotRemove = false;
7113         for (++BI; &*BI != TI; ++BI) {
7114           if (isa<AllocaInst>(BI) ||
7115               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7116             CannotRemove = true;
7117             break;
7118           }
7119         }
7120         if (!CannotRemove)
7121           return EraseInstFromFunction(CI);
7122       }
7123       break;
7124     }
7125     }
7126   }
7127
7128   return visitCallSite(II);
7129 }
7130
7131 // InvokeInst simplification
7132 //
7133 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7134   return visitCallSite(&II);
7135 }
7136
7137 // visitCallSite - Improvements for call and invoke instructions.
7138 //
7139 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7140   bool Changed = false;
7141
7142   // If the callee is a constexpr cast of a function, attempt to move the cast
7143   // to the arguments of the call/invoke.
7144   if (transformConstExprCastCall(CS)) return 0;
7145
7146   Value *Callee = CS.getCalledValue();
7147
7148   if (Function *CalleeF = dyn_cast<Function>(Callee))
7149     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7150       Instruction *OldCall = CS.getInstruction();
7151       // If the call and callee calling conventions don't match, this call must
7152       // be unreachable, as the call is undefined.
7153       new StoreInst(ConstantInt::getTrue(),
7154                     UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
7155       if (!OldCall->use_empty())
7156         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7157       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7158         return EraseInstFromFunction(*OldCall);
7159       return 0;
7160     }
7161
7162   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7163     // This instruction is not reachable, just remove it.  We insert a store to
7164     // undef so that we know that this code is not reachable, despite the fact
7165     // that we can't modify the CFG here.
7166     new StoreInst(ConstantInt::getTrue(),
7167                   UndefValue::get(PointerType::get(Type::Int1Ty)),
7168                   CS.getInstruction());
7169
7170     if (!CS.getInstruction()->use_empty())
7171       CS.getInstruction()->
7172         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7173
7174     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7175       // Don't break the CFG, insert a dummy cond branch.
7176       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7177                      ConstantInt::getTrue(), II);
7178     }
7179     return EraseInstFromFunction(*CS.getInstruction());
7180   }
7181
7182   const PointerType *PTy = cast<PointerType>(Callee->getType());
7183   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7184   if (FTy->isVarArg()) {
7185     // See if we can optimize any arguments passed through the varargs area of
7186     // the call.
7187     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7188            E = CS.arg_end(); I != E; ++I)
7189       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7190         // If this cast does not effect the value passed through the varargs
7191         // area, we can eliminate the use of the cast.
7192         Value *Op = CI->getOperand(0);
7193         if (CI->isLosslessCast()) {
7194           *I = Op;
7195           Changed = true;
7196         }
7197       }
7198   }
7199
7200   return Changed ? CS.getInstruction() : 0;
7201 }
7202
7203 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7204 // attempt to move the cast to the arguments of the call/invoke.
7205 //
7206 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7207   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7208   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7209   if (CE->getOpcode() != Instruction::BitCast || 
7210       !isa<Function>(CE->getOperand(0)))
7211     return false;
7212   Function *Callee = cast<Function>(CE->getOperand(0));
7213   Instruction *Caller = CS.getInstruction();
7214
7215   // Okay, this is a cast from a function to a different type.  Unless doing so
7216   // would cause a type conversion of one of our arguments, change this call to
7217   // be a direct call with arguments casted to the appropriate types.
7218   //
7219   const FunctionType *FT = Callee->getFunctionType();
7220   const Type *OldRetTy = Caller->getType();
7221
7222   // Check to see if we are changing the return type...
7223   if (OldRetTy != FT->getReturnType()) {
7224     if (Callee->isExternal() && !Caller->use_empty() && 
7225         OldRetTy != FT->getReturnType() &&
7226         // Conversion is ok if changing from pointer to int of same size.
7227         !(isa<PointerType>(FT->getReturnType()) &&
7228           TD->getIntPtrType() == OldRetTy))
7229       return false;   // Cannot transform this return value.
7230
7231     // If the callsite is an invoke instruction, and the return value is used by
7232     // a PHI node in a successor, we cannot change the return type of the call
7233     // because there is no place to put the cast instruction (without breaking
7234     // the critical edge).  Bail out in this case.
7235     if (!Caller->use_empty())
7236       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7237         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7238              UI != E; ++UI)
7239           if (PHINode *PN = dyn_cast<PHINode>(*UI))
7240             if (PN->getParent() == II->getNormalDest() ||
7241                 PN->getParent() == II->getUnwindDest())
7242               return false;
7243   }
7244
7245   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7246   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7247
7248   CallSite::arg_iterator AI = CS.arg_begin();
7249   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7250     const Type *ParamTy = FT->getParamType(i);
7251     const Type *ActTy = (*AI)->getType();
7252     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7253     //Either we can cast directly, or we can upconvert the argument
7254     bool isConvertible = ActTy == ParamTy ||
7255       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
7256       (ParamTy->isInteger() && ActTy->isInteger() &&
7257        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7258       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7259        && c->getSExtValue() > 0);
7260     if (Callee->isExternal() && !isConvertible) return false;
7261   }
7262
7263   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7264       Callee->isExternal())
7265     return false;   // Do not delete arguments unless we have a function body...
7266
7267   // Okay, we decided that this is a safe thing to do: go ahead and start
7268   // inserting cast instructions as necessary...
7269   std::vector<Value*> Args;
7270   Args.reserve(NumActualArgs);
7271
7272   AI = CS.arg_begin();
7273   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7274     const Type *ParamTy = FT->getParamType(i);
7275     if ((*AI)->getType() == ParamTy) {
7276       Args.push_back(*AI);
7277     } else {
7278       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7279           false, ParamTy, false);
7280       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7281       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7282     }
7283   }
7284
7285   // If the function takes more arguments than the call was taking, add them
7286   // now...
7287   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7288     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7289
7290   // If we are removing arguments to the function, emit an obnoxious warning...
7291   if (FT->getNumParams() < NumActualArgs)
7292     if (!FT->isVarArg()) {
7293       cerr << "WARNING: While resolving call to function '"
7294            << Callee->getName() << "' arguments were dropped!\n";
7295     } else {
7296       // Add all of the arguments in their promoted form to the arg list...
7297       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7298         const Type *PTy = getPromotedType((*AI)->getType());
7299         if (PTy != (*AI)->getType()) {
7300           // Must promote to pass through va_arg area!
7301           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
7302                                                                 PTy, false);
7303           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7304           InsertNewInstBefore(Cast, *Caller);
7305           Args.push_back(Cast);
7306         } else {
7307           Args.push_back(*AI);
7308         }
7309       }
7310     }
7311
7312   if (FT->getReturnType() == Type::VoidTy)
7313     Caller->setName("");   // Void type should not have a name...
7314
7315   Instruction *NC;
7316   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7317     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7318                         Args, Caller->getName(), Caller);
7319     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7320   } else {
7321     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
7322     if (cast<CallInst>(Caller)->isTailCall())
7323       cast<CallInst>(NC)->setTailCall();
7324    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7325   }
7326
7327   // Insert a cast of the return type as necessary...
7328   Value *NV = NC;
7329   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7330     if (NV->getType() != Type::VoidTy) {
7331       const Type *CallerTy = Caller->getType();
7332       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
7333                                                             CallerTy, false);
7334       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7335
7336       // If this is an invoke instruction, we should insert it after the first
7337       // non-phi, instruction in the normal successor block.
7338       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7339         BasicBlock::iterator I = II->getNormalDest()->begin();
7340         while (isa<PHINode>(I)) ++I;
7341         InsertNewInstBefore(NC, *I);
7342       } else {
7343         // Otherwise, it's a call, just insert cast right after the call instr
7344         InsertNewInstBefore(NC, *Caller);
7345       }
7346       AddUsersToWorkList(*Caller);
7347     } else {
7348       NV = UndefValue::get(Caller->getType());
7349     }
7350   }
7351
7352   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7353     Caller->replaceAllUsesWith(NV);
7354   Caller->getParent()->getInstList().erase(Caller);
7355   removeFromWorkList(Caller);
7356   return true;
7357 }
7358
7359 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7360 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7361 /// and a single binop.
7362 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7363   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7364   assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7365          isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
7366   unsigned Opc = FirstInst->getOpcode();
7367   Value *LHSVal = FirstInst->getOperand(0);
7368   Value *RHSVal = FirstInst->getOperand(1);
7369     
7370   const Type *LHSType = LHSVal->getType();
7371   const Type *RHSType = RHSVal->getType();
7372   
7373   // Scan to see if all operands are the same opcode, all have one use, and all
7374   // kill their operands (i.e. the operands have one use).
7375   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7376     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7377     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7378         // Verify type of the LHS matches so we don't fold cmp's of different
7379         // types or GEP's with different index types.
7380         I->getOperand(0)->getType() != LHSType ||
7381         I->getOperand(1)->getType() != RHSType)
7382       return 0;
7383
7384     // If they are CmpInst instructions, check their predicates
7385     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7386       if (cast<CmpInst>(I)->getPredicate() !=
7387           cast<CmpInst>(FirstInst)->getPredicate())
7388         return 0;
7389     
7390     // Keep track of which operand needs a phi node.
7391     if (I->getOperand(0) != LHSVal) LHSVal = 0;
7392     if (I->getOperand(1) != RHSVal) RHSVal = 0;
7393   }
7394   
7395   // Otherwise, this is safe to transform, determine if it is profitable.
7396
7397   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7398   // Indexes are often folded into load/store instructions, so we don't want to
7399   // hide them behind a phi.
7400   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7401     return 0;
7402   
7403   Value *InLHS = FirstInst->getOperand(0);
7404   Value *InRHS = FirstInst->getOperand(1);
7405   PHINode *NewLHS = 0, *NewRHS = 0;
7406   if (LHSVal == 0) {
7407     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7408     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7409     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7410     InsertNewInstBefore(NewLHS, PN);
7411     LHSVal = NewLHS;
7412   }
7413   
7414   if (RHSVal == 0) {
7415     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7416     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7417     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7418     InsertNewInstBefore(NewRHS, PN);
7419     RHSVal = NewRHS;
7420   }
7421   
7422   // Add all operands to the new PHIs.
7423   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7424     if (NewLHS) {
7425       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7426       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7427     }
7428     if (NewRHS) {
7429       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7430       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7431     }
7432   }
7433     
7434   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7435     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7436   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7437     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
7438                            RHSVal);
7439   else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7440     return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7441   else {
7442     assert(isa<GetElementPtrInst>(FirstInst));
7443     return new GetElementPtrInst(LHSVal, RHSVal);
7444   }
7445 }
7446
7447 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7448 /// of the block that defines it.  This means that it must be obvious the value
7449 /// of the load is not changed from the point of the load to the end of the
7450 /// block it is in.
7451 static bool isSafeToSinkLoad(LoadInst *L) {
7452   BasicBlock::iterator BBI = L, E = L->getParent()->end();
7453   
7454   for (++BBI; BBI != E; ++BBI)
7455     if (BBI->mayWriteToMemory())
7456       return false;
7457   return true;
7458 }
7459
7460
7461 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7462 // operator and they all are only used by the PHI, PHI together their
7463 // inputs, and do the operation once, to the result of the PHI.
7464 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7465   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7466
7467   // Scan the instruction, looking for input operations that can be folded away.
7468   // If all input operands to the phi are the same instruction (e.g. a cast from
7469   // the same type or "+42") we can pull the operation through the PHI, reducing
7470   // code size and simplifying code.
7471   Constant *ConstantOp = 0;
7472   const Type *CastSrcTy = 0;
7473   bool isVolatile = false;
7474   if (isa<CastInst>(FirstInst)) {
7475     CastSrcTy = FirstInst->getOperand(0)->getType();
7476   } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7477              isa<CmpInst>(FirstInst)) {
7478     // Can fold binop, compare or shift here if the RHS is a constant, 
7479     // otherwise call FoldPHIArgBinOpIntoPHI.
7480     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7481     if (ConstantOp == 0)
7482       return FoldPHIArgBinOpIntoPHI(PN);
7483   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7484     isVolatile = LI->isVolatile();
7485     // We can't sink the load if the loaded value could be modified between the
7486     // load and the PHI.
7487     if (LI->getParent() != PN.getIncomingBlock(0) ||
7488         !isSafeToSinkLoad(LI))
7489       return 0;
7490   } else if (isa<GetElementPtrInst>(FirstInst)) {
7491     if (FirstInst->getNumOperands() == 2)
7492       return FoldPHIArgBinOpIntoPHI(PN);
7493     // Can't handle general GEPs yet.
7494     return 0;
7495   } else {
7496     return 0;  // Cannot fold this operation.
7497   }
7498
7499   // Check to see if all arguments are the same operation.
7500   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7501     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7502     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7503     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
7504       return 0;
7505     if (CastSrcTy) {
7506       if (I->getOperand(0)->getType() != CastSrcTy)
7507         return 0;  // Cast operation must match.
7508     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7509       // We can't sink the load if the loaded value could be modified between 
7510       // the load and the PHI.
7511       if (LI->isVolatile() != isVolatile ||
7512           LI->getParent() != PN.getIncomingBlock(i) ||
7513           !isSafeToSinkLoad(LI))
7514         return 0;
7515     } else if (I->getOperand(1) != ConstantOp) {
7516       return 0;
7517     }
7518   }
7519
7520   // Okay, they are all the same operation.  Create a new PHI node of the
7521   // correct type, and PHI together all of the LHS's of the instructions.
7522   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7523                                PN.getName()+".in");
7524   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7525
7526   Value *InVal = FirstInst->getOperand(0);
7527   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7528
7529   // Add all operands to the new PHI.
7530   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7531     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7532     if (NewInVal != InVal)
7533       InVal = 0;
7534     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7535   }
7536
7537   Value *PhiVal;
7538   if (InVal) {
7539     // The new PHI unions all of the same values together.  This is really
7540     // common, so we handle it intelligently here for compile-time speed.
7541     PhiVal = InVal;
7542     delete NewPN;
7543   } else {
7544     InsertNewInstBefore(NewPN, PN);
7545     PhiVal = NewPN;
7546   }
7547
7548   // Insert and return the new operation.
7549   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7550     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7551   else if (isa<LoadInst>(FirstInst))
7552     return new LoadInst(PhiVal, "", isVolatile);
7553   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7554     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7555   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7556     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
7557                            PhiVal, ConstantOp);
7558   else
7559     return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
7560                          PhiVal, ConstantOp);
7561 }
7562
7563 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7564 /// that is dead.
7565 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7566   if (PN->use_empty()) return true;
7567   if (!PN->hasOneUse()) return false;
7568
7569   // Remember this node, and if we find the cycle, return.
7570   if (!PotentiallyDeadPHIs.insert(PN).second)
7571     return true;
7572
7573   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7574     return DeadPHICycle(PU, PotentiallyDeadPHIs);
7575
7576   return false;
7577 }
7578
7579 // PHINode simplification
7580 //
7581 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7582   // If LCSSA is around, don't mess with Phi nodes
7583   if (mustPreserveAnalysisID(LCSSAID)) return 0;
7584   
7585   if (Value *V = PN.hasConstantValue())
7586     return ReplaceInstUsesWith(PN, V);
7587
7588   // If all PHI operands are the same operation, pull them through the PHI,
7589   // reducing code size.
7590   if (isa<Instruction>(PN.getIncomingValue(0)) &&
7591       PN.getIncomingValue(0)->hasOneUse())
7592     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7593       return Result;
7594
7595   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
7596   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7597   // PHI)... break the cycle.
7598   if (PN.hasOneUse()) {
7599     Instruction *PHIUser = cast<Instruction>(PN.use_back());
7600     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
7601       std::set<PHINode*> PotentiallyDeadPHIs;
7602       PotentiallyDeadPHIs.insert(&PN);
7603       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7604         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7605     }
7606    
7607     // If this phi has a single use, and if that use just computes a value for
7608     // the next iteration of a loop, delete the phi.  This occurs with unused
7609     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
7610     // common case here is good because the only other things that catch this
7611     // are induction variable analysis (sometimes) and ADCE, which is only run
7612     // late.
7613     if (PHIUser->hasOneUse() &&
7614         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7615         PHIUser->use_back() == &PN) {
7616       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7617     }
7618   }
7619
7620   return 0;
7621 }
7622
7623 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7624                                    Instruction *InsertPoint,
7625                                    InstCombiner *IC) {
7626   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7627   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
7628   // We must cast correctly to the pointer type. Ensure that we
7629   // sign extend the integer value if it is smaller as this is
7630   // used for address computation.
7631   Instruction::CastOps opcode = 
7632      (VTySize < PtrSize ? Instruction::SExt :
7633       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7634   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
7635 }
7636
7637
7638 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7639   Value *PtrOp = GEP.getOperand(0);
7640   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
7641   // If so, eliminate the noop.
7642   if (GEP.getNumOperands() == 1)
7643     return ReplaceInstUsesWith(GEP, PtrOp);
7644
7645   if (isa<UndefValue>(GEP.getOperand(0)))
7646     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7647
7648   bool HasZeroPointerIndex = false;
7649   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7650     HasZeroPointerIndex = C->isNullValue();
7651
7652   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7653     return ReplaceInstUsesWith(GEP, PtrOp);
7654
7655   // Eliminate unneeded casts for indices.
7656   bool MadeChange = false;
7657   gep_type_iterator GTI = gep_type_begin(GEP);
7658   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7659     if (isa<SequentialType>(*GTI)) {
7660       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7661         if (CI->getOpcode() == Instruction::ZExt ||
7662             CI->getOpcode() == Instruction::SExt) {
7663           const Type *SrcTy = CI->getOperand(0)->getType();
7664           // We can eliminate a cast from i32 to i64 iff the target 
7665           // is a 32-bit pointer target.
7666           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7667             MadeChange = true;
7668             GEP.setOperand(i, CI->getOperand(0));
7669           }
7670         }
7671       }
7672       // If we are using a wider index than needed for this platform, shrink it
7673       // to what we need.  If the incoming value needs a cast instruction,
7674       // insert it.  This explicit cast can make subsequent optimizations more
7675       // obvious.
7676       Value *Op = GEP.getOperand(i);
7677       if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
7678         if (Constant *C = dyn_cast<Constant>(Op)) {
7679           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
7680           MadeChange = true;
7681         } else {
7682           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7683                                 GEP);
7684           GEP.setOperand(i, Op);
7685           MadeChange = true;
7686         }
7687     }
7688   if (MadeChange) return &GEP;
7689
7690   // Combine Indices - If the source pointer to this getelementptr instruction
7691   // is a getelementptr instruction, combine the indices of the two
7692   // getelementptr instructions into a single instruction.
7693   //
7694   std::vector<Value*> SrcGEPOperands;
7695   if (User *Src = dyn_castGetElementPtr(PtrOp))
7696     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
7697
7698   if (!SrcGEPOperands.empty()) {
7699     // Note that if our source is a gep chain itself that we wait for that
7700     // chain to be resolved before we perform this transformation.  This
7701     // avoids us creating a TON of code in some cases.
7702     //
7703     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7704         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7705       return 0;   // Wait until our source is folded to completion.
7706
7707     std::vector<Value *> Indices;
7708
7709     // Find out whether the last index in the source GEP is a sequential idx.
7710     bool EndsWithSequential = false;
7711     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7712            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7713       EndsWithSequential = !isa<StructType>(*I);
7714
7715     // Can we combine the two pointer arithmetics offsets?
7716     if (EndsWithSequential) {
7717       // Replace: gep (gep %P, long B), long A, ...
7718       // With:    T = long A+B; gep %P, T, ...
7719       //
7720       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7721       if (SO1 == Constant::getNullValue(SO1->getType())) {
7722         Sum = GO1;
7723       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7724         Sum = SO1;
7725       } else {
7726         // If they aren't the same type, convert both to an integer of the
7727         // target's pointer size.
7728         if (SO1->getType() != GO1->getType()) {
7729           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7730             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
7731           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7732             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
7733           } else {
7734             unsigned PS = TD->getPointerSize();
7735             if (TD->getTypeSize(SO1->getType()) == PS) {
7736               // Convert GO1 to SO1's type.
7737               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
7738
7739             } else if (TD->getTypeSize(GO1->getType()) == PS) {
7740               // Convert SO1 to GO1's type.
7741               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
7742             } else {
7743               const Type *PT = TD->getIntPtrType();
7744               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7745               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
7746             }
7747           }
7748         }
7749         if (isa<Constant>(SO1) && isa<Constant>(GO1))
7750           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7751         else {
7752           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7753           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7754         }
7755       }
7756
7757       // Recycle the GEP we already have if possible.
7758       if (SrcGEPOperands.size() == 2) {
7759         GEP.setOperand(0, SrcGEPOperands[0]);
7760         GEP.setOperand(1, Sum);
7761         return &GEP;
7762       } else {
7763         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7764                        SrcGEPOperands.end()-1);
7765         Indices.push_back(Sum);
7766         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7767       }
7768     } else if (isa<Constant>(*GEP.idx_begin()) &&
7769                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7770                SrcGEPOperands.size() != 1) {
7771       // Otherwise we can do the fold if the first index of the GEP is a zero
7772       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7773                      SrcGEPOperands.end());
7774       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7775     }
7776
7777     if (!Indices.empty())
7778       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7779
7780   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7781     // GEP of global variable.  If all of the indices for this GEP are
7782     // constants, we can promote this to a constexpr instead of an instruction.
7783
7784     // Scan for nonconstants...
7785     std::vector<Constant*> Indices;
7786     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7787     for (; I != E && isa<Constant>(*I); ++I)
7788       Indices.push_back(cast<Constant>(*I));
7789
7790     if (I == E) {  // If they are all constants...
7791       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
7792
7793       // Replace all uses of the GEP with the new constexpr...
7794       return ReplaceInstUsesWith(GEP, CE);
7795     }
7796   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
7797     if (!isa<PointerType>(X->getType())) {
7798       // Not interesting.  Source pointer must be a cast from pointer.
7799     } else if (HasZeroPointerIndex) {
7800       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7801       // into     : GEP [10 x ubyte]* X, long 0, ...
7802       //
7803       // This occurs when the program declares an array extern like "int X[];"
7804       //
7805       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7806       const PointerType *XTy = cast<PointerType>(X->getType());
7807       if (const ArrayType *XATy =
7808           dyn_cast<ArrayType>(XTy->getElementType()))
7809         if (const ArrayType *CATy =
7810             dyn_cast<ArrayType>(CPTy->getElementType()))
7811           if (CATy->getElementType() == XATy->getElementType()) {
7812             // At this point, we know that the cast source type is a pointer
7813             // to an array of the same type as the destination pointer
7814             // array.  Because the array type is never stepped over (there
7815             // is a leading zero) we can fold the cast into this GEP.
7816             GEP.setOperand(0, X);
7817             return &GEP;
7818           }
7819     } else if (GEP.getNumOperands() == 2) {
7820       // Transform things like:
7821       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7822       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7823       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7824       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7825       if (isa<ArrayType>(SrcElTy) &&
7826           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7827           TD->getTypeSize(ResElTy)) {
7828         Value *V = InsertNewInstBefore(
7829                new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7830                                      GEP.getOperand(1), GEP.getName()), GEP);
7831         // V and GEP are both pointer types --> BitCast
7832         return new BitCastInst(V, GEP.getType());
7833       }
7834       
7835       // Transform things like:
7836       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7837       //   (where tmp = 8*tmp2) into:
7838       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7839       
7840       if (isa<ArrayType>(SrcElTy) &&
7841           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
7842         uint64_t ArrayEltSize =
7843             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7844         
7845         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
7846         // allow either a mul, shift, or constant here.
7847         Value *NewIdx = 0;
7848         ConstantInt *Scale = 0;
7849         if (ArrayEltSize == 1) {
7850           NewIdx = GEP.getOperand(1);
7851           Scale = ConstantInt::get(NewIdx->getType(), 1);
7852         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7853           NewIdx = ConstantInt::get(CI->getType(), 1);
7854           Scale = CI;
7855         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7856           if (Inst->getOpcode() == Instruction::Shl &&
7857               isa<ConstantInt>(Inst->getOperand(1))) {
7858             unsigned ShAmt =
7859               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7860             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7861             NewIdx = Inst->getOperand(0);
7862           } else if (Inst->getOpcode() == Instruction::Mul &&
7863                      isa<ConstantInt>(Inst->getOperand(1))) {
7864             Scale = cast<ConstantInt>(Inst->getOperand(1));
7865             NewIdx = Inst->getOperand(0);
7866           }
7867         }
7868
7869         // If the index will be to exactly the right offset with the scale taken
7870         // out, perform the transformation.
7871         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7872           if (isa<ConstantInt>(Scale))
7873             Scale = ConstantInt::get(Scale->getType(),
7874                                       Scale->getZExtValue() / ArrayEltSize);
7875           if (Scale->getZExtValue() != 1) {
7876             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7877                                                        true /*SExt*/);
7878             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7879             NewIdx = InsertNewInstBefore(Sc, GEP);
7880           }
7881
7882           // Insert the new GEP instruction.
7883           Instruction *NewGEP =
7884             new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7885                                   NewIdx, GEP.getName());
7886           NewGEP = InsertNewInstBefore(NewGEP, GEP);
7887           // The NewGEP must be pointer typed, so must the old one -> BitCast
7888           return new BitCastInst(NewGEP, GEP.getType());
7889         }
7890       }
7891     }
7892   }
7893
7894   return 0;
7895 }
7896
7897 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7898   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7899   if (AI.isArrayAllocation())    // Check C != 1
7900     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7901       const Type *NewTy = 
7902         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7903       AllocationInst *New = 0;
7904
7905       // Create and insert the replacement instruction...
7906       if (isa<MallocInst>(AI))
7907         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7908       else {
7909         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7910         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7911       }
7912
7913       InsertNewInstBefore(New, AI);
7914
7915       // Scan to the end of the allocation instructions, to skip over a block of
7916       // allocas if possible...
7917       //
7918       BasicBlock::iterator It = New;
7919       while (isa<AllocationInst>(*It)) ++It;
7920
7921       // Now that I is pointing to the first non-allocation-inst in the block,
7922       // insert our getelementptr instruction...
7923       //
7924       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
7925       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7926                                        New->getName()+".sub", It);
7927
7928       // Now make everything use the getelementptr instead of the original
7929       // allocation.
7930       return ReplaceInstUsesWith(AI, V);
7931     } else if (isa<UndefValue>(AI.getArraySize())) {
7932       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7933     }
7934
7935   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7936   // Note that we only do this for alloca's, because malloc should allocate and
7937   // return a unique pointer, even for a zero byte allocation.
7938   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7939       TD->getTypeSize(AI.getAllocatedType()) == 0)
7940     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7941
7942   return 0;
7943 }
7944
7945 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7946   Value *Op = FI.getOperand(0);
7947
7948   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7949   if (CastInst *CI = dyn_cast<CastInst>(Op))
7950     if (isa<PointerType>(CI->getOperand(0)->getType())) {
7951       FI.setOperand(0, CI->getOperand(0));
7952       return &FI;
7953     }
7954
7955   // free undef -> unreachable.
7956   if (isa<UndefValue>(Op)) {
7957     // Insert a new store to null because we cannot modify the CFG here.
7958     new StoreInst(ConstantInt::getTrue(),
7959                   UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
7960     return EraseInstFromFunction(FI);
7961   }
7962
7963   // If we have 'free null' delete the instruction.  This can happen in stl code
7964   // when lots of inlining happens.
7965   if (isa<ConstantPointerNull>(Op))
7966     return EraseInstFromFunction(FI);
7967
7968   return 0;
7969 }
7970
7971
7972 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7973 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7974   User *CI = cast<User>(LI.getOperand(0));
7975   Value *CastOp = CI->getOperand(0);
7976
7977   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7978   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7979     const Type *SrcPTy = SrcTy->getElementType();
7980
7981     if ((DestPTy->isInteger() && DestPTy != Type::Int1Ty) ||
7982         isa<PointerType>(DestPTy) || isa<PackedType>(DestPTy)) {
7983       // If the source is an array, the code below will not succeed.  Check to
7984       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
7985       // constants.
7986       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7987         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7988           if (ASrcTy->getNumElements() != 0) {
7989             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
7990             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7991             SrcTy = cast<PointerType>(CastOp->getType());
7992             SrcPTy = SrcTy->getElementType();
7993           }
7994
7995       if (((SrcPTy->isInteger() && SrcPTy != Type::Int1Ty) ||
7996            isa<PointerType>(SrcPTy) || isa<PackedType>(SrcPTy)) &&
7997           // Do not allow turning this into a load of an integer, which is then
7998           // casted to a pointer, this pessimizes pointer analysis a lot.
7999           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8000           IC.getTargetData().getTypeSize(SrcPTy) ==
8001                IC.getTargetData().getTypeSize(DestPTy)) {
8002
8003         // Okay, we are casting from one integer or pointer type to another of
8004         // the same size.  Instead of casting the pointer before the load, cast
8005         // the result of the loaded value.
8006         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8007                                                              CI->getName(),
8008                                                          LI.isVolatile()),LI);
8009         // Now cast the result of the load.
8010         return new BitCastInst(NewLoad, LI.getType());
8011       }
8012     }
8013   }
8014   return 0;
8015 }
8016
8017 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8018 /// from this value cannot trap.  If it is not obviously safe to load from the
8019 /// specified pointer, we do a quick local scan of the basic block containing
8020 /// ScanFrom, to determine if the address is already accessed.
8021 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8022   // If it is an alloca or global variable, it is always safe to load from.
8023   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8024
8025   // Otherwise, be a little bit agressive by scanning the local block where we
8026   // want to check to see if the pointer is already being loaded or stored
8027   // from/to.  If so, the previous load or store would have already trapped,
8028   // so there is no harm doing an extra load (also, CSE will later eliminate
8029   // the load entirely).
8030   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8031
8032   while (BBI != E) {
8033     --BBI;
8034
8035     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8036       if (LI->getOperand(0) == V) return true;
8037     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8038       if (SI->getOperand(1) == V) return true;
8039
8040   }
8041   return false;
8042 }
8043
8044 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8045   Value *Op = LI.getOperand(0);
8046
8047   // load (cast X) --> cast (load X) iff safe
8048   if (isa<CastInst>(Op))
8049     if (Instruction *Res = InstCombineLoadCast(*this, LI))
8050       return Res;
8051
8052   // None of the following transforms are legal for volatile loads.
8053   if (LI.isVolatile()) return 0;
8054   
8055   if (&LI.getParent()->front() != &LI) {
8056     BasicBlock::iterator BBI = &LI; --BBI;
8057     // If the instruction immediately before this is a store to the same
8058     // address, do a simple form of store->load forwarding.
8059     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8060       if (SI->getOperand(1) == LI.getOperand(0))
8061         return ReplaceInstUsesWith(LI, SI->getOperand(0));
8062     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8063       if (LIB->getOperand(0) == LI.getOperand(0))
8064         return ReplaceInstUsesWith(LI, LIB);
8065   }
8066
8067   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8068     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8069         isa<UndefValue>(GEPI->getOperand(0))) {
8070       // Insert a new store to null instruction before the load to indicate
8071       // that this code is not reachable.  We do this instead of inserting
8072       // an unreachable instruction directly because we cannot modify the
8073       // CFG.
8074       new StoreInst(UndefValue::get(LI.getType()),
8075                     Constant::getNullValue(Op->getType()), &LI);
8076       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8077     }
8078
8079   if (Constant *C = dyn_cast<Constant>(Op)) {
8080     // load null/undef -> undef
8081     if ((C->isNullValue() || isa<UndefValue>(C))) {
8082       // Insert a new store to null instruction before the load to indicate that
8083       // this code is not reachable.  We do this instead of inserting an
8084       // unreachable instruction directly because we cannot modify the CFG.
8085       new StoreInst(UndefValue::get(LI.getType()),
8086                     Constant::getNullValue(Op->getType()), &LI);
8087       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8088     }
8089
8090     // Instcombine load (constant global) into the value loaded.
8091     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8092       if (GV->isConstant() && !GV->isExternal())
8093         return ReplaceInstUsesWith(LI, GV->getInitializer());
8094
8095     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8096     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8097       if (CE->getOpcode() == Instruction::GetElementPtr) {
8098         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8099           if (GV->isConstant() && !GV->isExternal())
8100             if (Constant *V = 
8101                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8102               return ReplaceInstUsesWith(LI, V);
8103         if (CE->getOperand(0)->isNullValue()) {
8104           // Insert a new store to null instruction before the load to indicate
8105           // that this code is not reachable.  We do this instead of inserting
8106           // an unreachable instruction directly because we cannot modify the
8107           // CFG.
8108           new StoreInst(UndefValue::get(LI.getType()),
8109                         Constant::getNullValue(Op->getType()), &LI);
8110           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8111         }
8112
8113       } else if (CE->isCast()) {
8114         if (Instruction *Res = InstCombineLoadCast(*this, LI))
8115           return Res;
8116       }
8117   }
8118
8119   if (Op->hasOneUse()) {
8120     // Change select and PHI nodes to select values instead of addresses: this
8121     // helps alias analysis out a lot, allows many others simplifications, and
8122     // exposes redundancy in the code.
8123     //
8124     // Note that we cannot do the transformation unless we know that the
8125     // introduced loads cannot trap!  Something like this is valid as long as
8126     // the condition is always false: load (select bool %C, int* null, int* %G),
8127     // but it would not be valid if we transformed it to load from null
8128     // unconditionally.
8129     //
8130     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8131       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
8132       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8133           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8134         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8135                                      SI->getOperand(1)->getName()+".val"), LI);
8136         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8137                                      SI->getOperand(2)->getName()+".val"), LI);
8138         return new SelectInst(SI->getCondition(), V1, V2);
8139       }
8140
8141       // load (select (cond, null, P)) -> load P
8142       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8143         if (C->isNullValue()) {
8144           LI.setOperand(0, SI->getOperand(2));
8145           return &LI;
8146         }
8147
8148       // load (select (cond, P, null)) -> load P
8149       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8150         if (C->isNullValue()) {
8151           LI.setOperand(0, SI->getOperand(1));
8152           return &LI;
8153         }
8154     }
8155   }
8156   return 0;
8157 }
8158
8159 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8160 /// when possible.
8161 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8162   User *CI = cast<User>(SI.getOperand(1));
8163   Value *CastOp = CI->getOperand(0);
8164
8165   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8166   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8167     const Type *SrcPTy = SrcTy->getElementType();
8168
8169     if ((DestPTy->isInteger() && DestPTy != Type::Int1Ty) ||
8170         isa<PointerType>(DestPTy)) {
8171       // If the source is an array, the code below will not succeed.  Check to
8172       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8173       // constants.
8174       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8175         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8176           if (ASrcTy->getNumElements() != 0) {
8177             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
8178             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8179             SrcTy = cast<PointerType>(CastOp->getType());
8180             SrcPTy = SrcTy->getElementType();
8181           }
8182
8183       if (((SrcPTy->isInteger() && SrcPTy != Type::Int1Ty) ||
8184            isa<PointerType>(SrcPTy)) &&
8185           IC.getTargetData().getTypeSize(SrcPTy) ==
8186                IC.getTargetData().getTypeSize(DestPTy)) {
8187
8188         // Okay, we are casting from one integer or pointer type to another of
8189         // the same size.  Instead of casting the pointer before 
8190         // the store, cast the value to be stored.
8191         Value *NewCast;
8192         Value *SIOp0 = SI.getOperand(0);
8193         Instruction::CastOps opcode = Instruction::BitCast;
8194         const Type* CastSrcTy = SIOp0->getType();
8195         const Type* CastDstTy = SrcPTy;
8196         if (isa<PointerType>(CastDstTy)) {
8197           if (CastSrcTy->isInteger())
8198             opcode = Instruction::IntToPtr;
8199         } else if (const IntegerType* DITy = dyn_cast<IntegerType>(CastDstTy)) {
8200           if (isa<PointerType>(SIOp0->getType()))
8201             opcode = Instruction::PtrToInt;
8202           else if (const IntegerType* SITy = dyn_cast<IntegerType>(CastSrcTy))
8203             assert(DITy->getBitWidth() == SITy->getBitWidth() &&
8204                    "Illegal store instruction");
8205         }
8206         if (Constant *C = dyn_cast<Constant>(SIOp0))
8207           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
8208         else
8209           NewCast = IC.InsertNewInstBefore(
8210             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
8211             SI);
8212         return new StoreInst(NewCast, CastOp);
8213       }
8214     }
8215   }
8216   return 0;
8217 }
8218
8219 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8220   Value *Val = SI.getOperand(0);
8221   Value *Ptr = SI.getOperand(1);
8222
8223   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
8224     EraseInstFromFunction(SI);
8225     ++NumCombined;
8226     return 0;
8227   }
8228   
8229   // If the RHS is an alloca with a single use, zapify the store, making the
8230   // alloca dead.
8231   if (Ptr->hasOneUse()) {
8232     if (isa<AllocaInst>(Ptr)) {
8233       EraseInstFromFunction(SI);
8234       ++NumCombined;
8235       return 0;
8236     }
8237     
8238     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8239       if (isa<AllocaInst>(GEP->getOperand(0)) &&
8240           GEP->getOperand(0)->hasOneUse()) {
8241         EraseInstFromFunction(SI);
8242         ++NumCombined;
8243         return 0;
8244       }
8245   }
8246
8247   // Do really simple DSE, to catch cases where there are several consequtive
8248   // stores to the same location, separated by a few arithmetic operations. This
8249   // situation often occurs with bitfield accesses.
8250   BasicBlock::iterator BBI = &SI;
8251   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8252        --ScanInsts) {
8253     --BBI;
8254     
8255     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8256       // Prev store isn't volatile, and stores to the same location?
8257       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8258         ++NumDeadStore;
8259         ++BBI;
8260         EraseInstFromFunction(*PrevSI);
8261         continue;
8262       }
8263       break;
8264     }
8265     
8266     // If this is a load, we have to stop.  However, if the loaded value is from
8267     // the pointer we're loading and is producing the pointer we're storing,
8268     // then *this* store is dead (X = load P; store X -> P).
8269     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8270       if (LI == Val && LI->getOperand(0) == Ptr) {
8271         EraseInstFromFunction(SI);
8272         ++NumCombined;
8273         return 0;
8274       }
8275       // Otherwise, this is a load from some other location.  Stores before it
8276       // may not be dead.
8277       break;
8278     }
8279     
8280     // Don't skip over loads or things that can modify memory.
8281     if (BBI->mayWriteToMemory())
8282       break;
8283   }
8284   
8285   
8286   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
8287
8288   // store X, null    -> turns into 'unreachable' in SimplifyCFG
8289   if (isa<ConstantPointerNull>(Ptr)) {
8290     if (!isa<UndefValue>(Val)) {
8291       SI.setOperand(0, UndefValue::get(Val->getType()));
8292       if (Instruction *U = dyn_cast<Instruction>(Val))
8293         WorkList.push_back(U);  // Dropped a use.
8294       ++NumCombined;
8295     }
8296     return 0;  // Do not modify these!
8297   }
8298
8299   // store undef, Ptr -> noop
8300   if (isa<UndefValue>(Val)) {
8301     EraseInstFromFunction(SI);
8302     ++NumCombined;
8303     return 0;
8304   }
8305
8306   // If the pointer destination is a cast, see if we can fold the cast into the
8307   // source instead.
8308   if (isa<CastInst>(Ptr))
8309     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8310       return Res;
8311   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8312     if (CE->isCast())
8313       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8314         return Res;
8315
8316   
8317   // If this store is the last instruction in the basic block, and if the block
8318   // ends with an unconditional branch, try to move it to the successor block.
8319   BBI = &SI; ++BBI;
8320   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8321     if (BI->isUnconditional()) {
8322       // Check to see if the successor block has exactly two incoming edges.  If
8323       // so, see if the other predecessor contains a store to the same location.
8324       // if so, insert a PHI node (if needed) and move the stores down.
8325       BasicBlock *Dest = BI->getSuccessor(0);
8326
8327       pred_iterator PI = pred_begin(Dest);
8328       BasicBlock *Other = 0;
8329       if (*PI != BI->getParent())
8330         Other = *PI;
8331       ++PI;
8332       if (PI != pred_end(Dest)) {
8333         if (*PI != BI->getParent())
8334           if (Other)
8335             Other = 0;
8336           else
8337             Other = *PI;
8338         if (++PI != pred_end(Dest))
8339           Other = 0;
8340       }
8341       if (Other) {  // If only one other pred...
8342         BBI = Other->getTerminator();
8343         // Make sure this other block ends in an unconditional branch and that
8344         // there is an instruction before the branch.
8345         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8346             BBI != Other->begin()) {
8347           --BBI;
8348           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8349           
8350           // If this instruction is a store to the same location.
8351           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8352             // Okay, we know we can perform this transformation.  Insert a PHI
8353             // node now if we need it.
8354             Value *MergedVal = OtherStore->getOperand(0);
8355             if (MergedVal != SI.getOperand(0)) {
8356               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8357               PN->reserveOperandSpace(2);
8358               PN->addIncoming(SI.getOperand(0), SI.getParent());
8359               PN->addIncoming(OtherStore->getOperand(0), Other);
8360               MergedVal = InsertNewInstBefore(PN, Dest->front());
8361             }
8362             
8363             // Advance to a place where it is safe to insert the new store and
8364             // insert it.
8365             BBI = Dest->begin();
8366             while (isa<PHINode>(BBI)) ++BBI;
8367             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8368                                               OtherStore->isVolatile()), *BBI);
8369
8370             // Nuke the old stores.
8371             EraseInstFromFunction(SI);
8372             EraseInstFromFunction(*OtherStore);
8373             ++NumCombined;
8374             return 0;
8375           }
8376         }
8377       }
8378     }
8379   
8380   return 0;
8381 }
8382
8383
8384 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8385   // Change br (not X), label True, label False to: br X, label False, True
8386   Value *X = 0;
8387   BasicBlock *TrueDest;
8388   BasicBlock *FalseDest;
8389   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8390       !isa<Constant>(X)) {
8391     // Swap Destinations and condition...
8392     BI.setCondition(X);
8393     BI.setSuccessor(0, FalseDest);
8394     BI.setSuccessor(1, TrueDest);
8395     return &BI;
8396   }
8397
8398   // Cannonicalize fcmp_one -> fcmp_oeq
8399   FCmpInst::Predicate FPred; Value *Y;
8400   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
8401                              TrueDest, FalseDest)))
8402     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8403          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8404       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
8405       std::string Name = I->getName(); I->setName("");
8406       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8407       Value *NewSCC =  new FCmpInst(NewPred, X, Y, Name, I);
8408       // Swap Destinations and condition...
8409       BI.setCondition(NewSCC);
8410       BI.setSuccessor(0, FalseDest);
8411       BI.setSuccessor(1, TrueDest);
8412       removeFromWorkList(I);
8413       I->getParent()->getInstList().erase(I);
8414       WorkList.push_back(cast<Instruction>(NewSCC));
8415       return &BI;
8416     }
8417
8418   // Cannonicalize icmp_ne -> icmp_eq
8419   ICmpInst::Predicate IPred;
8420   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8421                       TrueDest, FalseDest)))
8422     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
8423          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8424          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8425       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8426       std::string Name = I->getName(); I->setName("");
8427       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8428       Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
8429       // Swap Destinations and condition...
8430       BI.setCondition(NewSCC);
8431       BI.setSuccessor(0, FalseDest);
8432       BI.setSuccessor(1, TrueDest);
8433       removeFromWorkList(I);
8434       I->getParent()->getInstList().erase(I);
8435       WorkList.push_back(cast<Instruction>(NewSCC));
8436       return &BI;
8437     }
8438
8439   return 0;
8440 }
8441
8442 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8443   Value *Cond = SI.getCondition();
8444   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8445     if (I->getOpcode() == Instruction::Add)
8446       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8447         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8448         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8449           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8450                                                 AddRHS));
8451         SI.setOperand(0, I->getOperand(0));
8452         WorkList.push_back(I);
8453         return &SI;
8454       }
8455   }
8456   return 0;
8457 }
8458
8459 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8460 /// is to leave as a vector operation.
8461 static bool CheapToScalarize(Value *V, bool isConstant) {
8462   if (isa<ConstantAggregateZero>(V)) 
8463     return true;
8464   if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8465     if (isConstant) return true;
8466     // If all elts are the same, we can extract.
8467     Constant *Op0 = C->getOperand(0);
8468     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8469       if (C->getOperand(i) != Op0)
8470         return false;
8471     return true;
8472   }
8473   Instruction *I = dyn_cast<Instruction>(V);
8474   if (!I) return false;
8475   
8476   // Insert element gets simplified to the inserted element or is deleted if
8477   // this is constant idx extract element and its a constant idx insertelt.
8478   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8479       isa<ConstantInt>(I->getOperand(2)))
8480     return true;
8481   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8482     return true;
8483   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8484     if (BO->hasOneUse() &&
8485         (CheapToScalarize(BO->getOperand(0), isConstant) ||
8486          CheapToScalarize(BO->getOperand(1), isConstant)))
8487       return true;
8488   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8489     if (CI->hasOneUse() &&
8490         (CheapToScalarize(CI->getOperand(0), isConstant) ||
8491          CheapToScalarize(CI->getOperand(1), isConstant)))
8492       return true;
8493   
8494   return false;
8495 }
8496
8497 /// getShuffleMask - Read and decode a shufflevector mask.  It turns undef
8498 /// elements into values that are larger than the #elts in the input.
8499 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8500   unsigned NElts = SVI->getType()->getNumElements();
8501   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8502     return std::vector<unsigned>(NElts, 0);
8503   if (isa<UndefValue>(SVI->getOperand(2)))
8504     return std::vector<unsigned>(NElts, 2*NElts);
8505
8506   std::vector<unsigned> Result;
8507   const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8508   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8509     if (isa<UndefValue>(CP->getOperand(i)))
8510       Result.push_back(NElts*2);  // undef -> 8
8511     else
8512       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8513   return Result;
8514 }
8515
8516 /// FindScalarElement - Given a vector and an element number, see if the scalar
8517 /// value is already around as a register, for example if it were inserted then
8518 /// extracted from the vector.
8519 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8520   assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8521   const PackedType *PTy = cast<PackedType>(V->getType());
8522   unsigned Width = PTy->getNumElements();
8523   if (EltNo >= Width)  // Out of range access.
8524     return UndefValue::get(PTy->getElementType());
8525   
8526   if (isa<UndefValue>(V))
8527     return UndefValue::get(PTy->getElementType());
8528   else if (isa<ConstantAggregateZero>(V))
8529     return Constant::getNullValue(PTy->getElementType());
8530   else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8531     return CP->getOperand(EltNo);
8532   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8533     // If this is an insert to a variable element, we don't know what it is.
8534     if (!isa<ConstantInt>(III->getOperand(2))) 
8535       return 0;
8536     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8537     
8538     // If this is an insert to the element we are looking for, return the
8539     // inserted value.
8540     if (EltNo == IIElt) 
8541       return III->getOperand(1);
8542     
8543     // Otherwise, the insertelement doesn't modify the value, recurse on its
8544     // vector input.
8545     return FindScalarElement(III->getOperand(0), EltNo);
8546   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8547     unsigned InEl = getShuffleMask(SVI)[EltNo];
8548     if (InEl < Width)
8549       return FindScalarElement(SVI->getOperand(0), InEl);
8550     else if (InEl < Width*2)
8551       return FindScalarElement(SVI->getOperand(1), InEl - Width);
8552     else
8553       return UndefValue::get(PTy->getElementType());
8554   }
8555   
8556   // Otherwise, we don't know.
8557   return 0;
8558 }
8559
8560 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8561
8562   // If packed val is undef, replace extract with scalar undef.
8563   if (isa<UndefValue>(EI.getOperand(0)))
8564     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8565
8566   // If packed val is constant 0, replace extract with scalar 0.
8567   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8568     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8569   
8570   if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8571     // If packed val is constant with uniform operands, replace EI
8572     // with that operand
8573     Constant *op0 = C->getOperand(0);
8574     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8575       if (C->getOperand(i) != op0) {
8576         op0 = 0; 
8577         break;
8578       }
8579     if (op0)
8580       return ReplaceInstUsesWith(EI, op0);
8581   }
8582   
8583   // If extracting a specified index from the vector, see if we can recursively
8584   // find a previously computed scalar that was inserted into the vector.
8585   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8586     // This instruction only demands the single element from the input vector.
8587     // If the input vector has a single use, simplify it based on this use
8588     // property.
8589     uint64_t IndexVal = IdxC->getZExtValue();
8590     if (EI.getOperand(0)->hasOneUse()) {
8591       uint64_t UndefElts;
8592       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8593                                                 1 << IndexVal,
8594                                                 UndefElts)) {
8595         EI.setOperand(0, V);
8596         return &EI;
8597       }
8598     }
8599     
8600     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8601       return ReplaceInstUsesWith(EI, Elt);
8602   }
8603   
8604   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8605     if (I->hasOneUse()) {
8606       // Push extractelement into predecessor operation if legal and
8607       // profitable to do so
8608       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8609         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8610         if (CheapToScalarize(BO, isConstantElt)) {
8611           ExtractElementInst *newEI0 = 
8612             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8613                                    EI.getName()+".lhs");
8614           ExtractElementInst *newEI1 =
8615             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8616                                    EI.getName()+".rhs");
8617           InsertNewInstBefore(newEI0, EI);
8618           InsertNewInstBefore(newEI1, EI);
8619           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8620         }
8621       } else if (isa<LoadInst>(I)) {
8622         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
8623                                       PointerType::get(EI.getType()), EI);
8624         GetElementPtrInst *GEP = 
8625           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8626         InsertNewInstBefore(GEP, EI);
8627         return new LoadInst(GEP);
8628       }
8629     }
8630     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8631       // Extracting the inserted element?
8632       if (IE->getOperand(2) == EI.getOperand(1))
8633         return ReplaceInstUsesWith(EI, IE->getOperand(1));
8634       // If the inserted and extracted elements are constants, they must not
8635       // be the same value, extract from the pre-inserted value instead.
8636       if (isa<Constant>(IE->getOperand(2)) &&
8637           isa<Constant>(EI.getOperand(1))) {
8638         AddUsesToWorkList(EI);
8639         EI.setOperand(0, IE->getOperand(0));
8640         return &EI;
8641       }
8642     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8643       // If this is extracting an element from a shufflevector, figure out where
8644       // it came from and extract from the appropriate input element instead.
8645       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8646         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8647         Value *Src;
8648         if (SrcIdx < SVI->getType()->getNumElements())
8649           Src = SVI->getOperand(0);
8650         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8651           SrcIdx -= SVI->getType()->getNumElements();
8652           Src = SVI->getOperand(1);
8653         } else {
8654           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8655         }
8656         return new ExtractElementInst(Src, SrcIdx);
8657       }
8658     }
8659   }
8660   return 0;
8661 }
8662
8663 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8664 /// elements from either LHS or RHS, return the shuffle mask and true. 
8665 /// Otherwise, return false.
8666 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8667                                          std::vector<Constant*> &Mask) {
8668   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8669          "Invalid CollectSingleShuffleElements");
8670   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8671
8672   if (isa<UndefValue>(V)) {
8673     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8674     return true;
8675   } else if (V == LHS) {
8676     for (unsigned i = 0; i != NumElts; ++i)
8677       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8678     return true;
8679   } else if (V == RHS) {
8680     for (unsigned i = 0; i != NumElts; ++i)
8681       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
8682     return true;
8683   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8684     // If this is an insert of an extract from some other vector, include it.
8685     Value *VecOp    = IEI->getOperand(0);
8686     Value *ScalarOp = IEI->getOperand(1);
8687     Value *IdxOp    = IEI->getOperand(2);
8688     
8689     if (!isa<ConstantInt>(IdxOp))
8690       return false;
8691     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8692     
8693     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
8694       // Okay, we can handle this if the vector we are insertinting into is
8695       // transitively ok.
8696       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8697         // If so, update the mask to reflect the inserted undef.
8698         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
8699         return true;
8700       }      
8701     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8702       if (isa<ConstantInt>(EI->getOperand(1)) &&
8703           EI->getOperand(0)->getType() == V->getType()) {
8704         unsigned ExtractedIdx =
8705           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8706         
8707         // This must be extracting from either LHS or RHS.
8708         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8709           // Okay, we can handle this if the vector we are insertinting into is
8710           // transitively ok.
8711           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8712             // If so, update the mask to reflect the inserted value.
8713             if (EI->getOperand(0) == LHS) {
8714               Mask[InsertedIdx & (NumElts-1)] = 
8715                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8716             } else {
8717               assert(EI->getOperand(0) == RHS);
8718               Mask[InsertedIdx & (NumElts-1)] = 
8719                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
8720               
8721             }
8722             return true;
8723           }
8724         }
8725       }
8726     }
8727   }
8728   // TODO: Handle shufflevector here!
8729   
8730   return false;
8731 }
8732
8733 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8734 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
8735 /// that computes V and the LHS value of the shuffle.
8736 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8737                                      Value *&RHS) {
8738   assert(isa<PackedType>(V->getType()) && 
8739          (RHS == 0 || V->getType() == RHS->getType()) &&
8740          "Invalid shuffle!");
8741   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8742
8743   if (isa<UndefValue>(V)) {
8744     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8745     return V;
8746   } else if (isa<ConstantAggregateZero>(V)) {
8747     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
8748     return V;
8749   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8750     // If this is an insert of an extract from some other vector, include it.
8751     Value *VecOp    = IEI->getOperand(0);
8752     Value *ScalarOp = IEI->getOperand(1);
8753     Value *IdxOp    = IEI->getOperand(2);
8754     
8755     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8756       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8757           EI->getOperand(0)->getType() == V->getType()) {
8758         unsigned ExtractedIdx =
8759           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8760         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8761         
8762         // Either the extracted from or inserted into vector must be RHSVec,
8763         // otherwise we'd end up with a shuffle of three inputs.
8764         if (EI->getOperand(0) == RHS || RHS == 0) {
8765           RHS = EI->getOperand(0);
8766           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8767           Mask[InsertedIdx & (NumElts-1)] = 
8768             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
8769           return V;
8770         }
8771         
8772         if (VecOp == RHS) {
8773           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8774           // Everything but the extracted element is replaced with the RHS.
8775           for (unsigned i = 0; i != NumElts; ++i) {
8776             if (i != InsertedIdx)
8777               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
8778           }
8779           return V;
8780         }
8781         
8782         // If this insertelement is a chain that comes from exactly these two
8783         // vectors, return the vector and the effective shuffle.
8784         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8785           return EI->getOperand(0);
8786         
8787       }
8788     }
8789   }
8790   // TODO: Handle shufflevector here!
8791   
8792   // Otherwise, can't do anything fancy.  Return an identity vector.
8793   for (unsigned i = 0; i != NumElts; ++i)
8794     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8795   return V;
8796 }
8797
8798 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8799   Value *VecOp    = IE.getOperand(0);
8800   Value *ScalarOp = IE.getOperand(1);
8801   Value *IdxOp    = IE.getOperand(2);
8802   
8803   // If the inserted element was extracted from some other vector, and if the 
8804   // indexes are constant, try to turn this into a shufflevector operation.
8805   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8806     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8807         EI->getOperand(0)->getType() == IE.getType()) {
8808       unsigned NumVectorElts = IE.getType()->getNumElements();
8809       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8810       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8811       
8812       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8813         return ReplaceInstUsesWith(IE, VecOp);
8814       
8815       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
8816         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8817       
8818       // If we are extracting a value from a vector, then inserting it right
8819       // back into the same place, just use the input vector.
8820       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8821         return ReplaceInstUsesWith(IE, VecOp);      
8822       
8823       // We could theoretically do this for ANY input.  However, doing so could
8824       // turn chains of insertelement instructions into a chain of shufflevector
8825       // instructions, and right now we do not merge shufflevectors.  As such,
8826       // only do this in a situation where it is clear that there is benefit.
8827       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8828         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
8829         // the values of VecOp, except then one read from EIOp0.
8830         // Build a new shuffle mask.
8831         std::vector<Constant*> Mask;
8832         if (isa<UndefValue>(VecOp))
8833           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
8834         else {
8835           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8836           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
8837                                                        NumVectorElts));
8838         } 
8839         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8840         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8841                                      ConstantPacked::get(Mask));
8842       }
8843       
8844       // If this insertelement isn't used by some other insertelement, turn it
8845       // (and any insertelements it points to), into one big shuffle.
8846       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8847         std::vector<Constant*> Mask;
8848         Value *RHS = 0;
8849         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8850         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8851         // We now have a shuffle of LHS, RHS, Mask.
8852         return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8853       }
8854     }
8855   }
8856
8857   return 0;
8858 }
8859
8860
8861 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8862   Value *LHS = SVI.getOperand(0);
8863   Value *RHS = SVI.getOperand(1);
8864   std::vector<unsigned> Mask = getShuffleMask(&SVI);
8865
8866   bool MadeChange = false;
8867   
8868   // Undefined shuffle mask -> undefined value.
8869   if (isa<UndefValue>(SVI.getOperand(2)))
8870     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8871   
8872   // If we have shuffle(x, undef, mask) and any elements of mask refer to
8873   // the undef, change them to undefs.
8874   if (isa<UndefValue>(SVI.getOperand(1))) {
8875     // Scan to see if there are any references to the RHS.  If so, replace them
8876     // with undef element refs and set MadeChange to true.
8877     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8878       if (Mask[i] >= e && Mask[i] != 2*e) {
8879         Mask[i] = 2*e;
8880         MadeChange = true;
8881       }
8882     }
8883     
8884     if (MadeChange) {
8885       // Remap any references to RHS to use LHS.
8886       std::vector<Constant*> Elts;
8887       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8888         if (Mask[i] == 2*e)
8889           Elts.push_back(UndefValue::get(Type::Int32Ty));
8890         else
8891           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8892       }
8893       SVI.setOperand(2, ConstantPacked::get(Elts));
8894     }
8895   }
8896   
8897   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
8898   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8899   if (LHS == RHS || isa<UndefValue>(LHS)) {
8900     if (isa<UndefValue>(LHS) && LHS == RHS) {
8901       // shuffle(undef,undef,mask) -> undef.
8902       return ReplaceInstUsesWith(SVI, LHS);
8903     }
8904     
8905     // Remap any references to RHS to use LHS.
8906     std::vector<Constant*> Elts;
8907     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8908       if (Mask[i] >= 2*e)
8909         Elts.push_back(UndefValue::get(Type::Int32Ty));
8910       else {
8911         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8912             (Mask[i] <  e && isa<UndefValue>(LHS)))
8913           Mask[i] = 2*e;     // Turn into undef.
8914         else
8915           Mask[i] &= (e-1);  // Force to LHS.
8916         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8917       }
8918     }
8919     SVI.setOperand(0, SVI.getOperand(1));
8920     SVI.setOperand(1, UndefValue::get(RHS->getType()));
8921     SVI.setOperand(2, ConstantPacked::get(Elts));
8922     LHS = SVI.getOperand(0);
8923     RHS = SVI.getOperand(1);
8924     MadeChange = true;
8925   }
8926   
8927   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8928   bool isLHSID = true, isRHSID = true;
8929     
8930   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8931     if (Mask[i] >= e*2) continue;  // Ignore undef values.
8932     // Is this an identity shuffle of the LHS value?
8933     isLHSID &= (Mask[i] == i);
8934       
8935     // Is this an identity shuffle of the RHS value?
8936     isRHSID &= (Mask[i]-e == i);
8937   }
8938
8939   // Eliminate identity shuffles.
8940   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8941   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8942   
8943   // If the LHS is a shufflevector itself, see if we can combine it with this
8944   // one without producing an unusual shuffle.  Here we are really conservative:
8945   // we are absolutely afraid of producing a shuffle mask not in the input
8946   // program, because the code gen may not be smart enough to turn a merged
8947   // shuffle into two specific shuffles: it may produce worse code.  As such,
8948   // we only merge two shuffles if the result is one of the two input shuffle
8949   // masks.  In this case, merging the shuffles just removes one instruction,
8950   // which we know is safe.  This is good for things like turning:
8951   // (splat(splat)) -> splat.
8952   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8953     if (isa<UndefValue>(RHS)) {
8954       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8955
8956       std::vector<unsigned> NewMask;
8957       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8958         if (Mask[i] >= 2*e)
8959           NewMask.push_back(2*e);
8960         else
8961           NewMask.push_back(LHSMask[Mask[i]]);
8962       
8963       // If the result mask is equal to the src shuffle or this shuffle mask, do
8964       // the replacement.
8965       if (NewMask == LHSMask || NewMask == Mask) {
8966         std::vector<Constant*> Elts;
8967         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8968           if (NewMask[i] >= e*2) {
8969             Elts.push_back(UndefValue::get(Type::Int32Ty));
8970           } else {
8971             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
8972           }
8973         }
8974         return new ShuffleVectorInst(LHSSVI->getOperand(0),
8975                                      LHSSVI->getOperand(1),
8976                                      ConstantPacked::get(Elts));
8977       }
8978     }
8979   }
8980   
8981   return MadeChange ? &SVI : 0;
8982 }
8983
8984
8985
8986 void InstCombiner::removeFromWorkList(Instruction *I) {
8987   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8988                  WorkList.end());
8989 }
8990
8991
8992 /// TryToSinkInstruction - Try to move the specified instruction from its
8993 /// current block into the beginning of DestBlock, which can only happen if it's
8994 /// safe to move the instruction past all of the instructions between it and the
8995 /// end of its block.
8996 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8997   assert(I->hasOneUse() && "Invariants didn't hold!");
8998
8999   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9000   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
9001
9002   // Do not sink alloca instructions out of the entry block.
9003   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9004     return false;
9005
9006   // We can only sink load instructions if there is nothing between the load and
9007   // the end of block that could change the value.
9008   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9009     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9010          Scan != E; ++Scan)
9011       if (Scan->mayWriteToMemory())
9012         return false;
9013   }
9014
9015   BasicBlock::iterator InsertPos = DestBlock->begin();
9016   while (isa<PHINode>(InsertPos)) ++InsertPos;
9017
9018   I->moveBefore(InsertPos);
9019   ++NumSunkInst;
9020   return true;
9021 }
9022
9023 /// OptimizeConstantExpr - Given a constant expression and target data layout
9024 /// information, symbolically evaluate the constant expr to something simpler
9025 /// if possible.
9026 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
9027   if (!TD) return CE;
9028   
9029   Constant *Ptr = CE->getOperand(0);
9030   if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
9031       cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
9032     // If this is a constant expr gep that is effectively computing an
9033     // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
9034     bool isFoldableGEP = true;
9035     for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
9036       if (!isa<ConstantInt>(CE->getOperand(i)))
9037         isFoldableGEP = false;
9038     if (isFoldableGEP) {
9039       std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
9040       uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
9041       Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
9042       return ConstantExpr::getIntToPtr(C, CE->getType());
9043     }
9044   }
9045   
9046   return CE;
9047 }
9048
9049
9050 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9051 /// all reachable code to the worklist.
9052 ///
9053 /// This has a couple of tricks to make the code faster and more powerful.  In
9054 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9055 /// them to the worklist (this significantly speeds up instcombine on code where
9056 /// many instructions are dead or constant).  Additionally, if we find a branch
9057 /// whose condition is a known constant, we only visit the reachable successors.
9058 ///
9059 static void AddReachableCodeToWorklist(BasicBlock *BB, 
9060                                        std::set<BasicBlock*> &Visited,
9061                                        std::vector<Instruction*> &WorkList,
9062                                        const TargetData *TD) {
9063   // We have now visited this block!  If we've already been here, bail out.
9064   if (!Visited.insert(BB).second) return;
9065     
9066   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9067     Instruction *Inst = BBI++;
9068     
9069     // DCE instruction if trivially dead.
9070     if (isInstructionTriviallyDead(Inst)) {
9071       ++NumDeadInst;
9072       DOUT << "IC: DCE: " << *Inst;
9073       Inst->eraseFromParent();
9074       continue;
9075     }
9076     
9077     // ConstantProp instruction if trivially constant.
9078     if (Constant *C = ConstantFoldInstruction(Inst)) {
9079       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9080         C = OptimizeConstantExpr(CE, TD);
9081       DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9082       Inst->replaceAllUsesWith(C);
9083       ++NumConstProp;
9084       Inst->eraseFromParent();
9085       continue;
9086     }
9087     
9088     WorkList.push_back(Inst);
9089   }
9090
9091   // Recursively visit successors.  If this is a branch or switch on a constant,
9092   // only visit the reachable successor.
9093   TerminatorInst *TI = BB->getTerminator();
9094   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9095     if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9096       bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9097       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9098                                  TD);
9099       return;
9100     }
9101   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9102     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9103       // See if this is an explicit destination.
9104       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9105         if (SI->getCaseValue(i) == Cond) {
9106           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
9107           return;
9108         }
9109       
9110       // Otherwise it is the default destination.
9111       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
9112       return;
9113     }
9114   }
9115   
9116   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9117     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
9118 }
9119
9120 bool InstCombiner::runOnFunction(Function &F) {
9121   bool Changed = false;
9122   TD = &getAnalysis<TargetData>();
9123
9124   {
9125     // Do a depth-first traversal of the function, populate the worklist with
9126     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
9127     // track of which blocks we visit.
9128     std::set<BasicBlock*> Visited;
9129     AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
9130
9131     // Do a quick scan over the function.  If we find any blocks that are
9132     // unreachable, remove any instructions inside of them.  This prevents
9133     // the instcombine code from having to deal with some bad special cases.
9134     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9135       if (!Visited.count(BB)) {
9136         Instruction *Term = BB->getTerminator();
9137         while (Term != BB->begin()) {   // Remove instrs bottom-up
9138           BasicBlock::iterator I = Term; --I;
9139
9140           DOUT << "IC: DCE: " << *I;
9141           ++NumDeadInst;
9142
9143           if (!I->use_empty())
9144             I->replaceAllUsesWith(UndefValue::get(I->getType()));
9145           I->eraseFromParent();
9146         }
9147       }
9148   }
9149
9150   while (!WorkList.empty()) {
9151     Instruction *I = WorkList.back();  // Get an instruction from the worklist
9152     WorkList.pop_back();
9153
9154     // Check to see if we can DCE the instruction.
9155     if (isInstructionTriviallyDead(I)) {
9156       // Add operands to the worklist.
9157       if (I->getNumOperands() < 4)
9158         AddUsesToWorkList(*I);
9159       ++NumDeadInst;
9160
9161       DOUT << "IC: DCE: " << *I;
9162
9163       I->eraseFromParent();
9164       removeFromWorkList(I);
9165       continue;
9166     }
9167
9168     // Instruction isn't dead, see if we can constant propagate it.
9169     if (Constant *C = ConstantFoldInstruction(I)) {
9170       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9171         C = OptimizeConstantExpr(CE, TD);
9172       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9173
9174       // Add operands to the worklist.
9175       AddUsesToWorkList(*I);
9176       ReplaceInstUsesWith(*I, C);
9177
9178       ++NumConstProp;
9179       I->eraseFromParent();
9180       removeFromWorkList(I);
9181       continue;
9182     }
9183
9184     // See if we can trivially sink this instruction to a successor basic block.
9185     if (I->hasOneUse()) {
9186       BasicBlock *BB = I->getParent();
9187       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9188       if (UserParent != BB) {
9189         bool UserIsSuccessor = false;
9190         // See if the user is one of our successors.
9191         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9192           if (*SI == UserParent) {
9193             UserIsSuccessor = true;
9194             break;
9195           }
9196
9197         // If the user is one of our immediate successors, and if that successor
9198         // only has us as a predecessors (we'd have to split the critical edge
9199         // otherwise), we can keep going.
9200         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9201             next(pred_begin(UserParent)) == pred_end(UserParent))
9202           // Okay, the CFG is simple enough, try to sink this instruction.
9203           Changed |= TryToSinkInstruction(I, UserParent);
9204       }
9205     }
9206
9207     // Now that we have an instruction, try combining it to simplify it...
9208     if (Instruction *Result = visit(*I)) {
9209       ++NumCombined;
9210       // Should we replace the old instruction with a new one?
9211       if (Result != I) {
9212         DOUT << "IC: Old = " << *I
9213              << "    New = " << *Result;
9214
9215         // Everything uses the new instruction now.
9216         I->replaceAllUsesWith(Result);
9217
9218         // Push the new instruction and any users onto the worklist.
9219         WorkList.push_back(Result);
9220         AddUsersToWorkList(*Result);
9221
9222         // Move the name to the new instruction first...
9223         std::string OldName = I->getName(); I->setName("");
9224         Result->setName(OldName);
9225
9226         // Insert the new instruction into the basic block...
9227         BasicBlock *InstParent = I->getParent();
9228         BasicBlock::iterator InsertPos = I;
9229
9230         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
9231           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9232             ++InsertPos;
9233
9234         InstParent->getInstList().insert(InsertPos, Result);
9235
9236         // Make sure that we reprocess all operands now that we reduced their
9237         // use counts.
9238         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9239           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9240             WorkList.push_back(OpI);
9241
9242         // Instructions can end up on the worklist more than once.  Make sure
9243         // we do not process an instruction that has been deleted.
9244         removeFromWorkList(I);
9245
9246         // Erase the old instruction.
9247         InstParent->getInstList().erase(I);
9248       } else {
9249         DOUT << "IC: MOD = " << *I;
9250
9251         // If the instruction was modified, it's possible that it is now dead.
9252         // if so, remove it.
9253         if (isInstructionTriviallyDead(I)) {
9254           // Make sure we process all operands now that we are reducing their
9255           // use counts.
9256           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9257             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9258               WorkList.push_back(OpI);
9259
9260           // Instructions may end up in the worklist more than once.  Erase all
9261           // occurrences of this instruction.
9262           removeFromWorkList(I);
9263           I->eraseFromParent();
9264         } else {
9265           WorkList.push_back(Result);
9266           AddUsersToWorkList(*Result);
9267         }
9268       }
9269       Changed = true;
9270     }
9271   }
9272
9273   return Changed;
9274 }
9275
9276 FunctionPass *llvm::createInstructionCombiningPass() {
9277   return new InstCombiner();
9278 }
9279