aecc9a93ef1aa6ad401899dd3bb6c6caf93dc8a5
[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()->getIntegralTypeMask();
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->isIntegral()) {
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->getIntegralTypeMask();
637     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
638       
639     Mask &= SrcTy->getIntegralTypeMask();
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->getIntegralTypeMask();
650     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
651       
652     Mask &= SrcTy->getIntegralTypeMask();
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->getIntegralTypeMask();
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->getIntegralTypeMask();
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()->getIntegralTypeMask();
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()->getIntegralTypeMask();
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()->isIntegral())
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->getIntegralTypeMask();
1016     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1017     
1018     DemandedMask &= SrcTy->getIntegralTypeMask();
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->getIntegralTypeMask();
1031     uint64_t NewBits = I->getType()->getIntegralTypeMask() & 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->getIntegralTypeMask();
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()->getIntegralTypeMask();
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()->getIntegralTypeMask();
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 /// @returns true if the specified compare instruction is
1461 /// true when both operands are equal...
1462 /// @brief Determine if the FCmpInst returns true if both operands are equal
1463 static bool isTrueWhenEqual(FCmpInst &FCI) {
1464   FCmpInst::Predicate pred = FCI.getPredicate();
1465   return pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ ||
1466          pred == FCmpInst::FCMP_OGE || pred == FCmpInst::FCMP_UGE ||
1467          pred == FCmpInst::FCMP_OLE || pred == FCmpInst::FCMP_ULE;
1468 }
1469
1470 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1471 /// function is designed to check a chain of associative operators for a
1472 /// potential to apply a certain optimization.  Since the optimization may be
1473 /// applicable if the expression was reassociated, this checks the chain, then
1474 /// reassociates the expression as necessary to expose the optimization
1475 /// opportunity.  This makes use of a special Functor, which must define
1476 /// 'shouldApply' and 'apply' methods.
1477 ///
1478 template<typename Functor>
1479 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1480   unsigned Opcode = Root.getOpcode();
1481   Value *LHS = Root.getOperand(0);
1482
1483   // Quick check, see if the immediate LHS matches...
1484   if (F.shouldApply(LHS))
1485     return F.apply(Root);
1486
1487   // Otherwise, if the LHS is not of the same opcode as the root, return.
1488   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1489   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1490     // Should we apply this transform to the RHS?
1491     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1492
1493     // If not to the RHS, check to see if we should apply to the LHS...
1494     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1495       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1496       ShouldApply = true;
1497     }
1498
1499     // If the functor wants to apply the optimization to the RHS of LHSI,
1500     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1501     if (ShouldApply) {
1502       BasicBlock *BB = Root.getParent();
1503
1504       // Now all of the instructions are in the current basic block, go ahead
1505       // and perform the reassociation.
1506       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1507
1508       // First move the selected RHS to the LHS of the root...
1509       Root.setOperand(0, LHSI->getOperand(1));
1510
1511       // Make what used to be the LHS of the root be the user of the root...
1512       Value *ExtraOperand = TmpLHSI->getOperand(1);
1513       if (&Root == TmpLHSI) {
1514         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1515         return 0;
1516       }
1517       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1518       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1519       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1520       BasicBlock::iterator ARI = &Root; ++ARI;
1521       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1522       ARI = Root;
1523
1524       // Now propagate the ExtraOperand down the chain of instructions until we
1525       // get to LHSI.
1526       while (TmpLHSI != LHSI) {
1527         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1528         // Move the instruction to immediately before the chain we are
1529         // constructing to avoid breaking dominance properties.
1530         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1531         BB->getInstList().insert(ARI, NextLHSI);
1532         ARI = NextLHSI;
1533
1534         Value *NextOp = NextLHSI->getOperand(1);
1535         NextLHSI->setOperand(1, ExtraOperand);
1536         TmpLHSI = NextLHSI;
1537         ExtraOperand = NextOp;
1538       }
1539
1540       // Now that the instructions are reassociated, have the functor perform
1541       // the transformation...
1542       return F.apply(Root);
1543     }
1544
1545     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1546   }
1547   return 0;
1548 }
1549
1550
1551 // AddRHS - Implements: X + X --> X << 1
1552 struct AddRHS {
1553   Value *RHS;
1554   AddRHS(Value *rhs) : RHS(rhs) {}
1555   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1556   Instruction *apply(BinaryOperator &Add) const {
1557     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1558                          ConstantInt::get(Type::Int8Ty, 1));
1559   }
1560 };
1561
1562 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1563 //                 iff C1&C2 == 0
1564 struct AddMaskingAnd {
1565   Constant *C2;
1566   AddMaskingAnd(Constant *c) : C2(c) {}
1567   bool shouldApply(Value *LHS) const {
1568     ConstantInt *C1;
1569     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1570            ConstantExpr::getAnd(C1, C2)->isNullValue();
1571   }
1572   Instruction *apply(BinaryOperator &Add) const {
1573     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1574   }
1575 };
1576
1577 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1578                                              InstCombiner *IC) {
1579   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1580     if (Constant *SOC = dyn_cast<Constant>(SO))
1581       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1582
1583     return IC->InsertNewInstBefore(CastInst::create(
1584           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1585   }
1586
1587   // Figure out if the constant is the left or the right argument.
1588   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1589   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1590
1591   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1592     if (ConstIsRHS)
1593       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1594     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1595   }
1596
1597   Value *Op0 = SO, *Op1 = ConstOperand;
1598   if (!ConstIsRHS)
1599     std::swap(Op0, Op1);
1600   Instruction *New;
1601   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1602     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1603   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1604     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1605                           SO->getName()+".cmp");
1606   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1607     New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1608   else {
1609     assert(0 && "Unknown binary instruction type!");
1610     abort();
1611   }
1612   return IC->InsertNewInstBefore(New, I);
1613 }
1614
1615 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1616 // constant as the other operand, try to fold the binary operator into the
1617 // select arguments.  This also works for Cast instructions, which obviously do
1618 // not have a second operand.
1619 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1620                                      InstCombiner *IC) {
1621   // Don't modify shared select instructions
1622   if (!SI->hasOneUse()) return 0;
1623   Value *TV = SI->getOperand(1);
1624   Value *FV = SI->getOperand(2);
1625
1626   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1627     // Bool selects with constant operands can be folded to logical ops.
1628     if (SI->getType() == Type::Int1Ty) return 0;
1629
1630     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1631     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1632
1633     return new SelectInst(SI->getCondition(), SelectTrueVal,
1634                           SelectFalseVal);
1635   }
1636   return 0;
1637 }
1638
1639
1640 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1641 /// node as operand #0, see if we can fold the instruction into the PHI (which
1642 /// is only possible if all operands to the PHI are constants).
1643 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1644   PHINode *PN = cast<PHINode>(I.getOperand(0));
1645   unsigned NumPHIValues = PN->getNumIncomingValues();
1646   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1647
1648   // Check to see if all of the operands of the PHI are constants.  If there is
1649   // one non-constant value, remember the BB it is.  If there is more than one
1650   // bail out.
1651   BasicBlock *NonConstBB = 0;
1652   for (unsigned i = 0; i != NumPHIValues; ++i)
1653     if (!isa<Constant>(PN->getIncomingValue(i))) {
1654       if (NonConstBB) return 0;  // More than one non-const value.
1655       NonConstBB = PN->getIncomingBlock(i);
1656       
1657       // If the incoming non-constant value is in I's block, we have an infinite
1658       // loop.
1659       if (NonConstBB == I.getParent())
1660         return 0;
1661     }
1662   
1663   // If there is exactly one non-constant value, we can insert a copy of the
1664   // operation in that block.  However, if this is a critical edge, we would be
1665   // inserting the computation one some other paths (e.g. inside a loop).  Only
1666   // do this if the pred block is unconditionally branching into the phi block.
1667   if (NonConstBB) {
1668     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1669     if (!BI || !BI->isUnconditional()) return 0;
1670   }
1671
1672   // Okay, we can do the transformation: create the new PHI node.
1673   PHINode *NewPN = new PHINode(I.getType(), I.getName());
1674   I.setName("");
1675   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1676   InsertNewInstBefore(NewPN, *PN);
1677
1678   // Next, add all of the operands to the PHI.
1679   if (I.getNumOperands() == 2) {
1680     Constant *C = cast<Constant>(I.getOperand(1));
1681     for (unsigned i = 0; i != NumPHIValues; ++i) {
1682       Value *InV;
1683       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1684         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1685           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1686         else
1687           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1688       } else {
1689         assert(PN->getIncomingBlock(i) == NonConstBB);
1690         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1691           InV = BinaryOperator::create(BO->getOpcode(),
1692                                        PN->getIncomingValue(i), C, "phitmp",
1693                                        NonConstBB->getTerminator());
1694         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1695           InV = CmpInst::create(CI->getOpcode(), 
1696                                 CI->getPredicate(),
1697                                 PN->getIncomingValue(i), C, "phitmp",
1698                                 NonConstBB->getTerminator());
1699         else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1700           InV = new ShiftInst(SI->getOpcode(),
1701                               PN->getIncomingValue(i), C, "phitmp",
1702                               NonConstBB->getTerminator());
1703         else
1704           assert(0 && "Unknown binop!");
1705         
1706         WorkList.push_back(cast<Instruction>(InV));
1707       }
1708       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1709     }
1710   } else { 
1711     CastInst *CI = cast<CastInst>(&I);
1712     const Type *RetTy = CI->getType();
1713     for (unsigned i = 0; i != NumPHIValues; ++i) {
1714       Value *InV;
1715       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1716         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1717       } else {
1718         assert(PN->getIncomingBlock(i) == NonConstBB);
1719         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1720                                I.getType(), "phitmp", 
1721                                NonConstBB->getTerminator());
1722         WorkList.push_back(cast<Instruction>(InV));
1723       }
1724       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1725     }
1726   }
1727   return ReplaceInstUsesWith(I, NewPN);
1728 }
1729
1730 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1731   bool Changed = SimplifyCommutative(I);
1732   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1733
1734   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1735     // X + undef -> undef
1736     if (isa<UndefValue>(RHS))
1737       return ReplaceInstUsesWith(I, RHS);
1738
1739     // X + 0 --> X
1740     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1741       if (RHSC->isNullValue())
1742         return ReplaceInstUsesWith(I, LHS);
1743     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1744       if (CFP->isExactlyValue(-0.0))
1745         return ReplaceInstUsesWith(I, LHS);
1746     }
1747
1748     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1749       // X + (signbit) --> X ^ signbit
1750       uint64_t Val = CI->getZExtValue();
1751       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1752         return BinaryOperator::createXor(LHS, RHS);
1753       
1754       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1755       // (X & 254)+1 -> (X&254)|1
1756       uint64_t KnownZero, KnownOne;
1757       if (!isa<PackedType>(I.getType()) &&
1758           SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1759                                KnownZero, KnownOne))
1760         return &I;
1761     }
1762
1763     if (isa<PHINode>(LHS))
1764       if (Instruction *NV = FoldOpIntoPhi(I))
1765         return NV;
1766     
1767     ConstantInt *XorRHS = 0;
1768     Value *XorLHS = 0;
1769     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1770       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1771       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1772       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1773       
1774       uint64_t C0080Val = 1ULL << 31;
1775       int64_t CFF80Val = -C0080Val;
1776       unsigned Size = 32;
1777       do {
1778         if (TySizeBits > Size) {
1779           bool Found = false;
1780           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1781           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1782           if (RHSSExt == CFF80Val) {
1783             if (XorRHS->getZExtValue() == C0080Val)
1784               Found = true;
1785           } else if (RHSZExt == C0080Val) {
1786             if (XorRHS->getSExtValue() == CFF80Val)
1787               Found = true;
1788           }
1789           if (Found) {
1790             // This is a sign extend if the top bits are known zero.
1791             uint64_t Mask = ~0ULL;
1792             Mask <<= 64-(TySizeBits-Size);
1793             Mask &= XorLHS->getType()->getIntegralTypeMask();
1794             if (!MaskedValueIsZero(XorLHS, Mask))
1795               Size = 0;  // Not a sign ext, but can't be any others either.
1796             goto FoundSExt;
1797           }
1798         }
1799         Size >>= 1;
1800         C0080Val >>= Size;
1801         CFF80Val >>= Size;
1802       } while (Size >= 8);
1803       
1804 FoundSExt:
1805       const Type *MiddleType = 0;
1806       switch (Size) {
1807       default: break;
1808       case 32: MiddleType = Type::Int32Ty; break;
1809       case 16: MiddleType = Type::Int16Ty; break;
1810       case 8:  MiddleType = Type::Int8Ty; break;
1811       }
1812       if (MiddleType) {
1813         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1814         InsertNewInstBefore(NewTrunc, I);
1815         return new SExtInst(NewTrunc, I.getType());
1816       }
1817     }
1818   }
1819
1820   // X + X --> X << 1
1821   if (I.getType()->isInteger()) {
1822     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1823
1824     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1825       if (RHSI->getOpcode() == Instruction::Sub)
1826         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1827           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1828     }
1829     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1830       if (LHSI->getOpcode() == Instruction::Sub)
1831         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1832           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1833     }
1834   }
1835
1836   // -A + B  -->  B - A
1837   if (Value *V = dyn_castNegVal(LHS))
1838     return BinaryOperator::createSub(RHS, V);
1839
1840   // A + -B  -->  A - B
1841   if (!isa<Constant>(RHS))
1842     if (Value *V = dyn_castNegVal(RHS))
1843       return BinaryOperator::createSub(LHS, V);
1844
1845
1846   ConstantInt *C2;
1847   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1848     if (X == RHS)   // X*C + X --> X * (C+1)
1849       return BinaryOperator::createMul(RHS, AddOne(C2));
1850
1851     // X*C1 + X*C2 --> X * (C1+C2)
1852     ConstantInt *C1;
1853     if (X == dyn_castFoldableMul(RHS, C1))
1854       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1855   }
1856
1857   // X + X*C --> X * (C+1)
1858   if (dyn_castFoldableMul(RHS, C2) == LHS)
1859     return BinaryOperator::createMul(LHS, AddOne(C2));
1860
1861   // X + ~X --> -1   since   ~X = -X-1
1862   if (dyn_castNotVal(LHS) == RHS ||
1863       dyn_castNotVal(RHS) == LHS)
1864     return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1865   
1866
1867   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1868   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1869     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1870       return R;
1871
1872   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1873     Value *X = 0;
1874     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
1875       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1876       return BinaryOperator::createSub(C, X);
1877     }
1878
1879     // (X & FF00) + xx00  -> (X+xx00) & FF00
1880     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1881       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1882       if (Anded == CRHS) {
1883         // See if all bits from the first bit set in the Add RHS up are included
1884         // in the mask.  First, get the rightmost bit.
1885         uint64_t AddRHSV = CRHS->getZExtValue();
1886
1887         // Form a mask of all bits from the lowest bit added through the top.
1888         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1889         AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1890
1891         // See if the and mask includes all of these bits.
1892         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1893
1894         if (AddRHSHighBits == AddRHSHighBitsAnd) {
1895           // Okay, the xform is safe.  Insert the new add pronto.
1896           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1897                                                             LHS->getName()), I);
1898           return BinaryOperator::createAnd(NewAdd, C2);
1899         }
1900       }
1901     }
1902
1903     // Try to fold constant add into select arguments.
1904     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1905       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1906         return R;
1907   }
1908
1909   // add (cast *A to intptrtype) B -> 
1910   //   cast (GEP (cast *A to sbyte*) B) -> 
1911   //     intptrtype
1912   {
1913     CastInst *CI = dyn_cast<CastInst>(LHS);
1914     Value *Other = RHS;
1915     if (!CI) {
1916       CI = dyn_cast<CastInst>(RHS);
1917       Other = LHS;
1918     }
1919     if (CI && CI->getType()->isSized() && 
1920         (CI->getType()->getPrimitiveSizeInBits() == 
1921          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
1922         && isa<PointerType>(CI->getOperand(0)->getType())) {
1923       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
1924                                    PointerType::get(Type::Int8Ty), I);
1925       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1926       return new PtrToIntInst(I2, CI->getType());
1927     }
1928   }
1929
1930   return Changed ? &I : 0;
1931 }
1932
1933 // isSignBit - Return true if the value represented by the constant only has the
1934 // highest order bit set.
1935 static bool isSignBit(ConstantInt *CI) {
1936   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1937   return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1938 }
1939
1940 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1941 ///
1942 static Value *RemoveNoopCast(Value *V) {
1943   if (CastInst *CI = dyn_cast<CastInst>(V)) {
1944     const Type *CTy = CI->getType();
1945     const Type *OpTy = CI->getOperand(0)->getType();
1946     if (CTy->isInteger() && OpTy->isInteger()) {
1947       if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1948         return RemoveNoopCast(CI->getOperand(0));
1949     } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1950       return RemoveNoopCast(CI->getOperand(0));
1951   }
1952   return V;
1953 }
1954
1955 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1956   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1957
1958   if (Op0 == Op1)         // sub X, X  -> 0
1959     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1960
1961   // If this is a 'B = x-(-A)', change to B = x+A...
1962   if (Value *V = dyn_castNegVal(Op1))
1963     return BinaryOperator::createAdd(Op0, V);
1964
1965   if (isa<UndefValue>(Op0))
1966     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
1967   if (isa<UndefValue>(Op1))
1968     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
1969
1970   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1971     // Replace (-1 - A) with (~A)...
1972     if (C->isAllOnesValue())
1973       return BinaryOperator::createNot(Op1);
1974
1975     // C - ~X == X + (1+C)
1976     Value *X = 0;
1977     if (match(Op1, m_Not(m_Value(X))))
1978       return BinaryOperator::createAdd(X,
1979                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1980     // -((uint)X >> 31) -> ((int)X >> 31)
1981     // -((int)X >> 31) -> ((uint)X >> 31)
1982     if (C->isNullValue()) {
1983       Value *NoopCastedRHS = RemoveNoopCast(Op1);
1984       if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1985         if (SI->getOpcode() == Instruction::LShr) {
1986           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1987             // Check to see if we are shifting out everything but the sign bit.
1988             if (CU->getZExtValue() == 
1989                 SI->getType()->getPrimitiveSizeInBits()-1) {
1990               // Ok, the transformation is safe.  Insert AShr.
1991               // FIXME: Once integer types are signless, this cast should be 
1992               // removed.  
1993               Value *ShiftOp = SI->getOperand(0); 
1994               return new ShiftInst(Instruction::AShr, ShiftOp, CU,
1995                                    SI->getName());
1996             }
1997           }
1998         }
1999         else if (SI->getOpcode() == Instruction::AShr) {
2000           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2001             // Check to see if we are shifting out everything but the sign bit.
2002             if (CU->getZExtValue() == 
2003                 SI->getType()->getPrimitiveSizeInBits()-1) {
2004               
2005               // Ok, the transformation is safe.  Insert LShr. 
2006               return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU, 
2007                                    SI->getName());
2008             }
2009           }
2010         } 
2011     }
2012
2013     // Try to fold constant sub into select arguments.
2014     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2015       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2016         return R;
2017
2018     if (isa<PHINode>(Op0))
2019       if (Instruction *NV = FoldOpIntoPhi(I))
2020         return NV;
2021   }
2022
2023   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2024     if (Op1I->getOpcode() == Instruction::Add &&
2025         !Op0->getType()->isFPOrFPVector()) {
2026       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2027         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2028       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2029         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2030       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2031         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2032           // C1-(X+C2) --> (C1-C2)-X
2033           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2034                                            Op1I->getOperand(0));
2035       }
2036     }
2037
2038     if (Op1I->hasOneUse()) {
2039       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2040       // is not used by anyone else...
2041       //
2042       if (Op1I->getOpcode() == Instruction::Sub &&
2043           !Op1I->getType()->isFPOrFPVector()) {
2044         // Swap the two operands of the subexpr...
2045         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2046         Op1I->setOperand(0, IIOp1);
2047         Op1I->setOperand(1, IIOp0);
2048
2049         // Create the new top level add instruction...
2050         return BinaryOperator::createAdd(Op0, Op1);
2051       }
2052
2053       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2054       //
2055       if (Op1I->getOpcode() == Instruction::And &&
2056           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2057         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2058
2059         Value *NewNot =
2060           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2061         return BinaryOperator::createAnd(Op0, NewNot);
2062       }
2063
2064       // 0 - (X sdiv C)  -> (X sdiv -C)
2065       if (Op1I->getOpcode() == Instruction::SDiv)
2066         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2067           if (CSI->isNullValue())
2068             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2069               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2070                                                ConstantExpr::getNeg(DivRHS));
2071
2072       // X - X*C --> X * (1-C)
2073       ConstantInt *C2 = 0;
2074       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2075         Constant *CP1 =
2076           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2077         return BinaryOperator::createMul(Op0, CP1);
2078       }
2079     }
2080   }
2081
2082   if (!Op0->getType()->isFPOrFPVector())
2083     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2084       if (Op0I->getOpcode() == Instruction::Add) {
2085         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2086           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2087         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2088           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2089       } else if (Op0I->getOpcode() == Instruction::Sub) {
2090         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2091           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2092       }
2093
2094   ConstantInt *C1;
2095   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2096     if (X == Op1) { // X*C - X --> X * (C-1)
2097       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2098       return BinaryOperator::createMul(Op1, CP1);
2099     }
2100
2101     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2102     if (X == dyn_castFoldableMul(Op1, C2))
2103       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2104   }
2105   return 0;
2106 }
2107
2108 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2109 /// really just returns true if the most significant (sign) bit is set.
2110 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2111   switch (pred) {
2112     case ICmpInst::ICMP_SLT: 
2113       // True if LHS s< RHS and RHS == 0
2114       return RHS->isNullValue();
2115     case ICmpInst::ICMP_SLE: 
2116       // True if LHS s<= RHS and RHS == -1
2117       return RHS->isAllOnesValue();
2118     case ICmpInst::ICMP_UGE: 
2119       // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2120       return RHS->getZExtValue() == (1ULL << 
2121         (RHS->getType()->getPrimitiveSizeInBits()-1));
2122     case ICmpInst::ICMP_UGT:
2123       // True if LHS u> RHS and RHS == high-bit-mask - 1
2124       return RHS->getZExtValue() ==
2125         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2126     default:
2127       return false;
2128   }
2129 }
2130
2131 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2132   bool Changed = SimplifyCommutative(I);
2133   Value *Op0 = I.getOperand(0);
2134
2135   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2136     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2137
2138   // Simplify mul instructions with a constant RHS...
2139   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2140     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2141
2142       // ((X << C1)*C2) == (X * (C2 << C1))
2143       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2144         if (SI->getOpcode() == Instruction::Shl)
2145           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2146             return BinaryOperator::createMul(SI->getOperand(0),
2147                                              ConstantExpr::getShl(CI, ShOp));
2148
2149       if (CI->isNullValue())
2150         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2151       if (CI->equalsInt(1))                  // X * 1  == X
2152         return ReplaceInstUsesWith(I, Op0);
2153       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2154         return BinaryOperator::createNeg(Op0, I.getName());
2155
2156       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2157       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2158         uint64_t C = Log2_64(Val);
2159         return new ShiftInst(Instruction::Shl, Op0,
2160                              ConstantInt::get(Type::Int8Ty, C));
2161       }
2162     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2163       if (Op1F->isNullValue())
2164         return ReplaceInstUsesWith(I, Op1);
2165
2166       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2167       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2168       if (Op1F->getValue() == 1.0)
2169         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2170     }
2171     
2172     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2173       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2174           isa<ConstantInt>(Op0I->getOperand(1))) {
2175         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2176         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2177                                                      Op1, "tmp");
2178         InsertNewInstBefore(Add, I);
2179         Value *C1C2 = ConstantExpr::getMul(Op1, 
2180                                            cast<Constant>(Op0I->getOperand(1)));
2181         return BinaryOperator::createAdd(Add, C1C2);
2182         
2183       }
2184
2185     // Try to fold constant mul into select arguments.
2186     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2187       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2188         return R;
2189
2190     if (isa<PHINode>(Op0))
2191       if (Instruction *NV = FoldOpIntoPhi(I))
2192         return NV;
2193   }
2194
2195   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2196     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2197       return BinaryOperator::createMul(Op0v, Op1v);
2198
2199   // If one of the operands of the multiply is a cast from a boolean value, then
2200   // we know the bool is either zero or one, so this is a 'masking' multiply.
2201   // See if we can simplify things based on how the boolean was originally
2202   // formed.
2203   CastInst *BoolCast = 0;
2204   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2205     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2206       BoolCast = CI;
2207   if (!BoolCast)
2208     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2209       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2210         BoolCast = CI;
2211   if (BoolCast) {
2212     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2213       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2214       const Type *SCOpTy = SCIOp0->getType();
2215
2216       // If the icmp is true iff the sign bit of X is set, then convert this
2217       // multiply into a shift/and combination.
2218       if (isa<ConstantInt>(SCIOp1) &&
2219           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
2220         // Shift the X value right to turn it into "all signbits".
2221         Constant *Amt = ConstantInt::get(Type::Int8Ty,
2222                                           SCOpTy->getPrimitiveSizeInBits()-1);
2223         Value *V =
2224           InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
2225                                             BoolCast->getOperand(0)->getName()+
2226                                             ".mask"), I);
2227
2228         // If the multiply type is not the same as the source type, sign extend
2229         // or truncate to the multiply type.
2230         if (I.getType() != V->getType()) {
2231           unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2232           unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2233           Instruction::CastOps opcode = 
2234             (SrcBits == DstBits ? Instruction::BitCast : 
2235              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2236           V = InsertCastBefore(opcode, V, I.getType(), I);
2237         }
2238
2239         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2240         return BinaryOperator::createAnd(V, OtherOp);
2241       }
2242     }
2243   }
2244
2245   return Changed ? &I : 0;
2246 }
2247
2248 /// This function implements the transforms on div instructions that work
2249 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2250 /// used by the visitors to those instructions.
2251 /// @brief Transforms common to all three div instructions
2252 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2253   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2254
2255   // undef / X -> 0
2256   if (isa<UndefValue>(Op0))
2257     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2258
2259   // X / undef -> undef
2260   if (isa<UndefValue>(Op1))
2261     return ReplaceInstUsesWith(I, Op1);
2262
2263   // Handle cases involving: div X, (select Cond, Y, Z)
2264   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2265     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2266     // same basic block, then we replace the select with Y, and the condition 
2267     // of the select with false (if the cond value is in the same BB).  If the
2268     // select has uses other than the div, this allows them to be simplified
2269     // also. Note that div X, Y is just as good as div X, 0 (undef)
2270     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2271       if (ST->isNullValue()) {
2272         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2273         if (CondI && CondI->getParent() == I.getParent())
2274           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2275         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2276           I.setOperand(1, SI->getOperand(2));
2277         else
2278           UpdateValueUsesWith(SI, SI->getOperand(2));
2279         return &I;
2280       }
2281
2282     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2283     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2284       if (ST->isNullValue()) {
2285         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2286         if (CondI && CondI->getParent() == I.getParent())
2287           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2288         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2289           I.setOperand(1, SI->getOperand(1));
2290         else
2291           UpdateValueUsesWith(SI, SI->getOperand(1));
2292         return &I;
2293       }
2294   }
2295
2296   return 0;
2297 }
2298
2299 /// This function implements the transforms common to both integer division
2300 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2301 /// division instructions.
2302 /// @brief Common integer divide transforms
2303 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2304   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2305
2306   if (Instruction *Common = commonDivTransforms(I))
2307     return Common;
2308
2309   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2310     // div X, 1 == X
2311     if (RHS->equalsInt(1))
2312       return ReplaceInstUsesWith(I, Op0);
2313
2314     // (X / C1) / C2  -> X / (C1*C2)
2315     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2316       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2317         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2318           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2319                                         ConstantExpr::getMul(RHS, LHSRHS));
2320         }
2321
2322     if (!RHS->isNullValue()) { // avoid X udiv 0
2323       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2324         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2325           return R;
2326       if (isa<PHINode>(Op0))
2327         if (Instruction *NV = FoldOpIntoPhi(I))
2328           return NV;
2329     }
2330   }
2331
2332   // 0 / X == 0, we don't need to preserve faults!
2333   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2334     if (LHS->equalsInt(0))
2335       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2336
2337   return 0;
2338 }
2339
2340 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2341   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2342
2343   // Handle the integer div common cases
2344   if (Instruction *Common = commonIDivTransforms(I))
2345     return Common;
2346
2347   // X udiv C^2 -> X >> C
2348   // Check to see if this is an unsigned division with an exact power of 2,
2349   // if so, convert to a right shift.
2350   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2351     if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
2352       if (isPowerOf2_64(Val)) {
2353         uint64_t ShiftAmt = Log2_64(Val);
2354         return new ShiftInst(Instruction::LShr, Op0, 
2355                               ConstantInt::get(Type::Int8Ty, ShiftAmt));
2356       }
2357   }
2358
2359   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2360   if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2361     if (RHSI->getOpcode() == Instruction::Shl &&
2362         isa<ConstantInt>(RHSI->getOperand(0))) {
2363       uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2364       if (isPowerOf2_64(C1)) {
2365         Value *N = RHSI->getOperand(1);
2366         const Type *NTy = N->getType();
2367         if (uint64_t C2 = Log2_64(C1)) {
2368           Constant *C2V = ConstantInt::get(NTy, C2);
2369           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2370         }
2371         return new ShiftInst(Instruction::LShr, Op0, N);
2372       }
2373     }
2374   }
2375   
2376   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2377   // where C1&C2 are powers of two.
2378   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2379     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2380       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) 
2381         if (!STO->isNullValue() && !STO->isNullValue()) {
2382           uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2383           if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2384             // Compute the shift amounts
2385             unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2386             // Construct the "on true" case of the select
2387             Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
2388             Instruction *TSI = 
2389               new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
2390             TSI = InsertNewInstBefore(TSI, I);
2391     
2392             // Construct the "on false" case of the select
2393             Constant *FC = ConstantInt::get(Type::Int8Ty, FSA); 
2394             Instruction *FSI = 
2395               new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
2396             FSI = InsertNewInstBefore(FSI, I);
2397
2398             // construct the select instruction and return it.
2399             return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2400           }
2401         }
2402   }
2403   return 0;
2404 }
2405
2406 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2407   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2408
2409   // Handle the integer div common cases
2410   if (Instruction *Common = commonIDivTransforms(I))
2411     return Common;
2412
2413   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2414     // sdiv X, -1 == -X
2415     if (RHS->isAllOnesValue())
2416       return BinaryOperator::createNeg(Op0);
2417
2418     // -X/C -> X/-C
2419     if (Value *LHSNeg = dyn_castNegVal(Op0))
2420       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2421   }
2422
2423   // If the sign bits of both operands are zero (i.e. we can prove they are
2424   // unsigned inputs), turn this into a udiv.
2425   if (I.getType()->isInteger()) {
2426     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2427     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2428       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2429     }
2430   }      
2431   
2432   return 0;
2433 }
2434
2435 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2436   return commonDivTransforms(I);
2437 }
2438
2439 /// GetFactor - If we can prove that the specified value is at least a multiple
2440 /// of some factor, return that factor.
2441 static Constant *GetFactor(Value *V) {
2442   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2443     return CI;
2444   
2445   // Unless we can be tricky, we know this is a multiple of 1.
2446   Constant *Result = ConstantInt::get(V->getType(), 1);
2447   
2448   Instruction *I = dyn_cast<Instruction>(V);
2449   if (!I) return Result;
2450   
2451   if (I->getOpcode() == Instruction::Mul) {
2452     // Handle multiplies by a constant, etc.
2453     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2454                                 GetFactor(I->getOperand(1)));
2455   } else if (I->getOpcode() == Instruction::Shl) {
2456     // (X<<C) -> X * (1 << C)
2457     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2458       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2459       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2460     }
2461   } else if (I->getOpcode() == Instruction::And) {
2462     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2463       // X & 0xFFF0 is known to be a multiple of 16.
2464       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2465       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2466         return ConstantExpr::getShl(Result, 
2467                                     ConstantInt::get(Type::Int8Ty, Zeros));
2468     }
2469   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2470     // Only handle int->int casts.
2471     if (!CI->isIntegerCast())
2472       return Result;
2473     Value *Op = CI->getOperand(0);
2474     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2475   }    
2476   return Result;
2477 }
2478
2479 /// This function implements the transforms on rem instructions that work
2480 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2481 /// is used by the visitors to those instructions.
2482 /// @brief Transforms common to all three rem instructions
2483 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2484   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2485
2486   // 0 % X == 0, we don't need to preserve faults!
2487   if (Constant *LHS = dyn_cast<Constant>(Op0))
2488     if (LHS->isNullValue())
2489       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2490
2491   if (isa<UndefValue>(Op0))              // undef % X -> 0
2492     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2493   if (isa<UndefValue>(Op1))
2494     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2495
2496   // Handle cases involving: rem X, (select Cond, Y, Z)
2497   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2498     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2499     // the same basic block, then we replace the select with Y, and the
2500     // condition of the select with false (if the cond value is in the same
2501     // BB).  If the select has uses other than the div, this allows them to be
2502     // simplified also.
2503     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2504       if (ST->isNullValue()) {
2505         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2506         if (CondI && CondI->getParent() == I.getParent())
2507           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2508         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2509           I.setOperand(1, SI->getOperand(2));
2510         else
2511           UpdateValueUsesWith(SI, SI->getOperand(2));
2512         return &I;
2513       }
2514     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2515     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2516       if (ST->isNullValue()) {
2517         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2518         if (CondI && CondI->getParent() == I.getParent())
2519           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2520         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2521           I.setOperand(1, SI->getOperand(1));
2522         else
2523           UpdateValueUsesWith(SI, SI->getOperand(1));
2524         return &I;
2525       }
2526   }
2527
2528   return 0;
2529 }
2530
2531 /// This function implements the transforms common to both integer remainder
2532 /// instructions (urem and srem). It is called by the visitors to those integer
2533 /// remainder instructions.
2534 /// @brief Common integer remainder transforms
2535 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2536   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2537
2538   if (Instruction *common = commonRemTransforms(I))
2539     return common;
2540
2541   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2542     // X % 0 == undef, we don't need to preserve faults!
2543     if (RHS->equalsInt(0))
2544       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2545     
2546     if (RHS->equalsInt(1))  // X % 1 == 0
2547       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2548
2549     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2550       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2551         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2552           return R;
2553       } else if (isa<PHINode>(Op0I)) {
2554         if (Instruction *NV = FoldOpIntoPhi(I))
2555           return NV;
2556       }
2557       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2558       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2559         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2560     }
2561   }
2562
2563   return 0;
2564 }
2565
2566 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2567   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2568
2569   if (Instruction *common = commonIRemTransforms(I))
2570     return common;
2571   
2572   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2573     // X urem C^2 -> X and C
2574     // Check to see if this is an unsigned remainder with an exact power of 2,
2575     // if so, convert to a bitwise and.
2576     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2577       if (isPowerOf2_64(C->getZExtValue()))
2578         return BinaryOperator::createAnd(Op0, SubOne(C));
2579   }
2580
2581   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2582     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2583     if (RHSI->getOpcode() == Instruction::Shl &&
2584         isa<ConstantInt>(RHSI->getOperand(0))) {
2585       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2586       if (isPowerOf2_64(C1)) {
2587         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2588         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2589                                                                    "tmp"), I);
2590         return BinaryOperator::createAnd(Op0, Add);
2591       }
2592     }
2593   }
2594
2595   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2596   // where C1&C2 are powers of two.
2597   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2598     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2599       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2600         // STO == 0 and SFO == 0 handled above.
2601         if (isPowerOf2_64(STO->getZExtValue()) && 
2602             isPowerOf2_64(SFO->getZExtValue())) {
2603           Value *TrueAnd = InsertNewInstBefore(
2604             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2605           Value *FalseAnd = InsertNewInstBefore(
2606             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2607           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2608         }
2609       }
2610   }
2611   
2612   return 0;
2613 }
2614
2615 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2616   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2617
2618   if (Instruction *common = commonIRemTransforms(I))
2619     return common;
2620   
2621   if (Value *RHSNeg = dyn_castNegVal(Op1))
2622     if (!isa<ConstantInt>(RHSNeg) || 
2623         cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2624       // X % -Y -> X % Y
2625       AddUsesToWorkList(I);
2626       I.setOperand(1, RHSNeg);
2627       return &I;
2628     }
2629  
2630   // If the top bits of both operands are zero (i.e. we can prove they are
2631   // unsigned inputs), turn this into a urem.
2632   uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2633   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2634     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2635     return BinaryOperator::createURem(Op0, Op1, I.getName());
2636   }
2637
2638   return 0;
2639 }
2640
2641 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2642   return commonRemTransforms(I);
2643 }
2644
2645 // isMaxValueMinusOne - return true if this is Max-1
2646 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2647   if (isSigned) {
2648     // Calculate 0111111111..11111
2649     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2650     int64_t Val = INT64_MAX;             // All ones
2651     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
2652     return C->getSExtValue() == Val-1;
2653   }
2654   return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
2655 }
2656
2657 // isMinValuePlusOne - return true if this is Min+1
2658 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2659   if (isSigned) {
2660     // Calculate 1111111111000000000000
2661     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2662     int64_t Val = -1;                    // All ones
2663     Val <<= TypeBits-1;                  // Shift over to the right spot
2664     return C->getSExtValue() == Val+1;
2665   }
2666   return C->getZExtValue() == 1; // unsigned
2667 }
2668
2669 // isOneBitSet - Return true if there is exactly one bit set in the specified
2670 // constant.
2671 static bool isOneBitSet(const ConstantInt *CI) {
2672   uint64_t V = CI->getZExtValue();
2673   return V && (V & (V-1)) == 0;
2674 }
2675
2676 #if 0   // Currently unused
2677 // isLowOnes - Return true if the constant is of the form 0+1+.
2678 static bool isLowOnes(const ConstantInt *CI) {
2679   uint64_t V = CI->getZExtValue();
2680
2681   // There won't be bits set in parts that the type doesn't contain.
2682   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2683
2684   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2685   return U && V && (U & V) == 0;
2686 }
2687 #endif
2688
2689 // isHighOnes - Return true if the constant is of the form 1+0+.
2690 // This is the same as lowones(~X).
2691 static bool isHighOnes(const ConstantInt *CI) {
2692   uint64_t V = ~CI->getZExtValue();
2693   if (~V == 0) return false;  // 0's does not match "1+"
2694
2695   // There won't be bits set in parts that the type doesn't contain.
2696   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2697
2698   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2699   return U && V && (U & V) == 0;
2700 }
2701
2702 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2703 /// are carefully arranged to allow folding of expressions such as:
2704 ///
2705 ///      (A < B) | (A > B) --> (A != B)
2706 ///
2707 /// Note that this is only valid if the first and second predicates have the
2708 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2709 ///
2710 /// Three bits are used to represent the condition, as follows:
2711 ///   0  A > B
2712 ///   1  A == B
2713 ///   2  A < B
2714 ///
2715 /// <=>  Value  Definition
2716 /// 000     0   Always false
2717 /// 001     1   A >  B
2718 /// 010     2   A == B
2719 /// 011     3   A >= B
2720 /// 100     4   A <  B
2721 /// 101     5   A != B
2722 /// 110     6   A <= B
2723 /// 111     7   Always true
2724 ///  
2725 static unsigned getICmpCode(const ICmpInst *ICI) {
2726   switch (ICI->getPredicate()) {
2727     // False -> 0
2728   case ICmpInst::ICMP_UGT: return 1;  // 001
2729   case ICmpInst::ICMP_SGT: return 1;  // 001
2730   case ICmpInst::ICMP_EQ:  return 2;  // 010
2731   case ICmpInst::ICMP_UGE: return 3;  // 011
2732   case ICmpInst::ICMP_SGE: return 3;  // 011
2733   case ICmpInst::ICMP_ULT: return 4;  // 100
2734   case ICmpInst::ICMP_SLT: return 4;  // 100
2735   case ICmpInst::ICMP_NE:  return 5;  // 101
2736   case ICmpInst::ICMP_ULE: return 6;  // 110
2737   case ICmpInst::ICMP_SLE: return 6;  // 110
2738     // True -> 7
2739   default:
2740     assert(0 && "Invalid ICmp predicate!");
2741     return 0;
2742   }
2743 }
2744
2745 /// getICmpValue - This is the complement of getICmpCode, which turns an
2746 /// opcode and two operands into either a constant true or false, or a brand 
2747 /// new /// ICmp instruction. The sign is passed in to determine which kind
2748 /// of predicate to use in new icmp instructions.
2749 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2750   switch (code) {
2751   default: assert(0 && "Illegal ICmp code!");
2752   case  0: return ConstantInt::getFalse();
2753   case  1: 
2754     if (sign)
2755       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2756     else
2757       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2758   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
2759   case  3: 
2760     if (sign)
2761       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2762     else
2763       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2764   case  4: 
2765     if (sign)
2766       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2767     else
2768       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2769   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
2770   case  6: 
2771     if (sign)
2772       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2773     else
2774       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2775   case  7: return ConstantInt::getTrue();
2776   }
2777 }
2778
2779 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2780   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2781     (ICmpInst::isSignedPredicate(p1) && 
2782      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2783     (ICmpInst::isSignedPredicate(p2) && 
2784      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2785 }
2786
2787 namespace { 
2788 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2789 struct FoldICmpLogical {
2790   InstCombiner &IC;
2791   Value *LHS, *RHS;
2792   ICmpInst::Predicate pred;
2793   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2794     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2795       pred(ICI->getPredicate()) {}
2796   bool shouldApply(Value *V) const {
2797     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2798       if (PredicatesFoldable(pred, ICI->getPredicate()))
2799         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2800                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2801     return false;
2802   }
2803   Instruction *apply(Instruction &Log) const {
2804     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2805     if (ICI->getOperand(0) != LHS) {
2806       assert(ICI->getOperand(1) == LHS);
2807       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
2808     }
2809
2810     unsigned LHSCode = getICmpCode(ICI);
2811     unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
2812     unsigned Code;
2813     switch (Log.getOpcode()) {
2814     case Instruction::And: Code = LHSCode & RHSCode; break;
2815     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2816     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2817     default: assert(0 && "Illegal logical opcode!"); return 0;
2818     }
2819
2820     Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
2821     if (Instruction *I = dyn_cast<Instruction>(RV))
2822       return I;
2823     // Otherwise, it's a constant boolean value...
2824     return IC.ReplaceInstUsesWith(Log, RV);
2825   }
2826 };
2827 } // end anonymous namespace
2828
2829 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2830 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2831 // guaranteed to be either a shift instruction or a binary operator.
2832 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2833                                     ConstantInt *OpRHS,
2834                                     ConstantInt *AndRHS,
2835                                     BinaryOperator &TheAnd) {
2836   Value *X = Op->getOperand(0);
2837   Constant *Together = 0;
2838   if (!isa<ShiftInst>(Op))
2839     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2840
2841   switch (Op->getOpcode()) {
2842   case Instruction::Xor:
2843     if (Op->hasOneUse()) {
2844       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2845       std::string OpName = Op->getName(); Op->setName("");
2846       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2847       InsertNewInstBefore(And, TheAnd);
2848       return BinaryOperator::createXor(And, Together);
2849     }
2850     break;
2851   case Instruction::Or:
2852     if (Together == AndRHS) // (X | C) & C --> C
2853       return ReplaceInstUsesWith(TheAnd, AndRHS);
2854
2855     if (Op->hasOneUse() && Together != OpRHS) {
2856       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2857       std::string Op0Name = Op->getName(); Op->setName("");
2858       Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2859       InsertNewInstBefore(Or, TheAnd);
2860       return BinaryOperator::createAnd(Or, AndRHS);
2861     }
2862     break;
2863   case Instruction::Add:
2864     if (Op->hasOneUse()) {
2865       // Adding a one to a single bit bit-field should be turned into an XOR
2866       // of the bit.  First thing to check is to see if this AND is with a
2867       // single bit constant.
2868       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2869
2870       // Clear bits that are not part of the constant.
2871       AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2872
2873       // If there is only one bit set...
2874       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2875         // Ok, at this point, we know that we are masking the result of the
2876         // ADD down to exactly one bit.  If the constant we are adding has
2877         // no bits set below this bit, then we can eliminate the ADD.
2878         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2879
2880         // Check to see if any bits below the one bit set in AndRHSV are set.
2881         if ((AddRHS & (AndRHSV-1)) == 0) {
2882           // If not, the only thing that can effect the output of the AND is
2883           // the bit specified by AndRHSV.  If that bit is set, the effect of
2884           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2885           // no effect.
2886           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2887             TheAnd.setOperand(0, X);
2888             return &TheAnd;
2889           } else {
2890             std::string Name = Op->getName(); Op->setName("");
2891             // Pull the XOR out of the AND.
2892             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2893             InsertNewInstBefore(NewAnd, TheAnd);
2894             return BinaryOperator::createXor(NewAnd, AndRHS);
2895           }
2896         }
2897       }
2898     }
2899     break;
2900
2901   case Instruction::Shl: {
2902     // We know that the AND will not produce any of the bits shifted in, so if
2903     // the anded constant includes them, clear them now!
2904     //
2905     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2906     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2907     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2908
2909     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2910       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2911     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2912       TheAnd.setOperand(1, CI);
2913       return &TheAnd;
2914     }
2915     break;
2916   }
2917   case Instruction::LShr:
2918   {
2919     // We know that the AND will not produce any of the bits shifted in, so if
2920     // the anded constant includes them, clear them now!  This only applies to
2921     // unsigned shifts, because a signed shr may bring in set bits!
2922     //
2923     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2924     Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2925     Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2926
2927     if (CI == ShrMask) {   // Masking out bits that the shift already masks.
2928       return ReplaceInstUsesWith(TheAnd, Op);
2929     } else if (CI != AndRHS) {
2930       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
2931       return &TheAnd;
2932     }
2933     break;
2934   }
2935   case Instruction::AShr:
2936     // Signed shr.
2937     // See if this is shifting in some sign extension, then masking it out
2938     // with an and.
2939     if (Op->hasOneUse()) {
2940       Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2941       Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2942       Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2943       if (C == AndRHS) {          // Masking out bits shifted in.
2944         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
2945         // Make the argument unsigned.
2946         Value *ShVal = Op->getOperand(0);
2947         ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal, 
2948                                     OpRHS, Op->getName()), TheAnd);
2949         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
2950       }
2951     }
2952     break;
2953   }
2954   return 0;
2955 }
2956
2957
2958 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2959 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
2960 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
2961 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
2962 /// insert new instructions.
2963 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2964                                            bool isSigned, bool Inside, 
2965                                            Instruction &IB) {
2966   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
2967             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
2968          "Lo is not <= Hi in range emission code!");
2969     
2970   if (Inside) {
2971     if (Lo == Hi)  // Trivially false.
2972       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
2973
2974     // V >= Min && V < Hi --> V < Hi
2975     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2976     ICmpInst::Predicate pred = (isSigned ? 
2977         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2978       return new ICmpInst(pred, V, Hi);
2979     }
2980
2981     // Emit V-Lo <u Hi-Lo
2982     Constant *NegLo = ConstantExpr::getNeg(Lo);
2983     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2984     InsertNewInstBefore(Add, IB);
2985     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2986     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
2987   }
2988
2989   if (Lo == Hi)  // Trivially true.
2990     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
2991
2992   // V < Min || V >= Hi ->'V > Hi-1'
2993   Hi = SubOne(cast<ConstantInt>(Hi));
2994   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2995     ICmpInst::Predicate pred = (isSigned ? 
2996         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
2997     return new ICmpInst(pred, V, Hi);
2998   }
2999
3000   // Emit V-Lo > Hi-1-Lo
3001   Constant *NegLo = ConstantExpr::getNeg(Lo);
3002   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3003   InsertNewInstBefore(Add, IB);
3004   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3005   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3006 }
3007
3008 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3009 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3010 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3011 // not, since all 1s are not contiguous.
3012 static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
3013   uint64_t V = Val->getZExtValue();
3014   if (!isShiftedMask_64(V)) return false;
3015
3016   // look for the first zero bit after the run of ones
3017   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3018   // look for the first non-zero bit
3019   ME = 64-CountLeadingZeros_64(V);
3020   return true;
3021 }
3022
3023
3024
3025 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3026 /// where isSub determines whether the operator is a sub.  If we can fold one of
3027 /// the following xforms:
3028 /// 
3029 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3030 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3031 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3032 ///
3033 /// return (A +/- B).
3034 ///
3035 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3036                                         ConstantInt *Mask, bool isSub,
3037                                         Instruction &I) {
3038   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3039   if (!LHSI || LHSI->getNumOperands() != 2 ||
3040       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3041
3042   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3043
3044   switch (LHSI->getOpcode()) {
3045   default: return 0;
3046   case Instruction::And:
3047     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3048       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3049       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3050         break;
3051
3052       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3053       // part, we don't need any explicit masks to take them out of A.  If that
3054       // is all N is, ignore it.
3055       unsigned MB, ME;
3056       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3057         uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3058         Mask >>= 64-MB+1;
3059         if (MaskedValueIsZero(RHS, Mask))
3060           break;
3061       }
3062     }
3063     return 0;
3064   case Instruction::Or:
3065   case Instruction::Xor:
3066     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3067     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3068         ConstantExpr::getAnd(N, Mask)->isNullValue())
3069       break;
3070     return 0;
3071   }
3072   
3073   Instruction *New;
3074   if (isSub)
3075     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3076   else
3077     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3078   return InsertNewInstBefore(New, I);
3079 }
3080
3081 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3082   bool Changed = SimplifyCommutative(I);
3083   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3084
3085   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3086     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3087
3088   // and X, X = X
3089   if (Op0 == Op1)
3090     return ReplaceInstUsesWith(I, Op1);
3091
3092   // See if we can simplify any instructions used by the instruction whose sole 
3093   // purpose is to compute bits we don't care about.
3094   uint64_t KnownZero, KnownOne;
3095   if (!isa<PackedType>(I.getType()) &&
3096       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3097                            KnownZero, KnownOne))
3098     return &I;
3099   
3100   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3101     uint64_t AndRHSMask = AndRHS->getZExtValue();
3102     uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
3103     uint64_t NotAndRHS = AndRHSMask^TypeMask;
3104
3105     // Optimize a variety of ((val OP C1) & C2) combinations...
3106     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3107       Instruction *Op0I = cast<Instruction>(Op0);
3108       Value *Op0LHS = Op0I->getOperand(0);
3109       Value *Op0RHS = Op0I->getOperand(1);
3110       switch (Op0I->getOpcode()) {
3111       case Instruction::Xor:
3112       case Instruction::Or:
3113         // If the mask is only needed on one incoming arm, push it up.
3114         if (Op0I->hasOneUse()) {
3115           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3116             // Not masking anything out for the LHS, move to RHS.
3117             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3118                                                    Op0RHS->getName()+".masked");
3119             InsertNewInstBefore(NewRHS, I);
3120             return BinaryOperator::create(
3121                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3122           }
3123           if (!isa<Constant>(Op0RHS) &&
3124               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3125             // Not masking anything out for the RHS, move to LHS.
3126             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3127                                                    Op0LHS->getName()+".masked");
3128             InsertNewInstBefore(NewLHS, I);
3129             return BinaryOperator::create(
3130                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3131           }
3132         }
3133
3134         break;
3135       case Instruction::Add:
3136         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3137         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3138         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3139         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3140           return BinaryOperator::createAnd(V, AndRHS);
3141         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3142           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3143         break;
3144
3145       case Instruction::Sub:
3146         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3147         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3148         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3149         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3150           return BinaryOperator::createAnd(V, AndRHS);
3151         break;
3152       }
3153
3154       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3155         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3156           return Res;
3157     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3158       // If this is an integer truncation or change from signed-to-unsigned, and
3159       // if the source is an and/or with immediate, transform it.  This
3160       // frequently occurs for bitfield accesses.
3161       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3162         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3163             CastOp->getNumOperands() == 2)
3164           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3165             if (CastOp->getOpcode() == Instruction::And) {
3166               // Change: and (cast (and X, C1) to T), C2
3167               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3168               // This will fold the two constants together, which may allow 
3169               // other simplifications.
3170               Instruction *NewCast = CastInst::createTruncOrBitCast(
3171                 CastOp->getOperand(0), I.getType(), 
3172                 CastOp->getName()+".shrunk");
3173               NewCast = InsertNewInstBefore(NewCast, I);
3174               // trunc_or_bitcast(C1)&C2
3175               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3176               C3 = ConstantExpr::getAnd(C3, AndRHS);
3177               return BinaryOperator::createAnd(NewCast, C3);
3178             } else if (CastOp->getOpcode() == Instruction::Or) {
3179               // Change: and (cast (or X, C1) to T), C2
3180               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3181               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3182               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3183                 return ReplaceInstUsesWith(I, AndRHS);
3184             }
3185       }
3186     }
3187
3188     // Try to fold constant and into select arguments.
3189     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3190       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3191         return R;
3192     if (isa<PHINode>(Op0))
3193       if (Instruction *NV = FoldOpIntoPhi(I))
3194         return NV;
3195   }
3196
3197   Value *Op0NotVal = dyn_castNotVal(Op0);
3198   Value *Op1NotVal = dyn_castNotVal(Op1);
3199
3200   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3201     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3202
3203   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3204   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3205     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3206                                                I.getName()+".demorgan");
3207     InsertNewInstBefore(Or, I);
3208     return BinaryOperator::createNot(Or);
3209   }
3210   
3211   {
3212     Value *A = 0, *B = 0;
3213     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3214       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3215         return ReplaceInstUsesWith(I, Op1);
3216     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3217       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3218         return ReplaceInstUsesWith(I, Op0);
3219     
3220     if (Op0->hasOneUse() &&
3221         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3222       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3223         I.swapOperands();     // Simplify below
3224         std::swap(Op0, Op1);
3225       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3226         cast<BinaryOperator>(Op0)->swapOperands();
3227         I.swapOperands();     // Simplify below
3228         std::swap(Op0, Op1);
3229       }
3230     }
3231     if (Op1->hasOneUse() &&
3232         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3233       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3234         cast<BinaryOperator>(Op1)->swapOperands();
3235         std::swap(A, B);
3236       }
3237       if (A == Op0) {                                // A&(A^B) -> A & ~B
3238         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3239         InsertNewInstBefore(NotB, I);
3240         return BinaryOperator::createAnd(A, NotB);
3241       }
3242     }
3243   }
3244   
3245   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3246     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3247     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3248       return R;
3249
3250     Value *LHSVal, *RHSVal;
3251     ConstantInt *LHSCst, *RHSCst;
3252     ICmpInst::Predicate LHSCC, RHSCC;
3253     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3254       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3255         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3256             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3257             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3258             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3259             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3260             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3261           // Ensure that the larger constant is on the RHS.
3262           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3263             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3264           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3265           ICmpInst *LHS = cast<ICmpInst>(Op0);
3266           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3267             std::swap(LHS, RHS);
3268             std::swap(LHSCst, RHSCst);
3269             std::swap(LHSCC, RHSCC);
3270           }
3271
3272           // At this point, we know we have have two icmp instructions
3273           // comparing a value against two constants and and'ing the result
3274           // together.  Because of the above check, we know that we only have
3275           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3276           // (from the FoldICmpLogical check above), that the two constants 
3277           // are not equal and that the larger constant is on the RHS
3278           assert(LHSCst != RHSCst && "Compares not folded above?");
3279
3280           switch (LHSCC) {
3281           default: assert(0 && "Unknown integer condition code!");
3282           case ICmpInst::ICMP_EQ:
3283             switch (RHSCC) {
3284             default: assert(0 && "Unknown integer condition code!");
3285             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3286             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3287             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3288               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3289             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3290             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3291             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3292               return ReplaceInstUsesWith(I, LHS);
3293             }
3294           case ICmpInst::ICMP_NE:
3295             switch (RHSCC) {
3296             default: assert(0 && "Unknown integer condition code!");
3297             case ICmpInst::ICMP_ULT:
3298               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3299                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3300               break;                        // (X != 13 & X u< 15) -> no change
3301             case ICmpInst::ICMP_SLT:
3302               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3303                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3304               break;                        // (X != 13 & X s< 15) -> no change
3305             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3306             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3307             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3308               return ReplaceInstUsesWith(I, RHS);
3309             case ICmpInst::ICMP_NE:
3310               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3311                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3312                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3313                                                       LHSVal->getName()+".off");
3314                 InsertNewInstBefore(Add, I);
3315                 return new ICmpInst(ICmpInst::ICMP_UGT, Add, AddCST);
3316               }
3317               break;                        // (X != 13 & X != 15) -> no change
3318             }
3319             break;
3320           case ICmpInst::ICMP_ULT:
3321             switch (RHSCC) {
3322             default: assert(0 && "Unknown integer condition code!");
3323             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3324             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3325               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3326             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3327               break;
3328             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3329             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3330               return ReplaceInstUsesWith(I, LHS);
3331             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3332               break;
3333             }
3334             break;
3335           case ICmpInst::ICMP_SLT:
3336             switch (RHSCC) {
3337             default: assert(0 && "Unknown integer condition code!");
3338             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3339             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3340               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3341             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3342               break;
3343             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3344             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3345               return ReplaceInstUsesWith(I, LHS);
3346             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3347               break;
3348             }
3349             break;
3350           case ICmpInst::ICMP_UGT:
3351             switch (RHSCC) {
3352             default: assert(0 && "Unknown integer condition code!");
3353             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3354               return ReplaceInstUsesWith(I, LHS);
3355             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3356               return ReplaceInstUsesWith(I, RHS);
3357             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3358               break;
3359             case ICmpInst::ICMP_NE:
3360               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3361                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3362               break;                        // (X u> 13 & X != 15) -> no change
3363             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3364               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3365                                      true, I);
3366             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3367               break;
3368             }
3369             break;
3370           case ICmpInst::ICMP_SGT:
3371             switch (RHSCC) {
3372             default: assert(0 && "Unknown integer condition code!");
3373             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
3374               return ReplaceInstUsesWith(I, LHS);
3375             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3376               return ReplaceInstUsesWith(I, RHS);
3377             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3378               break;
3379             case ICmpInst::ICMP_NE:
3380               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3381                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3382               break;                        // (X s> 13 & X != 15) -> no change
3383             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3384               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3385                                      true, I);
3386             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3387               break;
3388             }
3389             break;
3390           }
3391         }
3392   }
3393
3394   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3395   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3396     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3397       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3398         const Type *SrcTy = Op0C->getOperand(0)->getType();
3399         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3400             // Only do this if the casts both really cause code to be generated.
3401             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3402                               I.getType(), TD) &&
3403             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3404                               I.getType(), TD)) {
3405           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3406                                                          Op1C->getOperand(0),
3407                                                          I.getName());
3408           InsertNewInstBefore(NewOp, I);
3409           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3410         }
3411       }
3412     
3413   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3414   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3415     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3416       if (SI0->getOpcode() == SI1->getOpcode() && 
3417           SI0->getOperand(1) == SI1->getOperand(1) &&
3418           (SI0->hasOneUse() || SI1->hasOneUse())) {
3419         Instruction *NewOp =
3420           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3421                                                         SI1->getOperand(0),
3422                                                         SI0->getName()), I);
3423         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3424       }
3425   }
3426
3427   return Changed ? &I : 0;
3428 }
3429
3430 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3431 /// in the result.  If it does, and if the specified byte hasn't been filled in
3432 /// yet, fill it in and return false.
3433 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3434   Instruction *I = dyn_cast<Instruction>(V);
3435   if (I == 0) return true;
3436
3437   // If this is an or instruction, it is an inner node of the bswap.
3438   if (I->getOpcode() == Instruction::Or)
3439     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3440            CollectBSwapParts(I->getOperand(1), ByteValues);
3441   
3442   // If this is a shift by a constant int, and it is "24", then its operand
3443   // defines a byte.  We only handle unsigned types here.
3444   if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3445     // Not shifting the entire input by N-1 bytes?
3446     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3447         8*(ByteValues.size()-1))
3448       return true;
3449     
3450     unsigned DestNo;
3451     if (I->getOpcode() == Instruction::Shl) {
3452       // X << 24 defines the top byte with the lowest of the input bytes.
3453       DestNo = ByteValues.size()-1;
3454     } else {
3455       // X >>u 24 defines the low byte with the highest of the input bytes.
3456       DestNo = 0;
3457     }
3458     
3459     // If the destination byte value is already defined, the values are or'd
3460     // together, which isn't a bswap (unless it's an or of the same bits).
3461     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3462       return true;
3463     ByteValues[DestNo] = I->getOperand(0);
3464     return false;
3465   }
3466   
3467   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3468   // don't have this.
3469   Value *Shift = 0, *ShiftLHS = 0;
3470   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3471   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3472       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3473     return true;
3474   Instruction *SI = cast<Instruction>(Shift);
3475
3476   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3477   if (ShiftAmt->getZExtValue() & 7 ||
3478       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3479     return true;
3480   
3481   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3482   unsigned DestByte;
3483   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3484     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3485       break;
3486   // Unknown mask for bswap.
3487   if (DestByte == ByteValues.size()) return true;
3488   
3489   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3490   unsigned SrcByte;
3491   if (SI->getOpcode() == Instruction::Shl)
3492     SrcByte = DestByte - ShiftBytes;
3493   else
3494     SrcByte = DestByte + ShiftBytes;
3495   
3496   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3497   if (SrcByte != ByteValues.size()-DestByte-1)
3498     return true;
3499   
3500   // If the destination byte value is already defined, the values are or'd
3501   // together, which isn't a bswap (unless it's an or of the same bits).
3502   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3503     return true;
3504   ByteValues[DestByte] = SI->getOperand(0);
3505   return false;
3506 }
3507
3508 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3509 /// If so, insert the new bswap intrinsic and return it.
3510 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3511   // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3512   if (I.getType() == Type::Int8Ty)
3513     return 0;
3514   
3515   /// ByteValues - For each byte of the result, we keep track of which value
3516   /// defines each byte.
3517   std::vector<Value*> ByteValues;
3518   ByteValues.resize(TD->getTypeSize(I.getType()));
3519     
3520   // Try to find all the pieces corresponding to the bswap.
3521   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3522       CollectBSwapParts(I.getOperand(1), ByteValues))
3523     return 0;
3524   
3525   // Check to see if all of the bytes come from the same value.
3526   Value *V = ByteValues[0];
3527   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3528   
3529   // Check to make sure that all of the bytes come from the same value.
3530   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3531     if (ByteValues[i] != V)
3532       return 0;
3533     
3534   // If they do then *success* we can turn this into a bswap.  Figure out what
3535   // bswap to make it into.
3536   Module *M = I.getParent()->getParent()->getParent();
3537   const char *FnName = 0;
3538   if (I.getType() == Type::Int16Ty)
3539     FnName = "llvm.bswap.i16";
3540   else if (I.getType() == Type::Int32Ty)
3541     FnName = "llvm.bswap.i32";
3542   else if (I.getType() == Type::Int64Ty)
3543     FnName = "llvm.bswap.i64";
3544   else
3545     assert(0 && "Unknown integer type!");
3546   Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3547   return new CallInst(F, V);
3548 }
3549
3550
3551 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3552   bool Changed = SimplifyCommutative(I);
3553   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3554
3555   if (isa<UndefValue>(Op1))
3556     return ReplaceInstUsesWith(I,                         // X | undef -> -1
3557                                ConstantInt::getAllOnesValue(I.getType()));
3558
3559   // or X, X = X
3560   if (Op0 == Op1)
3561     return ReplaceInstUsesWith(I, Op0);
3562
3563   // See if we can simplify any instructions used by the instruction whose sole 
3564   // purpose is to compute bits we don't care about.
3565   uint64_t KnownZero, KnownOne;
3566   if (!isa<PackedType>(I.getType()) &&
3567       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3568                            KnownZero, KnownOne))
3569     return &I;
3570   
3571   // or X, -1 == -1
3572   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3573     ConstantInt *C1 = 0; Value *X = 0;
3574     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3575     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3576       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3577       Op0->setName("");
3578       InsertNewInstBefore(Or, I);
3579       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3580     }
3581
3582     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3583     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3584       std::string Op0Name = Op0->getName(); Op0->setName("");
3585       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3586       InsertNewInstBefore(Or, I);
3587       return BinaryOperator::createXor(Or,
3588                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3589     }
3590
3591     // Try to fold constant and into select arguments.
3592     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3593       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3594         return R;
3595     if (isa<PHINode>(Op0))
3596       if (Instruction *NV = FoldOpIntoPhi(I))
3597         return NV;
3598   }
3599
3600   Value *A = 0, *B = 0;
3601   ConstantInt *C1 = 0, *C2 = 0;
3602
3603   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3604     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3605       return ReplaceInstUsesWith(I, Op1);
3606   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3607     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3608       return ReplaceInstUsesWith(I, Op0);
3609
3610   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3611   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3612   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3613       match(Op1, m_Or(m_Value(), m_Value())) ||
3614       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3615        match(Op1, m_Shift(m_Value(), m_Value())))) {
3616     if (Instruction *BSwap = MatchBSwap(I))
3617       return BSwap;
3618   }
3619   
3620   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3621   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3622       MaskedValueIsZero(Op1, C1->getZExtValue())) {
3623     Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3624     Op0->setName("");
3625     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3626   }
3627
3628   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3629   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3630       MaskedValueIsZero(Op0, C1->getZExtValue())) {
3631     Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3632     Op0->setName("");
3633     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3634   }
3635
3636   // (A & C1)|(B & C2)
3637   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3638       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3639
3640     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3641       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3642
3643
3644     // If we have: ((V + N) & C1) | (V & C2)
3645     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3646     // replace with V+N.
3647     if (C1 == ConstantExpr::getNot(C2)) {
3648       Value *V1 = 0, *V2 = 0;
3649       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3650           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3651         // Add commutes, try both ways.
3652         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3653           return ReplaceInstUsesWith(I, A);
3654         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3655           return ReplaceInstUsesWith(I, A);
3656       }
3657       // Or commutes, try both ways.
3658       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3659           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3660         // Add commutes, try both ways.
3661         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3662           return ReplaceInstUsesWith(I, B);
3663         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3664           return ReplaceInstUsesWith(I, B);
3665       }
3666     }
3667   }
3668   
3669   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3670   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3671     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3672       if (SI0->getOpcode() == SI1->getOpcode() && 
3673           SI0->getOperand(1) == SI1->getOperand(1) &&
3674           (SI0->hasOneUse() || SI1->hasOneUse())) {
3675         Instruction *NewOp =
3676         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3677                                                      SI1->getOperand(0),
3678                                                      SI0->getName()), I);
3679         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3680       }
3681   }
3682
3683   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3684     if (A == Op1)   // ~A | A == -1
3685       return ReplaceInstUsesWith(I,
3686                                 ConstantInt::getAllOnesValue(I.getType()));
3687   } else {
3688     A = 0;
3689   }
3690   // Note, A is still live here!
3691   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3692     if (Op0 == B)
3693       return ReplaceInstUsesWith(I,
3694                                 ConstantInt::getAllOnesValue(I.getType()));
3695
3696     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3697     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3698       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3699                                               I.getName()+".demorgan"), I);
3700       return BinaryOperator::createNot(And);
3701     }
3702   }
3703
3704   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3705   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3706     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3707       return R;
3708
3709     Value *LHSVal, *RHSVal;
3710     ConstantInt *LHSCst, *RHSCst;
3711     ICmpInst::Predicate LHSCC, RHSCC;
3712     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3713       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3714         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
3715             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3716             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3717             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3718             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3719             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3720           // Ensure that the larger constant is on the RHS.
3721           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3722             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3723           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3724           ICmpInst *LHS = cast<ICmpInst>(Op0);
3725           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3726             std::swap(LHS, RHS);
3727             std::swap(LHSCst, RHSCst);
3728             std::swap(LHSCC, RHSCC);
3729           }
3730
3731           // At this point, we know we have have two icmp instructions
3732           // comparing a value against two constants and or'ing the result
3733           // together.  Because of the above check, we know that we only have
3734           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3735           // FoldICmpLogical check above), that the two constants are not
3736           // equal.
3737           assert(LHSCst != RHSCst && "Compares not folded above?");
3738
3739           switch (LHSCC) {
3740           default: assert(0 && "Unknown integer condition code!");
3741           case ICmpInst::ICMP_EQ:
3742             switch (RHSCC) {
3743             default: assert(0 && "Unknown integer condition code!");
3744             case ICmpInst::ICMP_EQ:
3745               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3746                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3747                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3748                                                       LHSVal->getName()+".off");
3749                 InsertNewInstBefore(Add, I);
3750                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3751                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3752               }
3753               break;                         // (X == 13 | X == 15) -> no change
3754             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
3755             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
3756               break;
3757             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
3758             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
3759             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
3760               return ReplaceInstUsesWith(I, RHS);
3761             }
3762             break;
3763           case ICmpInst::ICMP_NE:
3764             switch (RHSCC) {
3765             default: assert(0 && "Unknown integer condition code!");
3766             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
3767             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
3768             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
3769               return ReplaceInstUsesWith(I, LHS);
3770             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
3771             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
3772             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
3773               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3774             }
3775             break;
3776           case ICmpInst::ICMP_ULT:
3777             switch (RHSCC) {
3778             default: assert(0 && "Unknown integer condition code!");
3779             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
3780               break;
3781             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
3782               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
3783                                      false, I);
3784             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
3785               break;
3786             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
3787             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
3788               return ReplaceInstUsesWith(I, RHS);
3789             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
3790               break;
3791             }
3792             break;
3793           case ICmpInst::ICMP_SLT:
3794             switch (RHSCC) {
3795             default: assert(0 && "Unknown integer condition code!");
3796             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
3797               break;
3798             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
3799               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
3800                                      false, I);
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) -> X != 15
3804             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
3805               return ReplaceInstUsesWith(I, RHS);
3806             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
3807               break;
3808             }
3809             break;
3810           case ICmpInst::ICMP_UGT:
3811             switch (RHSCC) {
3812             default: assert(0 && "Unknown integer condition code!");
3813             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
3814             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
3815               return ReplaceInstUsesWith(I, LHS);
3816             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
3817               break;
3818             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
3819             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
3820               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3821             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
3822               break;
3823             }
3824             break;
3825           case ICmpInst::ICMP_SGT:
3826             switch (RHSCC) {
3827             default: assert(0 && "Unknown integer condition code!");
3828             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
3829             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
3830               return ReplaceInstUsesWith(I, LHS);
3831             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
3832               break;
3833             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
3834             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
3835               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3836             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
3837               break;
3838             }
3839             break;
3840           }
3841         }
3842   }
3843     
3844   // fold (or (cast A), (cast B)) -> (cast (or A, B))
3845   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3846     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3847       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3848         const Type *SrcTy = Op0C->getOperand(0)->getType();
3849         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3850             // Only do this if the casts both really cause code to be generated.
3851             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3852                               I.getType(), TD) &&
3853             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3854                               I.getType(), TD)) {
3855           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3856                                                         Op1C->getOperand(0),
3857                                                         I.getName());
3858           InsertNewInstBefore(NewOp, I);
3859           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3860         }
3861       }
3862       
3863
3864   return Changed ? &I : 0;
3865 }
3866
3867 // XorSelf - Implements: X ^ X --> 0
3868 struct XorSelf {
3869   Value *RHS;
3870   XorSelf(Value *rhs) : RHS(rhs) {}
3871   bool shouldApply(Value *LHS) const { return LHS == RHS; }
3872   Instruction *apply(BinaryOperator &Xor) const {
3873     return &Xor;
3874   }
3875 };
3876
3877
3878 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3879   bool Changed = SimplifyCommutative(I);
3880   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3881
3882   if (isa<UndefValue>(Op1))
3883     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
3884
3885   // xor X, X = 0, even if X is nested in a sequence of Xor's.
3886   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3887     assert(Result == &I && "AssociativeOpt didn't work?");
3888     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3889   }
3890   
3891   // See if we can simplify any instructions used by the instruction whose sole 
3892   // purpose is to compute bits we don't care about.
3893   uint64_t KnownZero, KnownOne;
3894   if (!isa<PackedType>(I.getType()) &&
3895       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3896                            KnownZero, KnownOne))
3897     return &I;
3898
3899   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3900     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3901     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3902       if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
3903         return new ICmpInst(ICI->getInversePredicate(),
3904                             ICI->getOperand(0), ICI->getOperand(1));
3905
3906     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3907       // ~(c-X) == X-c-1 == X+(-c-1)
3908       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3909         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3910           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3911           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3912                                               ConstantInt::get(I.getType(), 1));
3913           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3914         }
3915
3916       // ~(~X & Y) --> (X | ~Y)
3917       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3918         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3919         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3920           Instruction *NotY =
3921             BinaryOperator::createNot(Op0I->getOperand(1),
3922                                       Op0I->getOperand(1)->getName()+".not");
3923           InsertNewInstBefore(NotY, I);
3924           return BinaryOperator::createOr(Op0NotVal, NotY);
3925         }
3926       }
3927
3928       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3929         if (Op0I->getOpcode() == Instruction::Add) {
3930           // ~(X-c) --> (-c-1)-X
3931           if (RHS->isAllOnesValue()) {
3932             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3933             return BinaryOperator::createSub(
3934                            ConstantExpr::getSub(NegOp0CI,
3935                                              ConstantInt::get(I.getType(), 1)),
3936                                           Op0I->getOperand(0));
3937           }
3938         } else if (Op0I->getOpcode() == Instruction::Or) {
3939           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3940           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3941             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3942             // Anything in both C1 and C2 is known to be zero, remove it from
3943             // NewRHS.
3944             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3945             NewRHS = ConstantExpr::getAnd(NewRHS, 
3946                                           ConstantExpr::getNot(CommonBits));
3947             WorkList.push_back(Op0I);
3948             I.setOperand(0, Op0I->getOperand(0));
3949             I.setOperand(1, NewRHS);
3950             return &I;
3951           }
3952         }
3953     }
3954
3955     // Try to fold constant and into select arguments.
3956     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3957       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3958         return R;
3959     if (isa<PHINode>(Op0))
3960       if (Instruction *NV = FoldOpIntoPhi(I))
3961         return NV;
3962   }
3963
3964   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
3965     if (X == Op1)
3966       return ReplaceInstUsesWith(I,
3967                                 ConstantInt::getAllOnesValue(I.getType()));
3968
3969   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
3970     if (X == Op0)
3971       return ReplaceInstUsesWith(I,
3972                                 ConstantInt::getAllOnesValue(I.getType()));
3973
3974   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3975     if (Op1I->getOpcode() == Instruction::Or) {
3976       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
3977         Op1I->swapOperands();
3978         I.swapOperands();
3979         std::swap(Op0, Op1);
3980       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
3981         I.swapOperands();     // Simplified below.
3982         std::swap(Op0, Op1);
3983       }
3984     } else if (Op1I->getOpcode() == Instruction::Xor) {
3985       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
3986         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3987       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
3988         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3989     } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3990       if (Op1I->getOperand(0) == Op0)                      // A^(A&B) -> A^(B&A)
3991         Op1I->swapOperands();
3992       if (Op0 == Op1I->getOperand(1)) {                    // A^(B&A) -> (B&A)^A
3993         I.swapOperands();     // Simplified below.
3994         std::swap(Op0, Op1);
3995       }
3996     }
3997
3998   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3999     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
4000       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
4001         Op0I->swapOperands();
4002       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
4003         Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4004         InsertNewInstBefore(NotB, I);
4005         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
4006       }
4007     } else if (Op0I->getOpcode() == Instruction::Xor) {
4008       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
4009         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4010       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
4011         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
4012     } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4013       if (Op0I->getOperand(0) == Op1)                      // (A&B)^A -> (B&A)^A
4014         Op0I->swapOperands();
4015       if (Op0I->getOperand(1) == Op1 &&                    // (B&A)^A == ~B & A
4016           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4017         Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4018         InsertNewInstBefore(N, I);
4019         return BinaryOperator::createAnd(N, Op1);
4020       }
4021     }
4022
4023   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4024   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4025     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4026       return R;
4027
4028   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4029   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4030     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4031       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4032         const Type *SrcTy = Op0C->getOperand(0)->getType();
4033         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
4034             // Only do this if the casts both really cause code to be generated.
4035             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4036                               I.getType(), TD) &&
4037             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4038                               I.getType(), TD)) {
4039           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4040                                                          Op1C->getOperand(0),
4041                                                          I.getName());
4042           InsertNewInstBefore(NewOp, I);
4043           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4044         }
4045       }
4046
4047   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4048   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4049     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4050       if (SI0->getOpcode() == SI1->getOpcode() && 
4051           SI0->getOperand(1) == SI1->getOperand(1) &&
4052           (SI0->hasOneUse() || SI1->hasOneUse())) {
4053         Instruction *NewOp =
4054         InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4055                                                       SI1->getOperand(0),
4056                                                       SI0->getName()), I);
4057         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4058       }
4059   }
4060     
4061   return Changed ? &I : 0;
4062 }
4063
4064 static bool isPositive(ConstantInt *C) {
4065   return C->getSExtValue() >= 0;
4066 }
4067
4068 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4069 /// overflowed for this type.
4070 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4071                             ConstantInt *In2) {
4072   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4073
4074   return cast<ConstantInt>(Result)->getZExtValue() <
4075          cast<ConstantInt>(In1)->getZExtValue();
4076 }
4077
4078 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4079 /// code necessary to compute the offset from the base pointer (without adding
4080 /// in the base pointer).  Return the result as a signed integer of intptr size.
4081 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4082   TargetData &TD = IC.getTargetData();
4083   gep_type_iterator GTI = gep_type_begin(GEP);
4084   const Type *IntPtrTy = TD.getIntPtrType();
4085   Value *Result = Constant::getNullValue(IntPtrTy);
4086
4087   // Build a mask for high order bits.
4088   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4089
4090   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4091     Value *Op = GEP->getOperand(i);
4092     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4093     Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4094     if (Constant *OpC = dyn_cast<Constant>(Op)) {
4095       if (!OpC->isNullValue()) {
4096         OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4097         Scale = ConstantExpr::getMul(OpC, Scale);
4098         if (Constant *RC = dyn_cast<Constant>(Result))
4099           Result = ConstantExpr::getAdd(RC, Scale);
4100         else {
4101           // Emit an add instruction.
4102           Result = IC.InsertNewInstBefore(
4103              BinaryOperator::createAdd(Result, Scale,
4104                                        GEP->getName()+".offs"), I);
4105         }
4106       }
4107     } else {
4108       // Convert to correct type.
4109       Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4110                                                Op->getName()+".c"), I);
4111       if (Size != 1)
4112         // We'll let instcombine(mul) convert this to a shl if possible.
4113         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4114                                                     GEP->getName()+".idx"), I);
4115
4116       // Emit an add instruction.
4117       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4118                                                     GEP->getName()+".offs"), I);
4119     }
4120   }
4121   return Result;
4122 }
4123
4124 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4125 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4126 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4127                                        ICmpInst::Predicate Cond,
4128                                        Instruction &I) {
4129   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4130
4131   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4132     if (isa<PointerType>(CI->getOperand(0)->getType()))
4133       RHS = CI->getOperand(0);
4134
4135   Value *PtrBase = GEPLHS->getOperand(0);
4136   if (PtrBase == RHS) {
4137     // As an optimization, we don't actually have to compute the actual value of
4138     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4139     // each index is zero or not.
4140     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4141       Instruction *InVal = 0;
4142       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4143       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4144         bool EmitIt = true;
4145         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4146           if (isa<UndefValue>(C))  // undef index -> undef.
4147             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4148           if (C->isNullValue())
4149             EmitIt = false;
4150           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4151             EmitIt = false;  // This is indexing into a zero sized array?
4152           } else if (isa<ConstantInt>(C))
4153             return ReplaceInstUsesWith(I, // No comparison is needed here.
4154                                  ConstantInt::get(Type::Int1Ty, 
4155                                                   Cond == ICmpInst::ICMP_NE));
4156         }
4157
4158         if (EmitIt) {
4159           Instruction *Comp =
4160             new ICmpInst(Cond, GEPLHS->getOperand(i),
4161                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4162           if (InVal == 0)
4163             InVal = Comp;
4164           else {
4165             InVal = InsertNewInstBefore(InVal, I);
4166             InsertNewInstBefore(Comp, I);
4167             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4168               InVal = BinaryOperator::createOr(InVal, Comp);
4169             else                              // True if all are equal
4170               InVal = BinaryOperator::createAnd(InVal, Comp);
4171           }
4172         }
4173       }
4174
4175       if (InVal)
4176         return InVal;
4177       else
4178         // No comparison is needed here, all indexes = 0
4179         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4180                                                 Cond == ICmpInst::ICMP_EQ));
4181     }
4182
4183     // Only lower this if the icmp is the only user of the GEP or if we expect
4184     // the result to fold to a constant!
4185     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4186       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4187       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4188       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4189                           Constant::getNullValue(Offset->getType()));
4190     }
4191   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4192     // If the base pointers are different, but the indices are the same, just
4193     // compare the base pointer.
4194     if (PtrBase != GEPRHS->getOperand(0)) {
4195       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4196       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4197                         GEPRHS->getOperand(0)->getType();
4198       if (IndicesTheSame)
4199         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4200           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4201             IndicesTheSame = false;
4202             break;
4203           }
4204
4205       // If all indices are the same, just compare the base pointers.
4206       if (IndicesTheSame)
4207         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4208                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4209
4210       // Otherwise, the base pointers are different and the indices are
4211       // different, bail out.
4212       return 0;
4213     }
4214
4215     // If one of the GEPs has all zero indices, recurse.
4216     bool AllZeros = true;
4217     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4218       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4219           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4220         AllZeros = false;
4221         break;
4222       }
4223     if (AllZeros)
4224       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4225                           ICmpInst::getSwappedPredicate(Cond), I);
4226
4227     // If the other GEP has all zero indices, recurse.
4228     AllZeros = true;
4229     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4230       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4231           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4232         AllZeros = false;
4233         break;
4234       }
4235     if (AllZeros)
4236       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4237
4238     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4239       // If the GEPs only differ by one index, compare it.
4240       unsigned NumDifferences = 0;  // Keep track of # differences.
4241       unsigned DiffOperand = 0;     // The operand that differs.
4242       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4243         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4244           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4245                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4246             // Irreconcilable differences.
4247             NumDifferences = 2;
4248             break;
4249           } else {
4250             if (NumDifferences++) break;
4251             DiffOperand = i;
4252           }
4253         }
4254
4255       if (NumDifferences == 0)   // SAME GEP?
4256         return ReplaceInstUsesWith(I, // No comparison is needed here.
4257                                    ConstantInt::get(Type::Int1Ty, 
4258                                                     Cond == ICmpInst::ICMP_EQ));
4259       else if (NumDifferences == 1) {
4260         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4261         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4262         // Make sure we do a signed comparison here.
4263         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4264       }
4265     }
4266
4267     // Only lower this if the icmp is the only user of the GEP or if we expect
4268     // the result to fold to a constant!
4269     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4270         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4271       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4272       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4273       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4274       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4275     }
4276   }
4277   return 0;
4278 }
4279
4280 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4281   bool Changed = SimplifyCompare(I);
4282   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4283
4284   // fcmp pred X, X
4285   if (Op0 == Op1)
4286     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4287                                                    isTrueWhenEqual(I)));
4288
4289   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4290     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4291
4292   // Handle fcmp with constant RHS
4293   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4294     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4295       switch (LHSI->getOpcode()) {
4296       case Instruction::PHI:
4297         if (Instruction *NV = FoldOpIntoPhi(I))
4298           return NV;
4299         break;
4300       case Instruction::Select:
4301         // If either operand of the select is a constant, we can fold the
4302         // comparison into the select arms, which will cause one to be
4303         // constant folded and the select turned into a bitwise or.
4304         Value *Op1 = 0, *Op2 = 0;
4305         if (LHSI->hasOneUse()) {
4306           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4307             // Fold the known value into the constant operand.
4308             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4309             // Insert a new FCmp of the other select operand.
4310             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4311                                                       LHSI->getOperand(2), RHSC,
4312                                                       I.getName()), I);
4313           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4314             // Fold the known value into the constant operand.
4315             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4316             // Insert a new FCmp of the other select operand.
4317             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4318                                                       LHSI->getOperand(1), RHSC,
4319                                                       I.getName()), I);
4320           }
4321         }
4322
4323         if (Op1)
4324           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4325         break;
4326       }
4327   }
4328
4329   return Changed ? &I : 0;
4330 }
4331
4332 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4333   bool Changed = SimplifyCompare(I);
4334   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4335   const Type *Ty = Op0->getType();
4336
4337   // icmp X, X
4338   if (Op0 == Op1)
4339     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4340                                                    isTrueWhenEqual(I)));
4341
4342   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4343     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4344
4345   // icmp of GlobalValues can never equal each other as long as they aren't
4346   // external weak linkage type.
4347   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4348     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4349       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4350         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4351                                                        !isTrueWhenEqual(I)));
4352
4353   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4354   // addresses never equal each other!  We already know that Op0 != Op1.
4355   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4356        isa<ConstantPointerNull>(Op0)) &&
4357       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4358        isa<ConstantPointerNull>(Op1)))
4359     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4360                                                    !isTrueWhenEqual(I)));
4361
4362   // icmp's with boolean values can always be turned into bitwise operations
4363   if (Ty == Type::Int1Ty) {
4364     switch (I.getPredicate()) {
4365     default: assert(0 && "Invalid icmp instruction!");
4366     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4367       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4368       InsertNewInstBefore(Xor, I);
4369       return BinaryOperator::createNot(Xor);
4370     }
4371     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4372       return BinaryOperator::createXor(Op0, Op1);
4373
4374     case ICmpInst::ICMP_UGT:
4375     case ICmpInst::ICMP_SGT:
4376       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4377       // FALL THROUGH
4378     case ICmpInst::ICMP_ULT:
4379     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4380       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4381       InsertNewInstBefore(Not, I);
4382       return BinaryOperator::createAnd(Not, Op1);
4383     }
4384     case ICmpInst::ICMP_UGE:
4385     case ICmpInst::ICMP_SGE:
4386       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4387       // FALL THROUGH
4388     case ICmpInst::ICMP_ULE:
4389     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4390       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4391       InsertNewInstBefore(Not, I);
4392       return BinaryOperator::createOr(Not, Op1);
4393     }
4394     }
4395   }
4396
4397   // See if we are doing a comparison between a constant and an instruction that
4398   // can be folded into the comparison.
4399   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4400     switch (I.getPredicate()) {
4401     default: break;
4402     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4403       if (CI->isMinValue(false))
4404         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4405       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4406         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4407       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4408         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4409       break;
4410
4411     case ICmpInst::ICMP_SLT:
4412       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4413         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4414       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4415         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4416       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4417         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4418       break;
4419
4420     case ICmpInst::ICMP_UGT:
4421       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4422         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4423       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4424         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4425       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4426         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4427       break;
4428
4429     case ICmpInst::ICMP_SGT:
4430       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4431         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4432       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4433         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4434       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4435         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4436       break;
4437
4438     case ICmpInst::ICMP_ULE:
4439       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4440         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4441       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4442         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4443       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4444         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4445       break;
4446
4447     case ICmpInst::ICMP_SLE:
4448       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4449         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4450       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4451         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4452       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4453         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4454       break;
4455
4456     case ICmpInst::ICMP_UGE:
4457       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4458         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4459       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4460         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4461       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4462         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4463       break;
4464
4465     case ICmpInst::ICMP_SGE:
4466       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4467         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4468       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4469         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4470       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4471         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4472       break;
4473     }
4474
4475     // If we still have a icmp le or icmp ge instruction, turn it into the
4476     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4477     // already been handled above, this requires little checking.
4478     //
4479     if (I.getPredicate() == ICmpInst::ICMP_ULE)
4480       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4481     if (I.getPredicate() == ICmpInst::ICMP_SLE)
4482       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4483     if (I.getPredicate() == ICmpInst::ICMP_UGE)
4484       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4485     if (I.getPredicate() == ICmpInst::ICMP_SGE)
4486       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4487     
4488     // See if we can fold the comparison based on bits known to be zero or one
4489     // in the input.
4490     uint64_t KnownZero, KnownOne;
4491     if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4492                              KnownZero, KnownOne, 0))
4493       return &I;
4494         
4495     // Given the known and unknown bits, compute a range that the LHS could be
4496     // in.
4497     if (KnownOne | KnownZero) {
4498       // Compute the Min, Max and RHS values based on the known bits. For the
4499       // EQ and NE we use unsigned values.
4500       uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4501       int64_t SMin = 0, SMax = 0, SRHSVal = 0;
4502       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4503         SRHSVal = CI->getSExtValue();
4504         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin, 
4505                                                SMax);
4506       } else {
4507         URHSVal = CI->getZExtValue();
4508         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin, 
4509                                                  UMax);
4510       }
4511       switch (I.getPredicate()) {  // LE/GE have been folded already.
4512       default: assert(0 && "Unknown icmp opcode!");
4513       case ICmpInst::ICMP_EQ:
4514         if (UMax < URHSVal || UMin > URHSVal)
4515           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4516         break;
4517       case ICmpInst::ICMP_NE:
4518         if (UMax < URHSVal || UMin > URHSVal)
4519           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4520         break;
4521       case ICmpInst::ICMP_ULT:
4522         if (UMax < URHSVal)
4523           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4524         if (UMin > URHSVal)
4525           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4526         break;
4527       case ICmpInst::ICMP_UGT:
4528         if (UMin > URHSVal)
4529           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4530         if (UMax < URHSVal)
4531           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4532         break;
4533       case ICmpInst::ICMP_SLT:
4534         if (SMax < SRHSVal)
4535           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4536         if (SMin > SRHSVal)
4537           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4538         break;
4539       case ICmpInst::ICMP_SGT: 
4540         if (SMin > SRHSVal)
4541           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4542         if (SMax < SRHSVal)
4543           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4544         break;
4545       }
4546     }
4547           
4548     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
4549     // instruction, see if that instruction also has constants so that the 
4550     // instruction can be folded into the icmp 
4551     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4552       switch (LHSI->getOpcode()) {
4553       case Instruction::And:
4554         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4555             LHSI->getOperand(0)->hasOneUse()) {
4556           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4557
4558           // If the LHS is an AND of a truncating cast, we can widen the
4559           // and/compare to be the input width without changing the value
4560           // produced, eliminating a cast.
4561           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4562             // We can do this transformation if either the AND constant does not
4563             // have its sign bit set or if it is an equality comparison. 
4564             // Extending a relational comparison when we're checking the sign
4565             // bit would not work.
4566             if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4567                 (I.isEquality() ||
4568                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4569                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4570               ConstantInt *NewCST;
4571               ConstantInt *NewCI;
4572               NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4573                                          AndCST->getZExtValue());
4574               NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4575                                         CI->getZExtValue());
4576               Instruction *NewAnd = 
4577                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4578                                           LHSI->getName());
4579               InsertNewInstBefore(NewAnd, I);
4580               return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
4581             }
4582           }
4583           
4584           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4585           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4586           // happens a LOT in code produced by the C front-end, for bitfield
4587           // access.
4588           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4589
4590           // Check to see if there is a noop-cast between the shift and the and.
4591           if (!Shift) {
4592             if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4593               if (CI->getOpcode() == Instruction::BitCast)
4594                 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4595           }
4596
4597           ConstantInt *ShAmt;
4598           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4599           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4600           const Type *AndTy = AndCST->getType();          // Type of the and.
4601
4602           // We can fold this as long as we can't shift unknown bits
4603           // into the mask.  This can only happen with signed shift
4604           // rights, as they sign-extend.
4605           if (ShAmt) {
4606             bool CanFold = Shift->isLogicalShift();
4607             if (!CanFold) {
4608               // To test for the bad case of the signed shr, see if any
4609               // of the bits shifted in could be tested after the mask.
4610               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4611               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4612
4613               Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
4614               Constant *ShVal =
4615                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4616                                      OShAmt);
4617               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4618                 CanFold = true;
4619             }
4620
4621             if (CanFold) {
4622               Constant *NewCst;
4623               if (Shift->getOpcode() == Instruction::Shl)
4624                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4625               else
4626                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4627
4628               // Check to see if we are shifting out any of the bits being
4629               // compared.
4630               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4631                 // If we shifted bits out, the fold is not going to work out.
4632                 // As a special case, check to see if this means that the
4633                 // result is always true or false now.
4634                 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4635                   return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4636                 if (I.getPredicate() == ICmpInst::ICMP_NE)
4637                   return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4638               } else {
4639                 I.setOperand(1, NewCst);
4640                 Constant *NewAndCST;
4641                 if (Shift->getOpcode() == Instruction::Shl)
4642                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4643                 else
4644                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4645                 LHSI->setOperand(1, NewAndCST);
4646                 LHSI->setOperand(0, Shift->getOperand(0));
4647                 WorkList.push_back(Shift); // Shift is dead.
4648                 AddUsesToWorkList(I);
4649                 return &I;
4650               }
4651             }
4652           }
4653           
4654           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4655           // preferable because it allows the C<<Y expression to be hoisted out
4656           // of a loop if Y is invariant and X is not.
4657           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4658               I.isEquality() && !Shift->isArithmeticShift() &&
4659               isa<Instruction>(Shift->getOperand(0))) {
4660             // Compute C << Y.
4661             Value *NS;
4662             if (Shift->getOpcode() == Instruction::LShr) {
4663               NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4664                                  "tmp");
4665             } else {
4666               // Insert a logical shift.
4667               NS = new ShiftInst(Instruction::LShr, AndCST,
4668                                  Shift->getOperand(1), "tmp");
4669             }
4670             InsertNewInstBefore(cast<Instruction>(NS), I);
4671
4672             // Compute X & (C << Y).
4673             Instruction *NewAnd = BinaryOperator::createAnd(
4674                 Shift->getOperand(0), NS, LHSI->getName());
4675             InsertNewInstBefore(NewAnd, I);
4676             
4677             I.setOperand(0, NewAnd);
4678             return &I;
4679           }
4680         }
4681         break;
4682
4683       case Instruction::Shl:         // (icmp pred (shl X, ShAmt), CI)
4684         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4685           if (I.isEquality()) {
4686             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4687
4688             // Check that the shift amount is in range.  If not, don't perform
4689             // undefined shifts.  When the shift is visited it will be
4690             // simplified.
4691             if (ShAmt->getZExtValue() >= TypeBits)
4692               break;
4693
4694             // If we are comparing against bits always shifted out, the
4695             // comparison cannot succeed.
4696             Constant *Comp =
4697               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4698             if (Comp != CI) {// Comparing against a bit that we know is zero.
4699               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4700               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4701               return ReplaceInstUsesWith(I, Cst);
4702             }
4703
4704             if (LHSI->hasOneUse()) {
4705               // Otherwise strength reduce the shift into an and.
4706               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4707               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4708               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4709
4710               Instruction *AndI =
4711                 BinaryOperator::createAnd(LHSI->getOperand(0),
4712                                           Mask, LHSI->getName()+".mask");
4713               Value *And = InsertNewInstBefore(AndI, I);
4714               return new ICmpInst(I.getPredicate(), And,
4715                                      ConstantExpr::getLShr(CI, ShAmt));
4716             }
4717           }
4718         }
4719         break;
4720
4721       case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
4722       case Instruction::AShr:
4723         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4724           if (I.isEquality()) {
4725             // Check that the shift amount is in range.  If not, don't perform
4726             // undefined shifts.  When the shift is visited it will be
4727             // simplified.
4728             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4729             if (ShAmt->getZExtValue() >= TypeBits)
4730               break;
4731
4732             // If we are comparing against bits always shifted out, the
4733             // comparison cannot succeed.
4734             Constant *Comp;
4735             if (LHSI->getOpcode() == Instruction::LShr) 
4736               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
4737                                            ShAmt);
4738             else
4739               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
4740                                            ShAmt);
4741
4742             if (Comp != CI) {// Comparing against a bit that we know is zero.
4743               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4744               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4745               return ReplaceInstUsesWith(I, Cst);
4746             }
4747
4748             if (LHSI->hasOneUse() || CI->isNullValue()) {
4749               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4750
4751               // Otherwise strength reduce the shift into an and.
4752               uint64_t Val = ~0ULL;          // All ones.
4753               Val <<= ShAmtVal;              // Shift over to the right spot.
4754               Val &= ~0ULL >> (64-TypeBits);
4755               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4756
4757               Instruction *AndI =
4758                 BinaryOperator::createAnd(LHSI->getOperand(0),
4759                                           Mask, LHSI->getName()+".mask");
4760               Value *And = InsertNewInstBefore(AndI, I);
4761               return new ICmpInst(I.getPredicate(), And,
4762                                      ConstantExpr::getShl(CI, ShAmt));
4763             }
4764           }
4765         }
4766         break;
4767
4768       case Instruction::SDiv:
4769       case Instruction::UDiv:
4770         // Fold: icmp pred ([us]div X, C1), C2 -> range test
4771         // Fold this div into the comparison, producing a range check. 
4772         // Determine, based on the divide type, what the range is being 
4773         // checked.  If there is an overflow on the low or high side, remember 
4774         // it, otherwise compute the range [low, hi) bounding the new value.
4775         // See: InsertRangeTest above for the kinds of replacements possible.
4776         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4777           // FIXME: If the operand types don't match the type of the divide 
4778           // then don't attempt this transform. The code below doesn't have the
4779           // logic to deal with a signed divide and an unsigned compare (and
4780           // vice versa). This is because (x /s C1) <s C2  produces different 
4781           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4782           // (x /u C1) <u C2.  Simply casting the operands and result won't 
4783           // work. :(  The if statement below tests that condition and bails 
4784           // if it finds it. 
4785           bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4786           if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
4787             break;
4788
4789           // Initialize the variables that will indicate the nature of the
4790           // range check.
4791           bool LoOverflow = false, HiOverflow = false;
4792           ConstantInt *LoBound = 0, *HiBound = 0;
4793
4794           // Compute Prod = CI * DivRHS. We are essentially solving an equation
4795           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
4796           // C2 (CI). By solving for X we can turn this into a range check 
4797           // instead of computing a divide. 
4798           ConstantInt *Prod = 
4799             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4800
4801           // Determine if the product overflows by seeing if the product is
4802           // not equal to the divide. Make sure we do the same kind of divide
4803           // as in the LHS instruction that we're folding. 
4804           bool ProdOV = !DivRHS->isNullValue() && 
4805             (DivIsSigned ?  ConstantExpr::getSDiv(Prod, DivRHS) :
4806               ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4807
4808           // Get the ICmp opcode
4809           ICmpInst::Predicate predicate = I.getPredicate();
4810
4811           if (DivRHS->isNullValue()) {  
4812             // Don't hack on divide by zeros!
4813           } else if (!DivIsSigned) {  // udiv
4814             LoBound = Prod;
4815             LoOverflow = ProdOV;
4816             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4817           } else if (isPositive(DivRHS)) { // Divisor is > 0.
4818             if (CI->isNullValue()) {       // (X / pos) op 0
4819               // Can't overflow.
4820               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4821               HiBound = DivRHS;
4822             } else if (isPositive(CI)) {   // (X / pos) op pos
4823               LoBound = Prod;
4824               LoOverflow = ProdOV;
4825               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4826             } else {                       // (X / pos) op neg
4827               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4828               LoOverflow = AddWithOverflow(LoBound, Prod,
4829                                            cast<ConstantInt>(DivRHSH));
4830               HiBound = Prod;
4831               HiOverflow = ProdOV;
4832             }
4833           } else {                         // Divisor is < 0.
4834             if (CI->isNullValue()) {       // (X / neg) op 0
4835               LoBound = AddOne(DivRHS);
4836               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4837               if (HiBound == DivRHS)
4838                 LoBound = 0;               // - INTMIN = INTMIN
4839             } else if (isPositive(CI)) {   // (X / neg) op pos
4840               HiOverflow = LoOverflow = ProdOV;
4841               if (!LoOverflow)
4842                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4843               HiBound = AddOne(Prod);
4844             } else {                       // (X / neg) op neg
4845               LoBound = Prod;
4846               LoOverflow = HiOverflow = ProdOV;
4847               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4848             }
4849
4850             // Dividing by a negate swaps the condition.
4851             predicate = ICmpInst::getSwappedPredicate(predicate);
4852           }
4853
4854           if (LoBound) {
4855             Value *X = LHSI->getOperand(0);
4856             switch (predicate) {
4857             default: assert(0 && "Unhandled icmp opcode!");
4858             case ICmpInst::ICMP_EQ:
4859               if (LoOverflow && HiOverflow)
4860                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4861               else if (HiOverflow)
4862                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SGE : 
4863                                     ICmpInst::ICMP_UGE, X, LoBound);
4864               else if (LoOverflow)
4865                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
4866                                     ICmpInst::ICMP_ULT, X, HiBound);
4867               else
4868                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4869                                        true, I);
4870             case ICmpInst::ICMP_NE:
4871               if (LoOverflow && HiOverflow)
4872                 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4873               else if (HiOverflow)
4874                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SLT : 
4875                                     ICmpInst::ICMP_ULT, X, LoBound);
4876               else if (LoOverflow)
4877                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
4878                                     ICmpInst::ICMP_UGE, X, HiBound);
4879               else
4880                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4881                                        false, I);
4882             case ICmpInst::ICMP_ULT:
4883             case ICmpInst::ICMP_SLT:
4884               if (LoOverflow)
4885                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4886               return new ICmpInst(predicate, X, LoBound);
4887             case ICmpInst::ICMP_UGT:
4888             case ICmpInst::ICMP_SGT:
4889               if (HiOverflow)
4890                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4891               if (predicate == ICmpInst::ICMP_UGT)
4892                 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4893               else
4894                 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
4895             }
4896           }
4897         }
4898         break;
4899       }
4900
4901     // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
4902     if (I.isEquality()) {
4903       bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4904
4905       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
4906       // the second operand is a constant, simplify a bit.
4907       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4908         switch (BO->getOpcode()) {
4909         case Instruction::SRem:
4910           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4911           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4912               BO->hasOneUse()) {
4913             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4914             if (V > 1 && isPowerOf2_64(V)) {
4915               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4916                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4917               return new ICmpInst(I.getPredicate(), NewRem, 
4918                                   Constant::getNullValue(BO->getType()));
4919             }
4920           }
4921           break;
4922         case Instruction::Add:
4923           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4924           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4925             if (BO->hasOneUse())
4926               return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4927                                   ConstantExpr::getSub(CI, BOp1C));
4928           } else if (CI->isNullValue()) {
4929             // Replace ((add A, B) != 0) with (A != -B) if A or B is
4930             // efficiently invertible, or if the add has just this one use.
4931             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4932
4933             if (Value *NegVal = dyn_castNegVal(BOp1))
4934               return new ICmpInst(I.getPredicate(), BOp0, NegVal);
4935             else if (Value *NegVal = dyn_castNegVal(BOp0))
4936               return new ICmpInst(I.getPredicate(), NegVal, BOp1);
4937             else if (BO->hasOneUse()) {
4938               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4939               BO->setName("");
4940               InsertNewInstBefore(Neg, I);
4941               return new ICmpInst(I.getPredicate(), BOp0, Neg);
4942             }
4943           }
4944           break;
4945         case Instruction::Xor:
4946           // For the xor case, we can xor two constants together, eliminating
4947           // the explicit xor.
4948           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4949             return new ICmpInst(I.getPredicate(), BO->getOperand(0), 
4950                                 ConstantExpr::getXor(CI, BOC));
4951
4952           // FALLTHROUGH
4953         case Instruction::Sub:
4954           // Replace (([sub|xor] A, B) != 0) with (A != B)
4955           if (CI->isNullValue())
4956             return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4957                                 BO->getOperand(1));
4958           break;
4959
4960         case Instruction::Or:
4961           // If bits are being or'd in that are not present in the constant we
4962           // are comparing against, then the comparison could never succeed!
4963           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4964             Constant *NotCI = ConstantExpr::getNot(CI);
4965             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4966               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4967                                                              isICMP_NE));
4968           }
4969           break;
4970
4971         case Instruction::And:
4972           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4973             // If bits are being compared against that are and'd out, then the
4974             // comparison can never succeed!
4975             if (!ConstantExpr::getAnd(CI,
4976                                       ConstantExpr::getNot(BOC))->isNullValue())
4977               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4978                                                              isICMP_NE));
4979
4980             // If we have ((X & C) == C), turn it into ((X & C) != 0).
4981             if (CI == BOC && isOneBitSet(CI))
4982               return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4983                                   ICmpInst::ICMP_NE, Op0,
4984                                   Constant::getNullValue(CI->getType()));
4985
4986             // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
4987             if (isSignBit(BOC)) {
4988               Value *X = BO->getOperand(0);
4989               Constant *Zero = Constant::getNullValue(X->getType());
4990               ICmpInst::Predicate pred = isICMP_NE ? 
4991                 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
4992               return new ICmpInst(pred, X, Zero);
4993             }
4994
4995             // ((X & ~7) == 0) --> X < 8
4996             if (CI->isNullValue() && isHighOnes(BOC)) {
4997               Value *X = BO->getOperand(0);
4998               Constant *NegX = ConstantExpr::getNeg(BOC);
4999               ICmpInst::Predicate pred = isICMP_NE ? 
5000                 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5001               return new ICmpInst(pred, X, NegX);
5002             }
5003
5004           }
5005         default: break;
5006         }
5007       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5008         // Handle set{eq|ne} <intrinsic>, intcst.
5009         switch (II->getIntrinsicID()) {
5010         default: break;
5011         case Intrinsic::bswap_i16: 
5012           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5013           WorkList.push_back(II);  // Dead?
5014           I.setOperand(0, II->getOperand(1));
5015           I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5016                                            ByteSwap_16(CI->getZExtValue())));
5017           return &I;
5018         case Intrinsic::bswap_i32:   
5019           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5020           WorkList.push_back(II);  // Dead?
5021           I.setOperand(0, II->getOperand(1));
5022           I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5023                                            ByteSwap_32(CI->getZExtValue())));
5024           return &I;
5025         case Intrinsic::bswap_i64:   
5026           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5027           WorkList.push_back(II);  // Dead?
5028           I.setOperand(0, II->getOperand(1));
5029           I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5030                                            ByteSwap_64(CI->getZExtValue())));
5031           return &I;
5032         }
5033       }
5034     } else {  // Not a ICMP_EQ/ICMP_NE
5035       // If the LHS is a cast from an integral value of the same size, then 
5036       // since we know the RHS is a constant, try to simlify.
5037       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5038         Value *CastOp = Cast->getOperand(0);
5039         const Type *SrcTy = CastOp->getType();
5040         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5041         if (SrcTy->isInteger() && 
5042             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5043           // If this is an unsigned comparison, try to make the comparison use
5044           // smaller constant values.
5045           switch (I.getPredicate()) {
5046             default: break;
5047             case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5048               ConstantInt *CUI = cast<ConstantInt>(CI);
5049               if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5050                 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5051                                     ConstantInt::get(SrcTy, -1));
5052               break;
5053             }
5054             case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5055               ConstantInt *CUI = cast<ConstantInt>(CI);
5056               if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5057                 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5058                                     Constant::getNullValue(SrcTy));
5059               break;
5060             }
5061           }
5062
5063         }
5064       }
5065     }
5066   }
5067
5068   // Handle icmp with constant RHS
5069   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5070     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5071       switch (LHSI->getOpcode()) {
5072       case Instruction::GetElementPtr:
5073         if (RHSC->isNullValue()) {
5074           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5075           bool isAllZeros = true;
5076           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5077             if (!isa<Constant>(LHSI->getOperand(i)) ||
5078                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5079               isAllZeros = false;
5080               break;
5081             }
5082           if (isAllZeros)
5083             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5084                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5085         }
5086         break;
5087
5088       case Instruction::PHI:
5089         if (Instruction *NV = FoldOpIntoPhi(I))
5090           return NV;
5091         break;
5092       case Instruction::Select:
5093         // If either operand of the select is a constant, we can fold the
5094         // comparison into the select arms, which will cause one to be
5095         // constant folded and the select turned into a bitwise or.
5096         Value *Op1 = 0, *Op2 = 0;
5097         if (LHSI->hasOneUse()) {
5098           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5099             // Fold the known value into the constant operand.
5100             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5101             // Insert a new ICmp of the other select operand.
5102             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5103                                                    LHSI->getOperand(2), RHSC,
5104                                                    I.getName()), I);
5105           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5106             // Fold the known value into the constant operand.
5107             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5108             // Insert a new ICmp of the other select operand.
5109             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5110                                                    LHSI->getOperand(1), RHSC,
5111                                                    I.getName()), I);
5112           }
5113         }
5114
5115         if (Op1)
5116           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5117         break;
5118       }
5119   }
5120
5121   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5122   if (User *GEP = dyn_castGetElementPtr(Op0))
5123     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5124       return NI;
5125   if (User *GEP = dyn_castGetElementPtr(Op1))
5126     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5127                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5128       return NI;
5129
5130   // Test to see if the operands of the icmp are casted versions of other
5131   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5132   // now.
5133   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5134     if (isa<PointerType>(Op0->getType()) && 
5135         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5136       // We keep moving the cast from the left operand over to the right
5137       // operand, where it can often be eliminated completely.
5138       Op0 = CI->getOperand(0);
5139
5140       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5141       // so eliminate it as well.
5142       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5143         Op1 = CI2->getOperand(0);
5144
5145       // If Op1 is a constant, we can fold the cast into the constant.
5146       if (Op0->getType() != Op1->getType())
5147         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5148           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5149         } else {
5150           // Otherwise, cast the RHS right before the icmp
5151           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5152         }
5153       return new ICmpInst(I.getPredicate(), Op0, Op1);
5154     }
5155   }
5156   
5157   if (isa<CastInst>(Op0)) {
5158     // Handle the special case of: icmp (cast bool to X), <cst>
5159     // This comes up when you have code like
5160     //   int X = A < B;
5161     //   if (X) ...
5162     // For generality, we handle any zero-extension of any operand comparison
5163     // with a constant or another cast from the same type.
5164     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5165       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5166         return R;
5167   }
5168   
5169   if (I.isEquality()) {
5170     Value *A, *B, *C, *D;
5171     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5172       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5173         Value *OtherVal = A == Op1 ? B : A;
5174         return new ICmpInst(I.getPredicate(), OtherVal,
5175                             Constant::getNullValue(A->getType()));
5176       }
5177
5178       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5179         // A^c1 == C^c2 --> A == C^(c1^c2)
5180         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5181           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5182             if (Op1->hasOneUse()) {
5183               Constant *NC = ConstantExpr::getXor(C1, C2);
5184               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5185               return new ICmpInst(I.getPredicate(), A,
5186                                   InsertNewInstBefore(Xor, I));
5187             }
5188         
5189         // A^B == A^D -> B == D
5190         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5191         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5192         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5193         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5194       }
5195     }
5196     
5197     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5198         (A == Op0 || B == Op0)) {
5199       // A == (A^B)  ->  B == 0
5200       Value *OtherVal = A == Op0 ? B : A;
5201       return new ICmpInst(I.getPredicate(), OtherVal,
5202                           Constant::getNullValue(A->getType()));
5203     }
5204     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5205       // (A-B) == A  ->  B == 0
5206       return new ICmpInst(I.getPredicate(), B,
5207                           Constant::getNullValue(B->getType()));
5208     }
5209     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5210       // A == (A-B)  ->  B == 0
5211       return new ICmpInst(I.getPredicate(), B,
5212                           Constant::getNullValue(B->getType()));
5213     }
5214     
5215     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5216     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5217         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5218         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5219       Value *X = 0, *Y = 0, *Z = 0;
5220       
5221       if (A == C) {
5222         X = B; Y = D; Z = A;
5223       } else if (A == D) {
5224         X = B; Y = C; Z = A;
5225       } else if (B == C) {
5226         X = A; Y = D; Z = B;
5227       } else if (B == D) {
5228         X = A; Y = C; Z = B;
5229       }
5230       
5231       if (X) {   // Build (X^Y) & Z
5232         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5233         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5234         I.setOperand(0, Op1);
5235         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5236         return &I;
5237       }
5238     }
5239   }
5240   return Changed ? &I : 0;
5241 }
5242
5243 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5244 // We only handle extending casts so far.
5245 //
5246 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5247   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5248   Value *LHSCIOp        = LHSCI->getOperand(0);
5249   const Type *SrcTy     = LHSCIOp->getType();
5250   const Type *DestTy    = LHSCI->getType();
5251   Value *RHSCIOp;
5252
5253   // We only handle extension cast instructions, so far. Enforce this.
5254   if (LHSCI->getOpcode() != Instruction::ZExt &&
5255       LHSCI->getOpcode() != Instruction::SExt)
5256     return 0;
5257
5258   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5259   bool isSignedCmp = ICI.isSignedPredicate();
5260
5261   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5262     // Not an extension from the same type?
5263     RHSCIOp = CI->getOperand(0);
5264     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5265       return 0;
5266     else
5267       // Okay, just insert a compare of the reduced operands now!
5268       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5269   }
5270
5271   // If we aren't dealing with a constant on the RHS, exit early
5272   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5273   if (!CI)
5274     return 0;
5275
5276   // Compute the constant that would happen if we truncated to SrcTy then
5277   // reextended to DestTy.
5278   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5279   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5280
5281   // If the re-extended constant didn't change...
5282   if (Res2 == CI) {
5283     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5284     // For example, we might have:
5285     //    %A = sext short %X to uint
5286     //    %B = icmp ugt uint %A, 1330
5287     // It is incorrect to transform this into 
5288     //    %B = icmp ugt short %X, 1330 
5289     // because %A may have negative value. 
5290     //
5291     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5292     // OR operation is EQ/NE.
5293     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5294       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5295     else
5296       return 0;
5297   }
5298
5299   // The re-extended constant changed so the constant cannot be represented 
5300   // in the shorter type. Consequently, we cannot emit a simple comparison.
5301
5302   // First, handle some easy cases. We know the result cannot be equal at this
5303   // point so handle the ICI.isEquality() cases
5304   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5305     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5306   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5307     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5308
5309   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5310   // should have been folded away previously and not enter in here.
5311   Value *Result;
5312   if (isSignedCmp) {
5313     // We're performing a signed comparison.
5314     if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5315       Result = ConstantInt::getFalse();          // X < (small) --> false
5316     else
5317       Result = ConstantInt::getTrue();           // X < (large) --> true
5318   } else {
5319     // We're performing an unsigned comparison.
5320     if (isSignedExt) {
5321       // We're performing an unsigned comp with a sign extended value.
5322       // This is true if the input is >= 0. [aka >s -1]
5323       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5324       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5325                                    NegOne, ICI.getName()), ICI);
5326     } else {
5327       // Unsigned extend & unsigned compare -> always true.
5328       Result = ConstantInt::getTrue();
5329     }
5330   }
5331
5332   // Finally, return the value computed.
5333   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5334       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5335     return ReplaceInstUsesWith(ICI, Result);
5336   } else {
5337     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5338             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5339            "ICmp should be folded!");
5340     if (Constant *CI = dyn_cast<Constant>(Result))
5341       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5342     else
5343       return BinaryOperator::createNot(Result);
5344   }
5345 }
5346
5347 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
5348   assert(I.getOperand(1)->getType() == Type::Int8Ty);
5349   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5350
5351   // shl X, 0 == X and shr X, 0 == X
5352   // shl 0, X == 0 and shr 0, X == 0
5353   if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
5354       Op0 == Constant::getNullValue(Op0->getType()))
5355     return ReplaceInstUsesWith(I, Op0);
5356   
5357   if (isa<UndefValue>(Op0)) {            
5358     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5359       return ReplaceInstUsesWith(I, Op0);
5360     else                                    // undef << X -> 0, undef >>u X -> 0
5361       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5362   }
5363   if (isa<UndefValue>(Op1)) {
5364     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5365       return ReplaceInstUsesWith(I, Op0);          
5366     else                                     // X << undef, X >>u undef -> 0
5367       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5368   }
5369
5370   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5371   if (I.getOpcode() == Instruction::AShr)
5372     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5373       if (CSI->isAllOnesValue())
5374         return ReplaceInstUsesWith(I, CSI);
5375
5376   // Try to fold constant and into select arguments.
5377   if (isa<Constant>(Op0))
5378     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5379       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5380         return R;
5381
5382   // See if we can turn a signed shr into an unsigned shr.
5383   if (I.isArithmeticShift()) {
5384     if (MaskedValueIsZero(Op0,
5385                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5386       return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
5387     }
5388   }
5389
5390   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5391     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5392       return Res;
5393   return 0;
5394 }
5395
5396 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5397                                                ShiftInst &I) {
5398   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5399   bool isSignedShift  = I.getOpcode() == Instruction::AShr;
5400   bool isUnsignedShift = !isSignedShift;
5401
5402   // See if we can simplify any instructions used by the instruction whose sole 
5403   // purpose is to compute bits we don't care about.
5404   uint64_t KnownZero, KnownOne;
5405   if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5406                            KnownZero, KnownOne))
5407     return &I;
5408   
5409   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5410   // of a signed value.
5411   //
5412   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5413   if (Op1->getZExtValue() >= TypeBits) {
5414     if (isUnsignedShift || isLeftShift)
5415       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5416     else {
5417       I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
5418       return &I;
5419     }
5420   }
5421   
5422   // ((X*C1) << C2) == (X * (C1 << C2))
5423   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5424     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5425       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5426         return BinaryOperator::createMul(BO->getOperand(0),
5427                                          ConstantExpr::getShl(BOOp, Op1));
5428   
5429   // Try to fold constant and into select arguments.
5430   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5431     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5432       return R;
5433   if (isa<PHINode>(Op0))
5434     if (Instruction *NV = FoldOpIntoPhi(I))
5435       return NV;
5436   
5437   if (Op0->hasOneUse()) {
5438     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5439       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5440       Value *V1, *V2;
5441       ConstantInt *CC;
5442       switch (Op0BO->getOpcode()) {
5443         default: break;
5444         case Instruction::Add:
5445         case Instruction::And:
5446         case Instruction::Or:
5447         case Instruction::Xor:
5448           // These operators commute.
5449           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5450           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5451               match(Op0BO->getOperand(1),
5452                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5453             Instruction *YS = new ShiftInst(Instruction::Shl, 
5454                                             Op0BO->getOperand(0), Op1,
5455                                             Op0BO->getName());
5456             InsertNewInstBefore(YS, I); // (Y << C)
5457             Instruction *X = 
5458               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5459                                      Op0BO->getOperand(1)->getName());
5460             InsertNewInstBefore(X, I);  // (X + (Y << C))
5461             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5462             C2 = ConstantExpr::getShl(C2, Op1);
5463             return BinaryOperator::createAnd(X, C2);
5464           }
5465           
5466           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5467           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5468               match(Op0BO->getOperand(1),
5469                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5470                           m_ConstantInt(CC))) && V2 == Op1 &&
5471       cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5472             Instruction *YS = new ShiftInst(Instruction::Shl, 
5473                                             Op0BO->getOperand(0), Op1,
5474                                             Op0BO->getName());
5475             InsertNewInstBefore(YS, I); // (Y << C)
5476             Instruction *XM =
5477               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5478                                         V1->getName()+".mask");
5479             InsertNewInstBefore(XM, I); // X & (CC << C)
5480             
5481             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5482           }
5483           
5484           // FALL THROUGH.
5485         case Instruction::Sub:
5486           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5487           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5488               match(Op0BO->getOperand(0),
5489                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5490             Instruction *YS = new ShiftInst(Instruction::Shl, 
5491                                             Op0BO->getOperand(1), Op1,
5492                                             Op0BO->getName());
5493             InsertNewInstBefore(YS, I); // (Y << C)
5494             Instruction *X =
5495               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5496                                      Op0BO->getOperand(0)->getName());
5497             InsertNewInstBefore(X, I);  // (X + (Y << C))
5498             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5499             C2 = ConstantExpr::getShl(C2, Op1);
5500             return BinaryOperator::createAnd(X, C2);
5501           }
5502           
5503           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5504           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5505               match(Op0BO->getOperand(0),
5506                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5507                           m_ConstantInt(CC))) && V2 == Op1 &&
5508               cast<BinaryOperator>(Op0BO->getOperand(0))
5509                   ->getOperand(0)->hasOneUse()) {
5510             Instruction *YS = new ShiftInst(Instruction::Shl, 
5511                                             Op0BO->getOperand(1), Op1,
5512                                             Op0BO->getName());
5513             InsertNewInstBefore(YS, I); // (Y << C)
5514             Instruction *XM =
5515               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5516                                         V1->getName()+".mask");
5517             InsertNewInstBefore(XM, I); // X & (CC << C)
5518             
5519             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5520           }
5521           
5522           break;
5523       }
5524       
5525       
5526       // If the operand is an bitwise operator with a constant RHS, and the
5527       // shift is the only use, we can pull it out of the shift.
5528       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5529         bool isValid = true;     // Valid only for And, Or, Xor
5530         bool highBitSet = false; // Transform if high bit of constant set?
5531         
5532         switch (Op0BO->getOpcode()) {
5533           default: isValid = false; break;   // Do not perform transform!
5534           case Instruction::Add:
5535             isValid = isLeftShift;
5536             break;
5537           case Instruction::Or:
5538           case Instruction::Xor:
5539             highBitSet = false;
5540             break;
5541           case Instruction::And:
5542             highBitSet = true;
5543             break;
5544         }
5545         
5546         // If this is a signed shift right, and the high bit is modified
5547         // by the logical operation, do not perform the transformation.
5548         // The highBitSet boolean indicates the value of the high bit of
5549         // the constant which would cause it to be modified for this
5550         // operation.
5551         //
5552         if (isValid && !isLeftShift && isSignedShift) {
5553           uint64_t Val = Op0C->getZExtValue();
5554           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5555         }
5556         
5557         if (isValid) {
5558           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5559           
5560           Instruction *NewShift =
5561             new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5562                           Op0BO->getName());
5563           Op0BO->setName("");
5564           InsertNewInstBefore(NewShift, I);
5565           
5566           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5567                                         NewRHS);
5568         }
5569       }
5570     }
5571   }
5572   
5573   // Find out if this is a shift of a shift by a constant.
5574   ShiftInst *ShiftOp = 0;
5575   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5576     ShiftOp = Op0SI;
5577   else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5578     // If this is a noop-integer cast of a shift instruction, use the shift.
5579     if (isa<ShiftInst>(CI->getOperand(0))) {
5580       ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5581     }
5582   }
5583   
5584   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5585     // Find the operands and properties of the input shift.  Note that the
5586     // signedness of the input shift may differ from the current shift if there
5587     // is a noop cast between the two.
5588     bool isShiftOfLeftShift   = ShiftOp->getOpcode() == Instruction::Shl;
5589     bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
5590     bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5591     
5592     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5593
5594     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5595     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5596     
5597     // Check for (A << c1) << c2   and   (A >> c1) >> c2.
5598     if (isLeftShift == isShiftOfLeftShift) {
5599       // Do not fold these shifts if the first one is signed and the second one
5600       // is unsigned and this is a right shift.  Further, don't do any folding
5601       // on them.
5602       if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5603         return 0;
5604       
5605       unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5606       if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5607         Amt = Op0->getType()->getPrimitiveSizeInBits();
5608       
5609       Value *Op = ShiftOp->getOperand(0);
5610       ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
5611                                           ConstantInt::get(Type::Int8Ty, Amt));
5612       if (I.getType() == ShiftResult->getType())
5613         return ShiftResult;
5614       InsertNewInstBefore(ShiftResult, I);
5615       return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
5616     }
5617     
5618     // Check for (A << c1) >> c2 or (A >> c1) << c2.  If we are dealing with
5619     // signed types, we can only support the (A >> c1) << c2 configuration,
5620     // because it can not turn an arbitrary bit of A into a sign bit.
5621     if (isUnsignedShift || isLeftShift) {
5622       // Calculate bitmask for what gets shifted off the edge.
5623       Constant *C = ConstantInt::getAllOnesValue(I.getType());
5624       if (isLeftShift)
5625         C = ConstantExpr::getShl(C, ShiftAmt1C);
5626       else
5627         C = ConstantExpr::getLShr(C, ShiftAmt1C);
5628       
5629       Value *Op = ShiftOp->getOperand(0);
5630       
5631       Instruction *Mask =
5632         BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5633       InsertNewInstBefore(Mask, I);
5634       
5635       // Figure out what flavor of shift we should use...
5636       if (ShiftAmt1 == ShiftAmt2) {
5637         return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
5638       } else if (ShiftAmt1 < ShiftAmt2) {
5639         return new ShiftInst(I.getOpcode(), Mask,
5640                          ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
5641       } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5642         if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5643           return new ShiftInst(Instruction::LShr, Mask, 
5644             ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5645         } else {
5646           return new ShiftInst(ShiftOp->getOpcode(), Mask,
5647                     ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5648         }
5649       } else {
5650         // (X >>s C1) << C2  where C1 > C2  === (X >>s (C1-C2)) & mask
5651         Instruction *Shift =
5652           new ShiftInst(ShiftOp->getOpcode(), Mask,
5653                         ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5654         InsertNewInstBefore(Shift, I);
5655         
5656         C = ConstantInt::getAllOnesValue(Shift->getType());
5657         C = ConstantExpr::getShl(C, Op1);
5658         return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5659       }
5660     } else {
5661       // We can handle signed (X << C1) >>s C2 if it's a sign extend.  In
5662       // this case, C1 == C2 and C1 is 8, 16, or 32.
5663       if (ShiftAmt1 == ShiftAmt2) {
5664         const Type *SExtType = 0;
5665         switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5666         case 8 : SExtType = Type::Int8Ty; break;
5667         case 16: SExtType = Type::Int16Ty; break;
5668         case 32: SExtType = Type::Int32Ty; break;
5669         }
5670         
5671         if (SExtType) {
5672           Instruction *NewTrunc = 
5673             new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
5674           InsertNewInstBefore(NewTrunc, I);
5675           return new SExtInst(NewTrunc, I.getType());
5676         }
5677       }
5678     }
5679   }
5680   return 0;
5681 }
5682
5683
5684 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5685 /// expression.  If so, decompose it, returning some value X, such that Val is
5686 /// X*Scale+Offset.
5687 ///
5688 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5689                                         unsigned &Offset) {
5690   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
5691   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5692     Offset = CI->getZExtValue();
5693     Scale  = 1;
5694     return ConstantInt::get(Type::Int32Ty, 0);
5695   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5696     if (I->getNumOperands() == 2) {
5697       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5698         if (I->getOpcode() == Instruction::Shl) {
5699           // This is a value scaled by '1 << the shift amt'.
5700           Scale = 1U << CUI->getZExtValue();
5701           Offset = 0;
5702           return I->getOperand(0);
5703         } else if (I->getOpcode() == Instruction::Mul) {
5704           // This value is scaled by 'CUI'.
5705           Scale = CUI->getZExtValue();
5706           Offset = 0;
5707           return I->getOperand(0);
5708         } else if (I->getOpcode() == Instruction::Add) {
5709           // We have X+C.  Check to see if we really have (X*C2)+C1, 
5710           // where C1 is divisible by C2.
5711           unsigned SubScale;
5712           Value *SubVal = 
5713             DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5714           Offset += CUI->getZExtValue();
5715           if (SubScale > 1 && (Offset % SubScale == 0)) {
5716             Scale = SubScale;
5717             return SubVal;
5718           }
5719         }
5720       }
5721     }
5722   }
5723
5724   // Otherwise, we can't look past this.
5725   Scale = 1;
5726   Offset = 0;
5727   return Val;
5728 }
5729
5730
5731 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5732 /// try to eliminate the cast by moving the type information into the alloc.
5733 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5734                                                    AllocationInst &AI) {
5735   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5736   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
5737   
5738   // Remove any uses of AI that are dead.
5739   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5740   std::vector<Instruction*> DeadUsers;
5741   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5742     Instruction *User = cast<Instruction>(*UI++);
5743     if (isInstructionTriviallyDead(User)) {
5744       while (UI != E && *UI == User)
5745         ++UI; // If this instruction uses AI more than once, don't break UI.
5746       
5747       // Add operands to the worklist.
5748       AddUsesToWorkList(*User);
5749       ++NumDeadInst;
5750       DOUT << "IC: DCE: " << *User;
5751       
5752       User->eraseFromParent();
5753       removeFromWorkList(User);
5754     }
5755   }
5756   
5757   // Get the type really allocated and the type casted to.
5758   const Type *AllocElTy = AI.getAllocatedType();
5759   const Type *CastElTy = PTy->getElementType();
5760   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5761
5762   unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5763   unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5764   if (CastElTyAlign < AllocElTyAlign) return 0;
5765
5766   // If the allocation has multiple uses, only promote it if we are strictly
5767   // increasing the alignment of the resultant allocation.  If we keep it the
5768   // same, we open the door to infinite loops of various kinds.
5769   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5770
5771   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5772   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5773   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5774
5775   // See if we can satisfy the modulus by pulling a scale out of the array
5776   // size argument.
5777   unsigned ArraySizeScale, ArrayOffset;
5778   Value *NumElements = // See if the array size is a decomposable linear expr.
5779     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5780  
5781   // If we can now satisfy the modulus, by using a non-1 scale, we really can
5782   // do the xform.
5783   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5784       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
5785
5786   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5787   Value *Amt = 0;
5788   if (Scale == 1) {
5789     Amt = NumElements;
5790   } else {
5791     // If the allocation size is constant, form a constant mul expression
5792     Amt = ConstantInt::get(Type::Int32Ty, Scale);
5793     if (isa<ConstantInt>(NumElements))
5794       Amt = ConstantExpr::getMul(
5795               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5796     // otherwise multiply the amount and the number of elements
5797     else if (Scale != 1) {
5798       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5799       Amt = InsertNewInstBefore(Tmp, AI);
5800     }
5801   }
5802   
5803   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5804     Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
5805     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5806     Amt = InsertNewInstBefore(Tmp, AI);
5807   }
5808   
5809   std::string Name = AI.getName(); AI.setName("");
5810   AllocationInst *New;
5811   if (isa<MallocInst>(AI))
5812     New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5813   else
5814     New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5815   InsertNewInstBefore(New, AI);
5816   
5817   // If the allocation has multiple uses, insert a cast and change all things
5818   // that used it to use the new cast.  This will also hack on CI, but it will
5819   // die soon.
5820   if (!AI.hasOneUse()) {
5821     AddUsesToWorkList(AI);
5822     // New is the allocation instruction, pointer typed. AI is the original
5823     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5824     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
5825     InsertNewInstBefore(NewCast, AI);
5826     AI.replaceAllUsesWith(NewCast);
5827   }
5828   return ReplaceInstUsesWith(CI, New);
5829 }
5830
5831 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5832 /// and return it without inserting any new casts.  This is used by code that
5833 /// tries to decide whether promoting or shrinking integer operations to wider
5834 /// or smaller types will allow us to eliminate a truncate or extend.
5835 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5836                                        int &NumCastsRemoved) {
5837   if (isa<Constant>(V)) return true;
5838   
5839   Instruction *I = dyn_cast<Instruction>(V);
5840   if (!I || !I->hasOneUse()) return false;
5841   
5842   switch (I->getOpcode()) {
5843   case Instruction::And:
5844   case Instruction::Or:
5845   case Instruction::Xor:
5846     // These operators can all arbitrarily be extended or truncated.
5847     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5848            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5849   case Instruction::AShr:
5850   case Instruction::LShr:
5851   case Instruction::Shl:
5852     // If this is just a bitcast changing the sign of the operation, we can
5853     // convert if the operand can be converted.
5854     if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5855       return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5856     break;
5857   case Instruction::Trunc:
5858   case Instruction::ZExt:
5859   case Instruction::SExt:
5860   case Instruction::BitCast:
5861     // If this is a cast from the destination type, we can trivially eliminate
5862     // it, and this will remove a cast overall.
5863     if (I->getOperand(0)->getType() == Ty) {
5864       // If the first operand is itself a cast, and is eliminable, do not count
5865       // this as an eliminable cast.  We would prefer to eliminate those two
5866       // casts first.
5867       if (isa<CastInst>(I->getOperand(0)))
5868         return true;
5869       
5870       ++NumCastsRemoved;
5871       return true;
5872     }
5873     break;
5874   default:
5875     // TODO: Can handle more cases here.
5876     break;
5877   }
5878   
5879   return false;
5880 }
5881
5882 /// EvaluateInDifferentType - Given an expression that 
5883 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5884 /// evaluate the expression.
5885 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
5886                                              bool isSigned ) {
5887   if (Constant *C = dyn_cast<Constant>(V))
5888     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
5889
5890   // Otherwise, it must be an instruction.
5891   Instruction *I = cast<Instruction>(V);
5892   Instruction *Res = 0;
5893   switch (I->getOpcode()) {
5894   case Instruction::And:
5895   case Instruction::Or:
5896   case Instruction::Xor: {
5897     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5898     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
5899     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5900                                  LHS, RHS, I->getName());
5901     break;
5902   }
5903   case Instruction::AShr:
5904   case Instruction::LShr:
5905   case Instruction::Shl: {
5906     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5907     Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5908                         I->getOperand(1), I->getName());
5909     break;
5910   }    
5911   case Instruction::Trunc:
5912   case Instruction::ZExt:
5913   case Instruction::SExt:
5914   case Instruction::BitCast:
5915     // If the source type of the cast is the type we're trying for then we can
5916     // just return the source. There's no need to insert it because its not new.
5917     if (I->getOperand(0)->getType() == Ty)
5918       return I->getOperand(0);
5919     
5920     // Some other kind of cast, which shouldn't happen, so just ..
5921     // FALL THROUGH
5922   default: 
5923     // TODO: Can handle more cases here.
5924     assert(0 && "Unreachable!");
5925     break;
5926   }
5927   
5928   return InsertNewInstBefore(Res, *I);
5929 }
5930
5931 /// @brief Implement the transforms common to all CastInst visitors.
5932 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
5933   Value *Src = CI.getOperand(0);
5934
5935   // Casting undef to anything results in undef so might as just replace it and
5936   // get rid of the cast.
5937   if (isa<UndefValue>(Src))   // cast undef -> undef
5938     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5939
5940   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5941   // eliminate it now.
5942   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
5943     if (Instruction::CastOps opc = 
5944         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5945       // The first cast (CSrc) is eliminable so we need to fix up or replace
5946       // the second cast (CI). CSrc will then have a good chance of being dead.
5947       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
5948     }
5949   }
5950
5951   // If casting the result of a getelementptr instruction with no offset, turn
5952   // this into a cast of the original pointer!
5953   //
5954   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5955     bool AllZeroOperands = true;
5956     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5957       if (!isa<Constant>(GEP->getOperand(i)) ||
5958           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5959         AllZeroOperands = false;
5960         break;
5961       }
5962     if (AllZeroOperands) {
5963       // Changing the cast operand is usually not a good idea but it is safe
5964       // here because the pointer operand is being replaced with another 
5965       // pointer operand so the opcode doesn't need to change.
5966       CI.setOperand(0, GEP->getOperand(0));
5967       return &CI;
5968     }
5969   }
5970     
5971   // If we are casting a malloc or alloca to a pointer to a type of the same
5972   // size, rewrite the allocation instruction to allocate the "right" type.
5973   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5974     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5975       return V;
5976
5977   // If we are casting a select then fold the cast into the select
5978   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5979     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5980       return NV;
5981
5982   // If we are casting a PHI then fold the cast into the PHI
5983   if (isa<PHINode>(Src))
5984     if (Instruction *NV = FoldOpIntoPhi(CI))
5985       return NV;
5986   
5987   return 0;
5988 }
5989
5990 /// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5991 /// integers. This function implements the common transforms for all those
5992 /// cases.
5993 /// @brief Implement the transforms common to CastInst with integer operands
5994 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
5995   if (Instruction *Result = commonCastTransforms(CI))
5996     return Result;
5997
5998   Value *Src = CI.getOperand(0);
5999   const Type *SrcTy = Src->getType();
6000   const Type *DestTy = CI.getType();
6001   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6002   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6003
6004   // See if we can simplify any instructions used by the LHS whose sole 
6005   // purpose is to compute bits we don't care about.
6006   uint64_t KnownZero = 0, KnownOne = 0;
6007   if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
6008                            KnownZero, KnownOne))
6009     return &CI;
6010
6011   // If the source isn't an instruction or has more than one use then we
6012   // can't do anything more. 
6013   Instruction *SrcI = dyn_cast<Instruction>(Src);
6014   if (!SrcI || !Src->hasOneUse())
6015     return 0;
6016
6017   // Attempt to propagate the cast into the instruction.
6018   int NumCastsRemoved = 0;
6019   if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6020     // If this cast is a truncate, evaluting in a different type always
6021     // eliminates the cast, so it is always a win.  If this is a noop-cast
6022     // this just removes a noop cast which isn't pointful, but simplifies
6023     // the code.  If this is a zero-extension, we need to do an AND to
6024     // maintain the clear top-part of the computation, so we require that
6025     // the input have eliminated at least one cast.  If this is a sign
6026     // extension, we insert two new casts (to do the extension) so we
6027     // require that two casts have been eliminated.
6028     bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6029     if (!DoXForm) {
6030       switch (CI.getOpcode()) {
6031         case Instruction::Trunc:
6032           DoXForm = true;
6033           break;
6034         case Instruction::ZExt:
6035           DoXForm = NumCastsRemoved >= 1;
6036           break;
6037         case Instruction::SExt:
6038           DoXForm = NumCastsRemoved >= 2;
6039           break;
6040         case Instruction::BitCast:
6041           DoXForm = false;
6042           break;
6043         default:
6044           // All the others use floating point so we shouldn't actually 
6045           // get here because of the check above.
6046           assert(!"Unknown cast type .. unreachable");
6047           break;
6048       }
6049     }
6050     
6051     if (DoXForm) {
6052       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6053                                            CI.getOpcode() == Instruction::SExt);
6054       assert(Res->getType() == DestTy);
6055       switch (CI.getOpcode()) {
6056       default: assert(0 && "Unknown cast type!");
6057       case Instruction::Trunc:
6058       case Instruction::BitCast:
6059         // Just replace this cast with the result.
6060         return ReplaceInstUsesWith(CI, Res);
6061       case Instruction::ZExt: {
6062         // We need to emit an AND to clear the high bits.
6063         assert(SrcBitSize < DestBitSize && "Not a zext?");
6064         Constant *C = 
6065           ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
6066         if (DestBitSize < 64)
6067           C = ConstantExpr::getTrunc(C, DestTy);
6068         return BinaryOperator::createAnd(Res, C);
6069       }
6070       case Instruction::SExt:
6071         // We need to emit a cast to truncate, then a cast to sext.
6072         return CastInst::create(Instruction::SExt,
6073             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6074                              CI), DestTy);
6075       }
6076     }
6077   }
6078   
6079   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6080   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6081
6082   switch (SrcI->getOpcode()) {
6083   case Instruction::Add:
6084   case Instruction::Mul:
6085   case Instruction::And:
6086   case Instruction::Or:
6087   case Instruction::Xor:
6088     // If we are discarding information, or just changing the sign, 
6089     // rewrite.
6090     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6091       // Don't insert two casts if they cannot be eliminated.  We allow 
6092       // two casts to be inserted if the sizes are the same.  This could 
6093       // only be converting signedness, which is a noop.
6094       if (DestBitSize == SrcBitSize || 
6095           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6096           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6097         Instruction::CastOps opcode = CI.getOpcode();
6098         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6099         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6100         return BinaryOperator::create(
6101             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6102       }
6103     }
6104
6105     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6106     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6107         SrcI->getOpcode() == Instruction::Xor &&
6108         Op1 == ConstantInt::getTrue() &&
6109         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6110       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6111       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6112     }
6113     break;
6114   case Instruction::SDiv:
6115   case Instruction::UDiv:
6116   case Instruction::SRem:
6117   case Instruction::URem:
6118     // If we are just changing the sign, rewrite.
6119     if (DestBitSize == SrcBitSize) {
6120       // Don't insert two casts if they cannot be eliminated.  We allow 
6121       // two casts to be inserted if the sizes are the same.  This could 
6122       // only be converting signedness, which is a noop.
6123       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6124           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6125         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6126                                               Op0, DestTy, SrcI);
6127         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6128                                               Op1, DestTy, SrcI);
6129         return BinaryOperator::create(
6130           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6131       }
6132     }
6133     break;
6134
6135   case Instruction::Shl:
6136     // Allow changing the sign of the source operand.  Do not allow 
6137     // changing the size of the shift, UNLESS the shift amount is a 
6138     // constant.  We must not change variable sized shifts to a smaller 
6139     // size, because it is undefined to shift more bits out than exist 
6140     // in the value.
6141     if (DestBitSize == SrcBitSize ||
6142         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6143       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6144           Instruction::BitCast : Instruction::Trunc);
6145       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6146       return new ShiftInst(Instruction::Shl, Op0c, Op1);
6147     }
6148     break;
6149   case Instruction::AShr:
6150     // If this is a signed shr, and if all bits shifted in are about to be
6151     // truncated off, turn it into an unsigned shr to allow greater
6152     // simplifications.
6153     if (DestBitSize < SrcBitSize &&
6154         isa<ConstantInt>(Op1)) {
6155       unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6156       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6157         // Insert the new logical shift right.
6158         return new ShiftInst(Instruction::LShr, Op0, Op1);
6159       }
6160     }
6161     break;
6162
6163   case Instruction::ICmp:
6164     // If we are just checking for a icmp eq of a single bit and casting it
6165     // to an integer, then shift the bit to the appropriate place and then
6166     // cast to integer to avoid the comparison.
6167     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6168       uint64_t Op1CV = Op1C->getZExtValue();
6169       // cast (X == 0) to int --> X^1      iff X has only the low bit set.
6170       // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6171       // cast (X == 1) to int --> X        iff X has only the low bit set.
6172       // cast (X == 2) to int --> X>>1     iff X has only the 2nd bit set.
6173       // cast (X != 0) to int --> X        iff X has only the low bit set.
6174       // cast (X != 0) to int --> X>>1     iff X has only the 2nd bit set.
6175       // cast (X != 1) to int --> X^1      iff X has only the low bit set.
6176       // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6177       if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6178         // If Op1C some other power of two, convert:
6179         uint64_t KnownZero, KnownOne;
6180         uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
6181         ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
6182
6183         // This only works for EQ and NE
6184         ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6185         if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6186           break;
6187         
6188         if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
6189           bool isNE = pred == ICmpInst::ICMP_NE;
6190           if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6191             // (X&4) == 2 --> false
6192             // (X&4) != 2 --> true
6193             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6194             Res = ConstantExpr::getZExt(Res, CI.getType());
6195             return ReplaceInstUsesWith(CI, Res);
6196           }
6197           
6198           unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6199           Value *In = Op0;
6200           if (ShiftAmt) {
6201             // Perform a logical shr by shiftamt.
6202             // Insert the shift to put the result in the low bit.
6203             In = InsertNewInstBefore(
6204               new ShiftInst(Instruction::LShr, In,
6205                             ConstantInt::get(Type::Int8Ty, ShiftAmt),
6206                             In->getName()+".lobit"), CI);
6207           }
6208           
6209           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6210             Constant *One = ConstantInt::get(In->getType(), 1);
6211             In = BinaryOperator::createXor(In, One, "tmp");
6212             InsertNewInstBefore(cast<Instruction>(In), CI);
6213           }
6214           
6215           if (CI.getType() == In->getType())
6216             return ReplaceInstUsesWith(CI, In);
6217           else
6218             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6219         }
6220       }
6221     }
6222     break;
6223   }
6224   return 0;
6225 }
6226
6227 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
6228   if (Instruction *Result = commonIntCastTransforms(CI))
6229     return Result;
6230   
6231   Value *Src = CI.getOperand(0);
6232   const Type *Ty = CI.getType();
6233   unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6234   
6235   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6236     switch (SrcI->getOpcode()) {
6237     default: break;
6238     case Instruction::LShr:
6239       // We can shrink lshr to something smaller if we know the bits shifted in
6240       // are already zeros.
6241       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6242         unsigned ShAmt = ShAmtV->getZExtValue();
6243         
6244         // Get a mask for the bits shifting in.
6245         uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
6246         Value* SrcIOp0 = SrcI->getOperand(0);
6247         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6248           if (ShAmt >= DestBitWidth)        // All zeros.
6249             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6250
6251           // Okay, we can shrink this.  Truncate the input, then return a new
6252           // shift.
6253           Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6254           return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6255         }
6256       } else {     // This is a variable shr.
6257         
6258         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6259         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6260         // loop-invariant and CSE'd.
6261         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6262           Value *One = ConstantInt::get(SrcI->getType(), 1);
6263
6264           Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6265                                                        SrcI->getOperand(1),
6266                                                        "tmp"), CI);
6267           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6268                                                             SrcI->getOperand(0),
6269                                                             "tmp"), CI);
6270           Value *Zero = Constant::getNullValue(V->getType());
6271           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6272         }
6273       }
6274       break;
6275     }
6276   }
6277   
6278   return 0;
6279 }
6280
6281 Instruction *InstCombiner::visitZExt(CastInst &CI) {
6282   // If one of the common conversion will work ..
6283   if (Instruction *Result = commonIntCastTransforms(CI))
6284     return Result;
6285
6286   Value *Src = CI.getOperand(0);
6287
6288   // If this is a cast of a cast
6289   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6290     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6291     // types and if the sizes are just right we can convert this into a logical
6292     // 'and' which will be much cheaper than the pair of casts.
6293     if (isa<TruncInst>(CSrc)) {
6294       // Get the sizes of the types involved
6295       Value *A = CSrc->getOperand(0);
6296       unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6297       unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6298       unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6299       // If we're actually extending zero bits and the trunc is a no-op
6300       if (MidSize < DstSize && SrcSize == DstSize) {
6301         // Replace both of the casts with an And of the type mask.
6302         uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6303         Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6304         Instruction *And = 
6305           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6306         // Unfortunately, if the type changed, we need to cast it back.
6307         if (And->getType() != CI.getType()) {
6308           And->setName(CSrc->getName()+".mask");
6309           InsertNewInstBefore(And, CI);
6310           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6311         }
6312         return And;
6313       }
6314     }
6315   }
6316
6317   return 0;
6318 }
6319
6320 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6321   return commonIntCastTransforms(CI);
6322 }
6323
6324 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6325   return commonCastTransforms(CI);
6326 }
6327
6328 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6329   return commonCastTransforms(CI);
6330 }
6331
6332 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6333   return commonCastTransforms(CI);
6334 }
6335
6336 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6337   return commonCastTransforms(CI);
6338 }
6339
6340 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6341   return commonCastTransforms(CI);
6342 }
6343
6344 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6345   return commonCastTransforms(CI);
6346 }
6347
6348 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6349   return commonCastTransforms(CI);
6350 }
6351
6352 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6353   return commonCastTransforms(CI);
6354 }
6355
6356 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6357
6358   // If the operands are integer typed then apply the integer transforms,
6359   // otherwise just apply the common ones.
6360   Value *Src = CI.getOperand(0);
6361   const Type *SrcTy = Src->getType();
6362   const Type *DestTy = CI.getType();
6363
6364   if (SrcTy->isInteger() && DestTy->isInteger()) {
6365     if (Instruction *Result = commonIntCastTransforms(CI))
6366       return Result;
6367   } else {
6368     if (Instruction *Result = commonCastTransforms(CI))
6369       return Result;
6370   }
6371
6372
6373   // Get rid of casts from one type to the same type. These are useless and can
6374   // be replaced by the operand.
6375   if (DestTy == Src->getType())
6376     return ReplaceInstUsesWith(CI, Src);
6377
6378   // If the source and destination are pointers, and this cast is equivalent to
6379   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
6380   // This can enhance SROA and other transforms that want type-safe pointers.
6381   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6382     if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6383       const Type *DstElTy = DstPTy->getElementType();
6384       const Type *SrcElTy = SrcPTy->getElementType();
6385       
6386       Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6387       unsigned NumZeros = 0;
6388       while (SrcElTy != DstElTy && 
6389              isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6390              SrcElTy->getNumContainedTypes() /* not "{}" */) {
6391         SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6392         ++NumZeros;
6393       }
6394
6395       // If we found a path from the src to dest, create the getelementptr now.
6396       if (SrcElTy == DstElTy) {
6397         std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6398         return new GetElementPtrInst(Src, Idxs);
6399       }
6400     }
6401   }
6402
6403   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6404     if (SVI->hasOneUse()) {
6405       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
6406       // a bitconvert to a vector with the same # elts.
6407       if (isa<PackedType>(DestTy) && 
6408           cast<PackedType>(DestTy)->getNumElements() == 
6409                 SVI->getType()->getNumElements()) {
6410         CastInst *Tmp;
6411         // If either of the operands is a cast from CI.getType(), then
6412         // evaluating the shuffle in the casted destination's type will allow
6413         // us to eliminate at least one cast.
6414         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
6415              Tmp->getOperand(0)->getType() == DestTy) ||
6416             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
6417              Tmp->getOperand(0)->getType() == DestTy)) {
6418           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6419                                                SVI->getOperand(0), DestTy, &CI);
6420           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6421                                                SVI->getOperand(1), DestTy, &CI);
6422           // Return a new shuffle vector.  Use the same element ID's, as we
6423           // know the vector types match #elts.
6424           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6425         }
6426       }
6427     }
6428   }
6429   return 0;
6430 }
6431
6432 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6433 ///   %C = or %A, %B
6434 ///   %D = select %cond, %C, %A
6435 /// into:
6436 ///   %C = select %cond, %B, 0
6437 ///   %D = or %A, %C
6438 ///
6439 /// Assuming that the specified instruction is an operand to the select, return
6440 /// a bitmask indicating which operands of this instruction are foldable if they
6441 /// equal the other incoming value of the select.
6442 ///
6443 static unsigned GetSelectFoldableOperands(Instruction *I) {
6444   switch (I->getOpcode()) {
6445   case Instruction::Add:
6446   case Instruction::Mul:
6447   case Instruction::And:
6448   case Instruction::Or:
6449   case Instruction::Xor:
6450     return 3;              // Can fold through either operand.
6451   case Instruction::Sub:   // Can only fold on the amount subtracted.
6452   case Instruction::Shl:   // Can only fold on the shift amount.
6453   case Instruction::LShr:
6454   case Instruction::AShr:
6455     return 1;
6456   default:
6457     return 0;              // Cannot fold
6458   }
6459 }
6460
6461 /// GetSelectFoldableConstant - For the same transformation as the previous
6462 /// function, return the identity constant that goes into the select.
6463 static Constant *GetSelectFoldableConstant(Instruction *I) {
6464   switch (I->getOpcode()) {
6465   default: assert(0 && "This cannot happen!"); abort();
6466   case Instruction::Add:
6467   case Instruction::Sub:
6468   case Instruction::Or:
6469   case Instruction::Xor:
6470     return Constant::getNullValue(I->getType());
6471   case Instruction::Shl:
6472   case Instruction::LShr:
6473   case Instruction::AShr:
6474     return Constant::getNullValue(Type::Int8Ty);
6475   case Instruction::And:
6476     return ConstantInt::getAllOnesValue(I->getType());
6477   case Instruction::Mul:
6478     return ConstantInt::get(I->getType(), 1);
6479   }
6480 }
6481
6482 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6483 /// have the same opcode and only one use each.  Try to simplify this.
6484 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6485                                           Instruction *FI) {
6486   if (TI->getNumOperands() == 1) {
6487     // If this is a non-volatile load or a cast from the same type,
6488     // merge.
6489     if (TI->isCast()) {
6490       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6491         return 0;
6492     } else {
6493       return 0;  // unknown unary op.
6494     }
6495
6496     // Fold this by inserting a select from the input values.
6497     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6498                                        FI->getOperand(0), SI.getName()+".v");
6499     InsertNewInstBefore(NewSI, SI);
6500     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
6501                             TI->getType());
6502   }
6503
6504   // Only handle binary, compare and shift operators here.
6505   if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6506     return 0;
6507
6508   // Figure out if the operations have any operands in common.
6509   Value *MatchOp, *OtherOpT, *OtherOpF;
6510   bool MatchIsOpZero;
6511   if (TI->getOperand(0) == FI->getOperand(0)) {
6512     MatchOp  = TI->getOperand(0);
6513     OtherOpT = TI->getOperand(1);
6514     OtherOpF = FI->getOperand(1);
6515     MatchIsOpZero = true;
6516   } else if (TI->getOperand(1) == FI->getOperand(1)) {
6517     MatchOp  = TI->getOperand(1);
6518     OtherOpT = TI->getOperand(0);
6519     OtherOpF = FI->getOperand(0);
6520     MatchIsOpZero = false;
6521   } else if (!TI->isCommutative()) {
6522     return 0;
6523   } else if (TI->getOperand(0) == FI->getOperand(1)) {
6524     MatchOp  = TI->getOperand(0);
6525     OtherOpT = TI->getOperand(1);
6526     OtherOpF = FI->getOperand(0);
6527     MatchIsOpZero = true;
6528   } else if (TI->getOperand(1) == FI->getOperand(0)) {
6529     MatchOp  = TI->getOperand(1);
6530     OtherOpT = TI->getOperand(0);
6531     OtherOpF = FI->getOperand(1);
6532     MatchIsOpZero = true;
6533   } else {
6534     return 0;
6535   }
6536
6537   // If we reach here, they do have operations in common.
6538   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6539                                      OtherOpF, SI.getName()+".v");
6540   InsertNewInstBefore(NewSI, SI);
6541
6542   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6543     if (MatchIsOpZero)
6544       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6545     else
6546       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6547   }
6548
6549   assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6550   if (MatchIsOpZero)
6551     return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6552   else
6553     return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6554 }
6555
6556 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6557   Value *CondVal = SI.getCondition();
6558   Value *TrueVal = SI.getTrueValue();
6559   Value *FalseVal = SI.getFalseValue();
6560
6561   // select true, X, Y  -> X
6562   // select false, X, Y -> Y
6563   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
6564     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
6565
6566   // select C, X, X -> X
6567   if (TrueVal == FalseVal)
6568     return ReplaceInstUsesWith(SI, TrueVal);
6569
6570   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
6571     return ReplaceInstUsesWith(SI, FalseVal);
6572   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
6573     return ReplaceInstUsesWith(SI, TrueVal);
6574   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
6575     if (isa<Constant>(TrueVal))
6576       return ReplaceInstUsesWith(SI, TrueVal);
6577     else
6578       return ReplaceInstUsesWith(SI, FalseVal);
6579   }
6580
6581   if (SI.getType() == Type::Int1Ty) {
6582     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
6583       if (C->getZExtValue()) {
6584         // Change: A = select B, true, C --> A = or B, C
6585         return BinaryOperator::createOr(CondVal, FalseVal);
6586       } else {
6587         // Change: A = select B, false, C --> A = and !B, C
6588         Value *NotCond =
6589           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6590                                              "not."+CondVal->getName()), SI);
6591         return BinaryOperator::createAnd(NotCond, FalseVal);
6592       }
6593     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
6594       if (C->getZExtValue() == false) {
6595         // Change: A = select B, C, false --> A = and B, C
6596         return BinaryOperator::createAnd(CondVal, TrueVal);
6597       } else {
6598         // Change: A = select B, C, true --> A = or !B, C
6599         Value *NotCond =
6600           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6601                                              "not."+CondVal->getName()), SI);
6602         return BinaryOperator::createOr(NotCond, TrueVal);
6603       }
6604     }
6605   }
6606
6607   // Selecting between two integer constants?
6608   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6609     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6610       // select C, 1, 0 -> cast C to int
6611       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6612         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6613       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6614         // select C, 0, 1 -> cast !C to int
6615         Value *NotCond =
6616           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6617                                                "not."+CondVal->getName()), SI);
6618         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6619       }
6620
6621       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
6622
6623         // (x <s 0) ? -1 : 0 -> ashr x, 31
6624         // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
6625         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6626           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6627             bool CanXForm = false;
6628             if (IC->isSignedPredicate())
6629               CanXForm = CmpCst->isNullValue() && 
6630                          IC->getPredicate() == ICmpInst::ICMP_SLT;
6631             else {
6632               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6633               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6634                          IC->getPredicate() == ICmpInst::ICMP_UGT;
6635             }
6636             
6637             if (CanXForm) {
6638               // The comparison constant and the result are not neccessarily the
6639               // same width. Make an all-ones value by inserting a AShr.
6640               Value *X = IC->getOperand(0);
6641               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6642               Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
6643               Instruction *SRA = new ShiftInst(Instruction::AShr, X,
6644                                                ShAmt, "ones");
6645               InsertNewInstBefore(SRA, SI);
6646               
6647               // Finally, convert to the type of the select RHS.  We figure out
6648               // if this requires a SExt, Trunc or BitCast based on the sizes.
6649               Instruction::CastOps opc = Instruction::BitCast;
6650               unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6651               unsigned SISize  = SI.getType()->getPrimitiveSizeInBits();
6652               if (SRASize < SISize)
6653                 opc = Instruction::SExt;
6654               else if (SRASize > SISize)
6655                 opc = Instruction::Trunc;
6656               return CastInst::create(opc, SRA, SI.getType());
6657             }
6658           }
6659
6660
6661         // If one of the constants is zero (we know they can't both be) and we
6662         // have a fcmp instruction with zero, and we have an 'and' with the
6663         // non-constant value, eliminate this whole mess.  This corresponds to
6664         // cases like this: ((X & 27) ? 27 : 0)
6665         if (TrueValC->isNullValue() || FalseValC->isNullValue())
6666           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6667               cast<Constant>(IC->getOperand(1))->isNullValue())
6668             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6669               if (ICA->getOpcode() == Instruction::And &&
6670                   isa<ConstantInt>(ICA->getOperand(1)) &&
6671                   (ICA->getOperand(1) == TrueValC ||
6672                    ICA->getOperand(1) == FalseValC) &&
6673                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6674                 // Okay, now we know that everything is set up, we just don't
6675                 // know whether we have a icmp_ne or icmp_eq and whether the 
6676                 // true or false val is the zero.
6677                 bool ShouldNotVal = !TrueValC->isNullValue();
6678                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
6679                 Value *V = ICA;
6680                 if (ShouldNotVal)
6681                   V = InsertNewInstBefore(BinaryOperator::create(
6682                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
6683                 return ReplaceInstUsesWith(SI, V);
6684               }
6685       }
6686     }
6687
6688   // See if we are selecting two values based on a comparison of the two values.
6689   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6690     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
6691       // Transform (X == Y) ? X : Y  -> Y
6692       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6693         return ReplaceInstUsesWith(SI, FalseVal);
6694       // Transform (X != Y) ? X : Y  -> X
6695       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6696         return ReplaceInstUsesWith(SI, TrueVal);
6697       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6698
6699     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
6700       // Transform (X == Y) ? Y : X  -> X
6701       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6702         return ReplaceInstUsesWith(SI, FalseVal);
6703       // Transform (X != Y) ? Y : X  -> Y
6704       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6705         return ReplaceInstUsesWith(SI, TrueVal);
6706       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6707     }
6708   }
6709
6710   // See if we are selecting two values based on a comparison of the two values.
6711   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6712     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6713       // Transform (X == Y) ? X : Y  -> Y
6714       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6715         return ReplaceInstUsesWith(SI, FalseVal);
6716       // Transform (X != Y) ? X : Y  -> X
6717       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6718         return ReplaceInstUsesWith(SI, TrueVal);
6719       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6720
6721     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6722       // Transform (X == Y) ? Y : X  -> X
6723       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6724         return ReplaceInstUsesWith(SI, FalseVal);
6725       // Transform (X != Y) ? Y : X  -> Y
6726       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6727         return ReplaceInstUsesWith(SI, TrueVal);
6728       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6729     }
6730   }
6731
6732   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6733     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6734       if (TI->hasOneUse() && FI->hasOneUse()) {
6735         Instruction *AddOp = 0, *SubOp = 0;
6736
6737         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6738         if (TI->getOpcode() == FI->getOpcode())
6739           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6740             return IV;
6741
6742         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
6743         // even legal for FP.
6744         if (TI->getOpcode() == Instruction::Sub &&
6745             FI->getOpcode() == Instruction::Add) {
6746           AddOp = FI; SubOp = TI;
6747         } else if (FI->getOpcode() == Instruction::Sub &&
6748                    TI->getOpcode() == Instruction::Add) {
6749           AddOp = TI; SubOp = FI;
6750         }
6751
6752         if (AddOp) {
6753           Value *OtherAddOp = 0;
6754           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6755             OtherAddOp = AddOp->getOperand(1);
6756           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6757             OtherAddOp = AddOp->getOperand(0);
6758           }
6759
6760           if (OtherAddOp) {
6761             // So at this point we know we have (Y -> OtherAddOp):
6762             //        select C, (add X, Y), (sub X, Z)
6763             Value *NegVal;  // Compute -Z
6764             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6765               NegVal = ConstantExpr::getNeg(C);
6766             } else {
6767               NegVal = InsertNewInstBefore(
6768                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6769             }
6770
6771             Value *NewTrueOp = OtherAddOp;
6772             Value *NewFalseOp = NegVal;
6773             if (AddOp != TI)
6774               std::swap(NewTrueOp, NewFalseOp);
6775             Instruction *NewSel =
6776               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6777
6778             NewSel = InsertNewInstBefore(NewSel, SI);
6779             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6780           }
6781         }
6782       }
6783
6784   // See if we can fold the select into one of our operands.
6785   if (SI.getType()->isInteger()) {
6786     // See the comment above GetSelectFoldableOperands for a description of the
6787     // transformation we are doing here.
6788     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6789       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6790           !isa<Constant>(FalseVal))
6791         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6792           unsigned OpToFold = 0;
6793           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6794             OpToFold = 1;
6795           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6796             OpToFold = 2;
6797           }
6798
6799           if (OpToFold) {
6800             Constant *C = GetSelectFoldableConstant(TVI);
6801             std::string Name = TVI->getName(); TVI->setName("");
6802             Instruction *NewSel =
6803               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6804                              Name);
6805             InsertNewInstBefore(NewSel, SI);
6806             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6807               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6808             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6809               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6810             else {
6811               assert(0 && "Unknown instruction!!");
6812             }
6813           }
6814         }
6815
6816     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6817       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6818           !isa<Constant>(TrueVal))
6819         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6820           unsigned OpToFold = 0;
6821           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6822             OpToFold = 1;
6823           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6824             OpToFold = 2;
6825           }
6826
6827           if (OpToFold) {
6828             Constant *C = GetSelectFoldableConstant(FVI);
6829             std::string Name = FVI->getName(); FVI->setName("");
6830             Instruction *NewSel =
6831               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6832                              Name);
6833             InsertNewInstBefore(NewSel, SI);
6834             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6835               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6836             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6837               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6838             else {
6839               assert(0 && "Unknown instruction!!");
6840             }
6841           }
6842         }
6843   }
6844
6845   if (BinaryOperator::isNot(CondVal)) {
6846     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6847     SI.setOperand(1, FalseVal);
6848     SI.setOperand(2, TrueVal);
6849     return &SI;
6850   }
6851
6852   return 0;
6853 }
6854
6855 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6856 /// determine, return it, otherwise return 0.
6857 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6858   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6859     unsigned Align = GV->getAlignment();
6860     if (Align == 0 && TD) 
6861       Align = TD->getTypeAlignment(GV->getType()->getElementType());
6862     return Align;
6863   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6864     unsigned Align = AI->getAlignment();
6865     if (Align == 0 && TD) {
6866       if (isa<AllocaInst>(AI))
6867         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6868       else if (isa<MallocInst>(AI)) {
6869         // Malloc returns maximally aligned memory.
6870         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6871         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6872         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::Int64Ty));
6873       }
6874     }
6875     return Align;
6876   } else if (isa<BitCastInst>(V) ||
6877              (isa<ConstantExpr>(V) && 
6878               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
6879     User *CI = cast<User>(V);
6880     if (isa<PointerType>(CI->getOperand(0)->getType()))
6881       return GetKnownAlignment(CI->getOperand(0), TD);
6882     return 0;
6883   } else if (isa<GetElementPtrInst>(V) ||
6884              (isa<ConstantExpr>(V) && 
6885               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6886     User *GEPI = cast<User>(V);
6887     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6888     if (BaseAlignment == 0) return 0;
6889     
6890     // If all indexes are zero, it is just the alignment of the base pointer.
6891     bool AllZeroOperands = true;
6892     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6893       if (!isa<Constant>(GEPI->getOperand(i)) ||
6894           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6895         AllZeroOperands = false;
6896         break;
6897       }
6898     if (AllZeroOperands)
6899       return BaseAlignment;
6900     
6901     // Otherwise, if the base alignment is >= the alignment we expect for the
6902     // base pointer type, then we know that the resultant pointer is aligned at
6903     // least as much as its type requires.
6904     if (!TD) return 0;
6905
6906     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6907     if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6908         <= BaseAlignment) {
6909       const Type *GEPTy = GEPI->getType();
6910       return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6911     }
6912     return 0;
6913   }
6914   return 0;
6915 }
6916
6917
6918 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
6919 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
6920 /// the heavy lifting.
6921 ///
6922 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6923   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6924   if (!II) return visitCallSite(&CI);
6925   
6926   // Intrinsics cannot occur in an invoke, so handle them here instead of in
6927   // visitCallSite.
6928   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6929     bool Changed = false;
6930
6931     // memmove/cpy/set of zero bytes is a noop.
6932     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6933       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6934
6935       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6936         if (CI->getZExtValue() == 1) {
6937           // Replace the instruction with just byte operations.  We would
6938           // transform other cases to loads/stores, but we don't know if
6939           // alignment is sufficient.
6940         }
6941     }
6942
6943     // If we have a memmove and the source operation is a constant global,
6944     // then the source and dest pointers can't alias, so we can change this
6945     // into a call to memcpy.
6946     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6947       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6948         if (GVSrc->isConstant()) {
6949           Module *M = CI.getParent()->getParent()->getParent();
6950           const char *Name;
6951           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
6952               Type::Int32Ty)
6953             Name = "llvm.memcpy.i32";
6954           else
6955             Name = "llvm.memcpy.i64";
6956           Constant *MemCpy = M->getOrInsertFunction(Name,
6957                                      CI.getCalledFunction()->getFunctionType());
6958           CI.setOperand(0, MemCpy);
6959           Changed = true;
6960         }
6961     }
6962
6963     // If we can determine a pointer alignment that is bigger than currently
6964     // set, update the alignment.
6965     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6966       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6967       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6968       unsigned Align = std::min(Alignment1, Alignment2);
6969       if (MI->getAlignment()->getZExtValue() < Align) {
6970         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
6971         Changed = true;
6972       }
6973     } else if (isa<MemSetInst>(MI)) {
6974       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6975       if (MI->getAlignment()->getZExtValue() < Alignment) {
6976         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
6977         Changed = true;
6978       }
6979     }
6980           
6981     if (Changed) return II;
6982   } else {
6983     switch (II->getIntrinsicID()) {
6984     default: break;
6985     case Intrinsic::ppc_altivec_lvx:
6986     case Intrinsic::ppc_altivec_lvxl:
6987     case Intrinsic::x86_sse_loadu_ps:
6988     case Intrinsic::x86_sse2_loadu_pd:
6989     case Intrinsic::x86_sse2_loadu_dq:
6990       // Turn PPC lvx     -> load if the pointer is known aligned.
6991       // Turn X86 loadups -> load if the pointer is known aligned.
6992       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6993         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
6994                                       PointerType::get(II->getType()), CI);
6995         return new LoadInst(Ptr);
6996       }
6997       break;
6998     case Intrinsic::ppc_altivec_stvx:
6999     case Intrinsic::ppc_altivec_stvxl:
7000       // Turn stvx -> store if the pointer is known aligned.
7001       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7002         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7003         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7004                                       OpPtrTy, CI);
7005         return new StoreInst(II->getOperand(1), Ptr);
7006       }
7007       break;
7008     case Intrinsic::x86_sse_storeu_ps:
7009     case Intrinsic::x86_sse2_storeu_pd:
7010     case Intrinsic::x86_sse2_storeu_dq:
7011     case Intrinsic::x86_sse2_storel_dq:
7012       // Turn X86 storeu -> store if the pointer is known aligned.
7013       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7014         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7015         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7016                                       OpPtrTy, CI);
7017         return new StoreInst(II->getOperand(2), Ptr);
7018       }
7019       break;
7020       
7021     case Intrinsic::x86_sse_cvttss2si: {
7022       // These intrinsics only demands the 0th element of its input vector.  If
7023       // we can simplify the input based on that, do so now.
7024       uint64_t UndefElts;
7025       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7026                                                 UndefElts)) {
7027         II->setOperand(1, V);
7028         return II;
7029       }
7030       break;
7031     }
7032       
7033     case Intrinsic::ppc_altivec_vperm:
7034       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7035       if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7036         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7037         
7038         // Check that all of the elements are integer constants or undefs.
7039         bool AllEltsOk = true;
7040         for (unsigned i = 0; i != 16; ++i) {
7041           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7042               !isa<UndefValue>(Mask->getOperand(i))) {
7043             AllEltsOk = false;
7044             break;
7045           }
7046         }
7047         
7048         if (AllEltsOk) {
7049           // Cast the input vectors to byte vectors.
7050           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7051                                         II->getOperand(1), Mask->getType(), CI);
7052           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7053                                         II->getOperand(2), Mask->getType(), CI);
7054           Value *Result = UndefValue::get(Op0->getType());
7055           
7056           // Only extract each element once.
7057           Value *ExtractedElts[32];
7058           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7059           
7060           for (unsigned i = 0; i != 16; ++i) {
7061             if (isa<UndefValue>(Mask->getOperand(i)))
7062               continue;
7063             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7064             Idx &= 31;  // Match the hardware behavior.
7065             
7066             if (ExtractedElts[Idx] == 0) {
7067               Instruction *Elt = 
7068                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7069               InsertNewInstBefore(Elt, CI);
7070               ExtractedElts[Idx] = Elt;
7071             }
7072           
7073             // Insert this value into the result vector.
7074             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7075             InsertNewInstBefore(cast<Instruction>(Result), CI);
7076           }
7077           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7078         }
7079       }
7080       break;
7081
7082     case Intrinsic::stackrestore: {
7083       // If the save is right next to the restore, remove the restore.  This can
7084       // happen when variable allocas are DCE'd.
7085       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7086         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7087           BasicBlock::iterator BI = SS;
7088           if (&*++BI == II)
7089             return EraseInstFromFunction(CI);
7090         }
7091       }
7092       
7093       // If the stack restore is in a return/unwind block and if there are no
7094       // allocas or calls between the restore and the return, nuke the restore.
7095       TerminatorInst *TI = II->getParent()->getTerminator();
7096       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7097         BasicBlock::iterator BI = II;
7098         bool CannotRemove = false;
7099         for (++BI; &*BI != TI; ++BI) {
7100           if (isa<AllocaInst>(BI) ||
7101               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7102             CannotRemove = true;
7103             break;
7104           }
7105         }
7106         if (!CannotRemove)
7107           return EraseInstFromFunction(CI);
7108       }
7109       break;
7110     }
7111     }
7112   }
7113
7114   return visitCallSite(II);
7115 }
7116
7117 // InvokeInst simplification
7118 //
7119 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7120   return visitCallSite(&II);
7121 }
7122
7123 // visitCallSite - Improvements for call and invoke instructions.
7124 //
7125 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7126   bool Changed = false;
7127
7128   // If the callee is a constexpr cast of a function, attempt to move the cast
7129   // to the arguments of the call/invoke.
7130   if (transformConstExprCastCall(CS)) return 0;
7131
7132   Value *Callee = CS.getCalledValue();
7133
7134   if (Function *CalleeF = dyn_cast<Function>(Callee))
7135     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7136       Instruction *OldCall = CS.getInstruction();
7137       // If the call and callee calling conventions don't match, this call must
7138       // be unreachable, as the call is undefined.
7139       new StoreInst(ConstantInt::getTrue(),
7140                     UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
7141       if (!OldCall->use_empty())
7142         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7143       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7144         return EraseInstFromFunction(*OldCall);
7145       return 0;
7146     }
7147
7148   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7149     // This instruction is not reachable, just remove it.  We insert a store to
7150     // undef so that we know that this code is not reachable, despite the fact
7151     // that we can't modify the CFG here.
7152     new StoreInst(ConstantInt::getTrue(),
7153                   UndefValue::get(PointerType::get(Type::Int1Ty)),
7154                   CS.getInstruction());
7155
7156     if (!CS.getInstruction()->use_empty())
7157       CS.getInstruction()->
7158         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7159
7160     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7161       // Don't break the CFG, insert a dummy cond branch.
7162       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7163                      ConstantInt::getTrue(), II);
7164     }
7165     return EraseInstFromFunction(*CS.getInstruction());
7166   }
7167
7168   const PointerType *PTy = cast<PointerType>(Callee->getType());
7169   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7170   if (FTy->isVarArg()) {
7171     // See if we can optimize any arguments passed through the varargs area of
7172     // the call.
7173     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7174            E = CS.arg_end(); I != E; ++I)
7175       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7176         // If this cast does not effect the value passed through the varargs
7177         // area, we can eliminate the use of the cast.
7178         Value *Op = CI->getOperand(0);
7179         if (CI->isLosslessCast()) {
7180           *I = Op;
7181           Changed = true;
7182         }
7183       }
7184   }
7185
7186   return Changed ? CS.getInstruction() : 0;
7187 }
7188
7189 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7190 // attempt to move the cast to the arguments of the call/invoke.
7191 //
7192 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7193   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7194   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7195   if (CE->getOpcode() != Instruction::BitCast || 
7196       !isa<Function>(CE->getOperand(0)))
7197     return false;
7198   Function *Callee = cast<Function>(CE->getOperand(0));
7199   Instruction *Caller = CS.getInstruction();
7200
7201   // Okay, this is a cast from a function to a different type.  Unless doing so
7202   // would cause a type conversion of one of our arguments, change this call to
7203   // be a direct call with arguments casted to the appropriate types.
7204   //
7205   const FunctionType *FT = Callee->getFunctionType();
7206   const Type *OldRetTy = Caller->getType();
7207
7208   // Check to see if we are changing the return type...
7209   if (OldRetTy != FT->getReturnType()) {
7210     if (Callee->isExternal() && !Caller->use_empty() && 
7211         OldRetTy != FT->getReturnType() &&
7212         // Conversion is ok if changing from pointer to int of same size.
7213         !(isa<PointerType>(FT->getReturnType()) &&
7214           TD->getIntPtrType() == OldRetTy))
7215       return false;   // Cannot transform this return value.
7216
7217     // If the callsite is an invoke instruction, and the return value is used by
7218     // a PHI node in a successor, we cannot change the return type of the call
7219     // because there is no place to put the cast instruction (without breaking
7220     // the critical edge).  Bail out in this case.
7221     if (!Caller->use_empty())
7222       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7223         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7224              UI != E; ++UI)
7225           if (PHINode *PN = dyn_cast<PHINode>(*UI))
7226             if (PN->getParent() == II->getNormalDest() ||
7227                 PN->getParent() == II->getUnwindDest())
7228               return false;
7229   }
7230
7231   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7232   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7233
7234   CallSite::arg_iterator AI = CS.arg_begin();
7235   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7236     const Type *ParamTy = FT->getParamType(i);
7237     const Type *ActTy = (*AI)->getType();
7238     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7239     //Either we can cast directly, or we can upconvert the argument
7240     bool isConvertible = ActTy == ParamTy ||
7241       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
7242       (ParamTy->isIntegral() && ActTy->isIntegral() &&
7243        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7244       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7245        && c->getSExtValue() > 0);
7246     if (Callee->isExternal() && !isConvertible) return false;
7247   }
7248
7249   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7250       Callee->isExternal())
7251     return false;   // Do not delete arguments unless we have a function body...
7252
7253   // Okay, we decided that this is a safe thing to do: go ahead and start
7254   // inserting cast instructions as necessary...
7255   std::vector<Value*> Args;
7256   Args.reserve(NumActualArgs);
7257
7258   AI = CS.arg_begin();
7259   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7260     const Type *ParamTy = FT->getParamType(i);
7261     if ((*AI)->getType() == ParamTy) {
7262       Args.push_back(*AI);
7263     } else {
7264       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7265           false, ParamTy, false);
7266       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7267       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7268     }
7269   }
7270
7271   // If the function takes more arguments than the call was taking, add them
7272   // now...
7273   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7274     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7275
7276   // If we are removing arguments to the function, emit an obnoxious warning...
7277   if (FT->getNumParams() < NumActualArgs)
7278     if (!FT->isVarArg()) {
7279       cerr << "WARNING: While resolving call to function '"
7280            << Callee->getName() << "' arguments were dropped!\n";
7281     } else {
7282       // Add all of the arguments in their promoted form to the arg list...
7283       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7284         const Type *PTy = getPromotedType((*AI)->getType());
7285         if (PTy != (*AI)->getType()) {
7286           // Must promote to pass through va_arg area!
7287           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
7288                                                                 PTy, false);
7289           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7290           InsertNewInstBefore(Cast, *Caller);
7291           Args.push_back(Cast);
7292         } else {
7293           Args.push_back(*AI);
7294         }
7295       }
7296     }
7297
7298   if (FT->getReturnType() == Type::VoidTy)
7299     Caller->setName("");   // Void type should not have a name...
7300
7301   Instruction *NC;
7302   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7303     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7304                         Args, Caller->getName(), Caller);
7305     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7306   } else {
7307     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
7308     if (cast<CallInst>(Caller)->isTailCall())
7309       cast<CallInst>(NC)->setTailCall();
7310    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7311   }
7312
7313   // Insert a cast of the return type as necessary...
7314   Value *NV = NC;
7315   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7316     if (NV->getType() != Type::VoidTy) {
7317       const Type *CallerTy = Caller->getType();
7318       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
7319                                                             CallerTy, false);
7320       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7321
7322       // If this is an invoke instruction, we should insert it after the first
7323       // non-phi, instruction in the normal successor block.
7324       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7325         BasicBlock::iterator I = II->getNormalDest()->begin();
7326         while (isa<PHINode>(I)) ++I;
7327         InsertNewInstBefore(NC, *I);
7328       } else {
7329         // Otherwise, it's a call, just insert cast right after the call instr
7330         InsertNewInstBefore(NC, *Caller);
7331       }
7332       AddUsersToWorkList(*Caller);
7333     } else {
7334       NV = UndefValue::get(Caller->getType());
7335     }
7336   }
7337
7338   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7339     Caller->replaceAllUsesWith(NV);
7340   Caller->getParent()->getInstList().erase(Caller);
7341   removeFromWorkList(Caller);
7342   return true;
7343 }
7344
7345 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7346 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7347 /// and a single binop.
7348 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7349   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7350   assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7351          isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
7352   unsigned Opc = FirstInst->getOpcode();
7353   Value *LHSVal = FirstInst->getOperand(0);
7354   Value *RHSVal = FirstInst->getOperand(1);
7355     
7356   const Type *LHSType = LHSVal->getType();
7357   const Type *RHSType = RHSVal->getType();
7358   
7359   // Scan to see if all operands are the same opcode, all have one use, and all
7360   // kill their operands (i.e. the operands have one use).
7361   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7362     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7363     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7364         // Verify type of the LHS matches so we don't fold cmp's of different
7365         // types or GEP's with different index types.
7366         I->getOperand(0)->getType() != LHSType ||
7367         I->getOperand(1)->getType() != RHSType)
7368       return 0;
7369
7370     // If they are CmpInst instructions, check their predicates
7371     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7372       if (cast<CmpInst>(I)->getPredicate() !=
7373           cast<CmpInst>(FirstInst)->getPredicate())
7374         return 0;
7375     
7376     // Keep track of which operand needs a phi node.
7377     if (I->getOperand(0) != LHSVal) LHSVal = 0;
7378     if (I->getOperand(1) != RHSVal) RHSVal = 0;
7379   }
7380   
7381   // Otherwise, this is safe to transform, determine if it is profitable.
7382
7383   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7384   // Indexes are often folded into load/store instructions, so we don't want to
7385   // hide them behind a phi.
7386   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7387     return 0;
7388   
7389   Value *InLHS = FirstInst->getOperand(0);
7390   Value *InRHS = FirstInst->getOperand(1);
7391   PHINode *NewLHS = 0, *NewRHS = 0;
7392   if (LHSVal == 0) {
7393     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7394     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7395     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7396     InsertNewInstBefore(NewLHS, PN);
7397     LHSVal = NewLHS;
7398   }
7399   
7400   if (RHSVal == 0) {
7401     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7402     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7403     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7404     InsertNewInstBefore(NewRHS, PN);
7405     RHSVal = NewRHS;
7406   }
7407   
7408   // Add all operands to the new PHIs.
7409   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7410     if (NewLHS) {
7411       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7412       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7413     }
7414     if (NewRHS) {
7415       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7416       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7417     }
7418   }
7419     
7420   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7421     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7422   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7423     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
7424                            RHSVal);
7425   else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7426     return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7427   else {
7428     assert(isa<GetElementPtrInst>(FirstInst));
7429     return new GetElementPtrInst(LHSVal, RHSVal);
7430   }
7431 }
7432
7433 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7434 /// of the block that defines it.  This means that it must be obvious the value
7435 /// of the load is not changed from the point of the load to the end of the
7436 /// block it is in.
7437 static bool isSafeToSinkLoad(LoadInst *L) {
7438   BasicBlock::iterator BBI = L, E = L->getParent()->end();
7439   
7440   for (++BBI; BBI != E; ++BBI)
7441     if (BBI->mayWriteToMemory())
7442       return false;
7443   return true;
7444 }
7445
7446
7447 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7448 // operator and they all are only used by the PHI, PHI together their
7449 // inputs, and do the operation once, to the result of the PHI.
7450 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7451   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7452
7453   // Scan the instruction, looking for input operations that can be folded away.
7454   // If all input operands to the phi are the same instruction (e.g. a cast from
7455   // the same type or "+42") we can pull the operation through the PHI, reducing
7456   // code size and simplifying code.
7457   Constant *ConstantOp = 0;
7458   const Type *CastSrcTy = 0;
7459   bool isVolatile = false;
7460   if (isa<CastInst>(FirstInst)) {
7461     CastSrcTy = FirstInst->getOperand(0)->getType();
7462   } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7463              isa<CmpInst>(FirstInst)) {
7464     // Can fold binop, compare or shift here if the RHS is a constant, 
7465     // otherwise call FoldPHIArgBinOpIntoPHI.
7466     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7467     if (ConstantOp == 0)
7468       return FoldPHIArgBinOpIntoPHI(PN);
7469   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7470     isVolatile = LI->isVolatile();
7471     // We can't sink the load if the loaded value could be modified between the
7472     // load and the PHI.
7473     if (LI->getParent() != PN.getIncomingBlock(0) ||
7474         !isSafeToSinkLoad(LI))
7475       return 0;
7476   } else if (isa<GetElementPtrInst>(FirstInst)) {
7477     if (FirstInst->getNumOperands() == 2)
7478       return FoldPHIArgBinOpIntoPHI(PN);
7479     // Can't handle general GEPs yet.
7480     return 0;
7481   } else {
7482     return 0;  // Cannot fold this operation.
7483   }
7484
7485   // Check to see if all arguments are the same operation.
7486   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7487     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7488     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7489     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
7490       return 0;
7491     if (CastSrcTy) {
7492       if (I->getOperand(0)->getType() != CastSrcTy)
7493         return 0;  // Cast operation must match.
7494     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7495       // We can't sink the load if the loaded value could be modified between 
7496       // the load and the PHI.
7497       if (LI->isVolatile() != isVolatile ||
7498           LI->getParent() != PN.getIncomingBlock(i) ||
7499           !isSafeToSinkLoad(LI))
7500         return 0;
7501     } else if (I->getOperand(1) != ConstantOp) {
7502       return 0;
7503     }
7504   }
7505
7506   // Okay, they are all the same operation.  Create a new PHI node of the
7507   // correct type, and PHI together all of the LHS's of the instructions.
7508   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7509                                PN.getName()+".in");
7510   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7511
7512   Value *InVal = FirstInst->getOperand(0);
7513   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7514
7515   // Add all operands to the new PHI.
7516   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7517     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7518     if (NewInVal != InVal)
7519       InVal = 0;
7520     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7521   }
7522
7523   Value *PhiVal;
7524   if (InVal) {
7525     // The new PHI unions all of the same values together.  This is really
7526     // common, so we handle it intelligently here for compile-time speed.
7527     PhiVal = InVal;
7528     delete NewPN;
7529   } else {
7530     InsertNewInstBefore(NewPN, PN);
7531     PhiVal = NewPN;
7532   }
7533
7534   // Insert and return the new operation.
7535   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7536     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7537   else if (isa<LoadInst>(FirstInst))
7538     return new LoadInst(PhiVal, "", isVolatile);
7539   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7540     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7541   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7542     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
7543                            PhiVal, ConstantOp);
7544   else
7545     return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
7546                          PhiVal, ConstantOp);
7547 }
7548
7549 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7550 /// that is dead.
7551 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7552   if (PN->use_empty()) return true;
7553   if (!PN->hasOneUse()) return false;
7554
7555   // Remember this node, and if we find the cycle, return.
7556   if (!PotentiallyDeadPHIs.insert(PN).second)
7557     return true;
7558
7559   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7560     return DeadPHICycle(PU, PotentiallyDeadPHIs);
7561
7562   return false;
7563 }
7564
7565 // PHINode simplification
7566 //
7567 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7568   // If LCSSA is around, don't mess with Phi nodes
7569   if (mustPreserveAnalysisID(LCSSAID)) return 0;
7570   
7571   if (Value *V = PN.hasConstantValue())
7572     return ReplaceInstUsesWith(PN, V);
7573
7574   // If all PHI operands are the same operation, pull them through the PHI,
7575   // reducing code size.
7576   if (isa<Instruction>(PN.getIncomingValue(0)) &&
7577       PN.getIncomingValue(0)->hasOneUse())
7578     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7579       return Result;
7580
7581   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
7582   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7583   // PHI)... break the cycle.
7584   if (PN.hasOneUse())
7585     if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7586       std::set<PHINode*> PotentiallyDeadPHIs;
7587       PotentiallyDeadPHIs.insert(&PN);
7588       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7589         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7590     }
7591
7592   return 0;
7593 }
7594
7595 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7596                                    Instruction *InsertPoint,
7597                                    InstCombiner *IC) {
7598   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7599   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
7600   // We must cast correctly to the pointer type. Ensure that we
7601   // sign extend the integer value if it is smaller as this is
7602   // used for address computation.
7603   Instruction::CastOps opcode = 
7604      (VTySize < PtrSize ? Instruction::SExt :
7605       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7606   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
7607 }
7608
7609
7610 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7611   Value *PtrOp = GEP.getOperand(0);
7612   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
7613   // If so, eliminate the noop.
7614   if (GEP.getNumOperands() == 1)
7615     return ReplaceInstUsesWith(GEP, PtrOp);
7616
7617   if (isa<UndefValue>(GEP.getOperand(0)))
7618     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7619
7620   bool HasZeroPointerIndex = false;
7621   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7622     HasZeroPointerIndex = C->isNullValue();
7623
7624   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7625     return ReplaceInstUsesWith(GEP, PtrOp);
7626
7627   // Eliminate unneeded casts for indices.
7628   bool MadeChange = false;
7629   gep_type_iterator GTI = gep_type_begin(GEP);
7630   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7631     if (isa<SequentialType>(*GTI)) {
7632       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7633         Value *Src = CI->getOperand(0);
7634         const Type *SrcTy = Src->getType();
7635         const Type *DestTy = CI->getType();
7636         if (Src->getType()->isInteger()) {
7637           if (SrcTy->getPrimitiveSizeInBits() ==
7638                        DestTy->getPrimitiveSizeInBits()) {
7639             // We can always eliminate a cast from ulong or long to the other.
7640             // We can always eliminate a cast from uint to int or the other on
7641             // 32-bit pointer platforms.
7642             if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
7643               MadeChange = true;
7644               GEP.setOperand(i, Src);
7645             }
7646           } else if (SrcTy->getPrimitiveSizeInBits() < 
7647                      DestTy->getPrimitiveSizeInBits() &&
7648                      SrcTy->getPrimitiveSizeInBits() == 32) {
7649             // We can eliminate a cast from [u]int to [u]long iff the target 
7650             // is a 32-bit pointer target.
7651             if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7652               MadeChange = true;
7653               GEP.setOperand(i, Src);
7654             }
7655           }
7656         }
7657       }
7658       // If we are using a wider index than needed for this platform, shrink it
7659       // to what we need.  If the incoming value needs a cast instruction,
7660       // insert it.  This explicit cast can make subsequent optimizations more
7661       // obvious.
7662       Value *Op = GEP.getOperand(i);
7663       if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
7664         if (Constant *C = dyn_cast<Constant>(Op)) {
7665           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
7666           MadeChange = true;
7667         } else {
7668           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7669                                 GEP);
7670           GEP.setOperand(i, Op);
7671           MadeChange = true;
7672         }
7673     }
7674   if (MadeChange) return &GEP;
7675
7676   // Combine Indices - If the source pointer to this getelementptr instruction
7677   // is a getelementptr instruction, combine the indices of the two
7678   // getelementptr instructions into a single instruction.
7679   //
7680   std::vector<Value*> SrcGEPOperands;
7681   if (User *Src = dyn_castGetElementPtr(PtrOp))
7682     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
7683
7684   if (!SrcGEPOperands.empty()) {
7685     // Note that if our source is a gep chain itself that we wait for that
7686     // chain to be resolved before we perform this transformation.  This
7687     // avoids us creating a TON of code in some cases.
7688     //
7689     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7690         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7691       return 0;   // Wait until our source is folded to completion.
7692
7693     std::vector<Value *> Indices;
7694
7695     // Find out whether the last index in the source GEP is a sequential idx.
7696     bool EndsWithSequential = false;
7697     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7698            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7699       EndsWithSequential = !isa<StructType>(*I);
7700
7701     // Can we combine the two pointer arithmetics offsets?
7702     if (EndsWithSequential) {
7703       // Replace: gep (gep %P, long B), long A, ...
7704       // With:    T = long A+B; gep %P, T, ...
7705       //
7706       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7707       if (SO1 == Constant::getNullValue(SO1->getType())) {
7708         Sum = GO1;
7709       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7710         Sum = SO1;
7711       } else {
7712         // If they aren't the same type, convert both to an integer of the
7713         // target's pointer size.
7714         if (SO1->getType() != GO1->getType()) {
7715           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7716             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
7717           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7718             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
7719           } else {
7720             unsigned PS = TD->getPointerSize();
7721             if (TD->getTypeSize(SO1->getType()) == PS) {
7722               // Convert GO1 to SO1's type.
7723               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
7724
7725             } else if (TD->getTypeSize(GO1->getType()) == PS) {
7726               // Convert SO1 to GO1's type.
7727               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
7728             } else {
7729               const Type *PT = TD->getIntPtrType();
7730               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7731               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
7732             }
7733           }
7734         }
7735         if (isa<Constant>(SO1) && isa<Constant>(GO1))
7736           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7737         else {
7738           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7739           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7740         }
7741       }
7742
7743       // Recycle the GEP we already have if possible.
7744       if (SrcGEPOperands.size() == 2) {
7745         GEP.setOperand(0, SrcGEPOperands[0]);
7746         GEP.setOperand(1, Sum);
7747         return &GEP;
7748       } else {
7749         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7750                        SrcGEPOperands.end()-1);
7751         Indices.push_back(Sum);
7752         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7753       }
7754     } else if (isa<Constant>(*GEP.idx_begin()) &&
7755                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7756                SrcGEPOperands.size() != 1) {
7757       // Otherwise we can do the fold if the first index of the GEP is a zero
7758       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7759                      SrcGEPOperands.end());
7760       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7761     }
7762
7763     if (!Indices.empty())
7764       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7765
7766   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7767     // GEP of global variable.  If all of the indices for this GEP are
7768     // constants, we can promote this to a constexpr instead of an instruction.
7769
7770     // Scan for nonconstants...
7771     std::vector<Constant*> Indices;
7772     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7773     for (; I != E && isa<Constant>(*I); ++I)
7774       Indices.push_back(cast<Constant>(*I));
7775
7776     if (I == E) {  // If they are all constants...
7777       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
7778
7779       // Replace all uses of the GEP with the new constexpr...
7780       return ReplaceInstUsesWith(GEP, CE);
7781     }
7782   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
7783     if (!isa<PointerType>(X->getType())) {
7784       // Not interesting.  Source pointer must be a cast from pointer.
7785     } else if (HasZeroPointerIndex) {
7786       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7787       // into     : GEP [10 x ubyte]* X, long 0, ...
7788       //
7789       // This occurs when the program declares an array extern like "int X[];"
7790       //
7791       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7792       const PointerType *XTy = cast<PointerType>(X->getType());
7793       if (const ArrayType *XATy =
7794           dyn_cast<ArrayType>(XTy->getElementType()))
7795         if (const ArrayType *CATy =
7796             dyn_cast<ArrayType>(CPTy->getElementType()))
7797           if (CATy->getElementType() == XATy->getElementType()) {
7798             // At this point, we know that the cast source type is a pointer
7799             // to an array of the same type as the destination pointer
7800             // array.  Because the array type is never stepped over (there
7801             // is a leading zero) we can fold the cast into this GEP.
7802             GEP.setOperand(0, X);
7803             return &GEP;
7804           }
7805     } else if (GEP.getNumOperands() == 2) {
7806       // Transform things like:
7807       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7808       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7809       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7810       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7811       if (isa<ArrayType>(SrcElTy) &&
7812           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7813           TD->getTypeSize(ResElTy)) {
7814         Value *V = InsertNewInstBefore(
7815                new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7816                                      GEP.getOperand(1), GEP.getName()), GEP);
7817         // V and GEP are both pointer types --> BitCast
7818         return new BitCastInst(V, GEP.getType());
7819       }
7820       
7821       // Transform things like:
7822       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7823       //   (where tmp = 8*tmp2) into:
7824       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7825       
7826       if (isa<ArrayType>(SrcElTy) &&
7827           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
7828         uint64_t ArrayEltSize =
7829             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7830         
7831         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
7832         // allow either a mul, shift, or constant here.
7833         Value *NewIdx = 0;
7834         ConstantInt *Scale = 0;
7835         if (ArrayEltSize == 1) {
7836           NewIdx = GEP.getOperand(1);
7837           Scale = ConstantInt::get(NewIdx->getType(), 1);
7838         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7839           NewIdx = ConstantInt::get(CI->getType(), 1);
7840           Scale = CI;
7841         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7842           if (Inst->getOpcode() == Instruction::Shl &&
7843               isa<ConstantInt>(Inst->getOperand(1))) {
7844             unsigned ShAmt =
7845               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7846             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7847             NewIdx = Inst->getOperand(0);
7848           } else if (Inst->getOpcode() == Instruction::Mul &&
7849                      isa<ConstantInt>(Inst->getOperand(1))) {
7850             Scale = cast<ConstantInt>(Inst->getOperand(1));
7851             NewIdx = Inst->getOperand(0);
7852           }
7853         }
7854
7855         // If the index will be to exactly the right offset with the scale taken
7856         // out, perform the transformation.
7857         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7858           if (isa<ConstantInt>(Scale))
7859             Scale = ConstantInt::get(Scale->getType(),
7860                                       Scale->getZExtValue() / ArrayEltSize);
7861           if (Scale->getZExtValue() != 1) {
7862             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7863                                                        true /*SExt*/);
7864             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7865             NewIdx = InsertNewInstBefore(Sc, GEP);
7866           }
7867
7868           // Insert the new GEP instruction.
7869           Instruction *NewGEP =
7870             new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7871                                   NewIdx, GEP.getName());
7872           NewGEP = InsertNewInstBefore(NewGEP, GEP);
7873           // The NewGEP must be pointer typed, so must the old one -> BitCast
7874           return new BitCastInst(NewGEP, GEP.getType());
7875         }
7876       }
7877     }
7878   }
7879
7880   return 0;
7881 }
7882
7883 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7884   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7885   if (AI.isArrayAllocation())    // Check C != 1
7886     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7887       const Type *NewTy = 
7888         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7889       AllocationInst *New = 0;
7890
7891       // Create and insert the replacement instruction...
7892       if (isa<MallocInst>(AI))
7893         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7894       else {
7895         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7896         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7897       }
7898
7899       InsertNewInstBefore(New, AI);
7900
7901       // Scan to the end of the allocation instructions, to skip over a block of
7902       // allocas if possible...
7903       //
7904       BasicBlock::iterator It = New;
7905       while (isa<AllocationInst>(*It)) ++It;
7906
7907       // Now that I is pointing to the first non-allocation-inst in the block,
7908       // insert our getelementptr instruction...
7909       //
7910       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
7911       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7912                                        New->getName()+".sub", It);
7913
7914       // Now make everything use the getelementptr instead of the original
7915       // allocation.
7916       return ReplaceInstUsesWith(AI, V);
7917     } else if (isa<UndefValue>(AI.getArraySize())) {
7918       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7919     }
7920
7921   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7922   // Note that we only do this for alloca's, because malloc should allocate and
7923   // return a unique pointer, even for a zero byte allocation.
7924   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7925       TD->getTypeSize(AI.getAllocatedType()) == 0)
7926     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7927
7928   return 0;
7929 }
7930
7931 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7932   Value *Op = FI.getOperand(0);
7933
7934   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7935   if (CastInst *CI = dyn_cast<CastInst>(Op))
7936     if (isa<PointerType>(CI->getOperand(0)->getType())) {
7937       FI.setOperand(0, CI->getOperand(0));
7938       return &FI;
7939     }
7940
7941   // free undef -> unreachable.
7942   if (isa<UndefValue>(Op)) {
7943     // Insert a new store to null because we cannot modify the CFG here.
7944     new StoreInst(ConstantInt::getTrue(),
7945                   UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
7946     return EraseInstFromFunction(FI);
7947   }
7948
7949   // If we have 'free null' delete the instruction.  This can happen in stl code
7950   // when lots of inlining happens.
7951   if (isa<ConstantPointerNull>(Op))
7952     return EraseInstFromFunction(FI);
7953
7954   return 0;
7955 }
7956
7957
7958 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7959 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7960   User *CI = cast<User>(LI.getOperand(0));
7961   Value *CastOp = CI->getOperand(0);
7962
7963   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7964   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7965     const Type *SrcPTy = SrcTy->getElementType();
7966
7967     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
7968         isa<PackedType>(DestPTy)) {
7969       // If the source is an array, the code below will not succeed.  Check to
7970       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
7971       // constants.
7972       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7973         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7974           if (ASrcTy->getNumElements() != 0) {
7975             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
7976             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7977             SrcTy = cast<PointerType>(CastOp->getType());
7978             SrcPTy = SrcTy->getElementType();
7979           }
7980
7981       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
7982            isa<PackedType>(SrcPTy)) &&
7983           // Do not allow turning this into a load of an integer, which is then
7984           // casted to a pointer, this pessimizes pointer analysis a lot.
7985           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
7986           IC.getTargetData().getTypeSize(SrcPTy) ==
7987                IC.getTargetData().getTypeSize(DestPTy)) {
7988
7989         // Okay, we are casting from one integer or pointer type to another of
7990         // the same size.  Instead of casting the pointer before the load, cast
7991         // the result of the loaded value.
7992         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7993                                                              CI->getName(),
7994                                                          LI.isVolatile()),LI);
7995         // Now cast the result of the load.
7996         return new BitCastInst(NewLoad, LI.getType());
7997       }
7998     }
7999   }
8000   return 0;
8001 }
8002
8003 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8004 /// from this value cannot trap.  If it is not obviously safe to load from the
8005 /// specified pointer, we do a quick local scan of the basic block containing
8006 /// ScanFrom, to determine if the address is already accessed.
8007 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8008   // If it is an alloca or global variable, it is always safe to load from.
8009   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8010
8011   // Otherwise, be a little bit agressive by scanning the local block where we
8012   // want to check to see if the pointer is already being loaded or stored
8013   // from/to.  If so, the previous load or store would have already trapped,
8014   // so there is no harm doing an extra load (also, CSE will later eliminate
8015   // the load entirely).
8016   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8017
8018   while (BBI != E) {
8019     --BBI;
8020
8021     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8022       if (LI->getOperand(0) == V) return true;
8023     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8024       if (SI->getOperand(1) == V) return true;
8025
8026   }
8027   return false;
8028 }
8029
8030 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8031   Value *Op = LI.getOperand(0);
8032
8033   // load (cast X) --> cast (load X) iff safe
8034   if (isa<CastInst>(Op))
8035     if (Instruction *Res = InstCombineLoadCast(*this, LI))
8036       return Res;
8037
8038   // None of the following transforms are legal for volatile loads.
8039   if (LI.isVolatile()) return 0;
8040   
8041   if (&LI.getParent()->front() != &LI) {
8042     BasicBlock::iterator BBI = &LI; --BBI;
8043     // If the instruction immediately before this is a store to the same
8044     // address, do a simple form of store->load forwarding.
8045     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8046       if (SI->getOperand(1) == LI.getOperand(0))
8047         return ReplaceInstUsesWith(LI, SI->getOperand(0));
8048     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8049       if (LIB->getOperand(0) == LI.getOperand(0))
8050         return ReplaceInstUsesWith(LI, LIB);
8051   }
8052
8053   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8054     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8055         isa<UndefValue>(GEPI->getOperand(0))) {
8056       // Insert a new store to null instruction before the load to indicate
8057       // that this code is not reachable.  We do this instead of inserting
8058       // an unreachable instruction directly because we cannot modify the
8059       // CFG.
8060       new StoreInst(UndefValue::get(LI.getType()),
8061                     Constant::getNullValue(Op->getType()), &LI);
8062       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8063     }
8064
8065   if (Constant *C = dyn_cast<Constant>(Op)) {
8066     // load null/undef -> undef
8067     if ((C->isNullValue() || isa<UndefValue>(C))) {
8068       // Insert a new store to null instruction before the load to indicate that
8069       // this code is not reachable.  We do this instead of inserting an
8070       // unreachable instruction directly because we cannot modify the CFG.
8071       new StoreInst(UndefValue::get(LI.getType()),
8072                     Constant::getNullValue(Op->getType()), &LI);
8073       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8074     }
8075
8076     // Instcombine load (constant global) into the value loaded.
8077     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8078       if (GV->isConstant() && !GV->isExternal())
8079         return ReplaceInstUsesWith(LI, GV->getInitializer());
8080
8081     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8082     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8083       if (CE->getOpcode() == Instruction::GetElementPtr) {
8084         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8085           if (GV->isConstant() && !GV->isExternal())
8086             if (Constant *V = 
8087                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8088               return ReplaceInstUsesWith(LI, V);
8089         if (CE->getOperand(0)->isNullValue()) {
8090           // Insert a new store to null instruction before the load to indicate
8091           // that this code is not reachable.  We do this instead of inserting
8092           // an unreachable instruction directly because we cannot modify the
8093           // CFG.
8094           new StoreInst(UndefValue::get(LI.getType()),
8095                         Constant::getNullValue(Op->getType()), &LI);
8096           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8097         }
8098
8099       } else if (CE->isCast()) {
8100         if (Instruction *Res = InstCombineLoadCast(*this, LI))
8101           return Res;
8102       }
8103   }
8104
8105   if (Op->hasOneUse()) {
8106     // Change select and PHI nodes to select values instead of addresses: this
8107     // helps alias analysis out a lot, allows many others simplifications, and
8108     // exposes redundancy in the code.
8109     //
8110     // Note that we cannot do the transformation unless we know that the
8111     // introduced loads cannot trap!  Something like this is valid as long as
8112     // the condition is always false: load (select bool %C, int* null, int* %G),
8113     // but it would not be valid if we transformed it to load from null
8114     // unconditionally.
8115     //
8116     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8117       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
8118       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8119           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8120         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8121                                      SI->getOperand(1)->getName()+".val"), LI);
8122         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8123                                      SI->getOperand(2)->getName()+".val"), LI);
8124         return new SelectInst(SI->getCondition(), V1, V2);
8125       }
8126
8127       // load (select (cond, null, P)) -> load P
8128       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8129         if (C->isNullValue()) {
8130           LI.setOperand(0, SI->getOperand(2));
8131           return &LI;
8132         }
8133
8134       // load (select (cond, P, null)) -> load P
8135       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8136         if (C->isNullValue()) {
8137           LI.setOperand(0, SI->getOperand(1));
8138           return &LI;
8139         }
8140     }
8141   }
8142   return 0;
8143 }
8144
8145 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8146 /// when possible.
8147 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8148   User *CI = cast<User>(SI.getOperand(1));
8149   Value *CastOp = CI->getOperand(0);
8150
8151   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8152   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8153     const Type *SrcPTy = SrcTy->getElementType();
8154
8155     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8156       // If the source is an array, the code below will not succeed.  Check to
8157       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8158       // constants.
8159       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8160         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8161           if (ASrcTy->getNumElements() != 0) {
8162             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
8163             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8164             SrcTy = cast<PointerType>(CastOp->getType());
8165             SrcPTy = SrcTy->getElementType();
8166           }
8167
8168       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8169           IC.getTargetData().getTypeSize(SrcPTy) ==
8170                IC.getTargetData().getTypeSize(DestPTy)) {
8171
8172         // Okay, we are casting from one integer or pointer type to another of
8173         // the same size.  Instead of casting the pointer before the store, cast
8174         // the value to be stored.
8175         Value *NewCast;
8176         Instruction::CastOps opcode = Instruction::BitCast;
8177         Value *SIOp0 = SI.getOperand(0);
8178         if (isa<PointerType>(SrcPTy)) {
8179           if (SIOp0->getType()->isIntegral())
8180             opcode = Instruction::IntToPtr;
8181         } else if (SrcPTy->isIntegral()) {
8182           if (isa<PointerType>(SIOp0->getType()))
8183             opcode = Instruction::PtrToInt;
8184         }
8185         if (Constant *C = dyn_cast<Constant>(SIOp0))
8186           NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
8187         else
8188           NewCast = IC.InsertNewInstBefore(
8189             CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
8190         return new StoreInst(NewCast, CastOp);
8191       }
8192     }
8193   }
8194   return 0;
8195 }
8196
8197 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8198   Value *Val = SI.getOperand(0);
8199   Value *Ptr = SI.getOperand(1);
8200
8201   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
8202     EraseInstFromFunction(SI);
8203     ++NumCombined;
8204     return 0;
8205   }
8206
8207   // Do really simple DSE, to catch cases where there are several consequtive
8208   // stores to the same location, separated by a few arithmetic operations. This
8209   // situation often occurs with bitfield accesses.
8210   BasicBlock::iterator BBI = &SI;
8211   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8212        --ScanInsts) {
8213     --BBI;
8214     
8215     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8216       // Prev store isn't volatile, and stores to the same location?
8217       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8218         ++NumDeadStore;
8219         ++BBI;
8220         EraseInstFromFunction(*PrevSI);
8221         continue;
8222       }
8223       break;
8224     }
8225     
8226     // If this is a load, we have to stop.  However, if the loaded value is from
8227     // the pointer we're loading and is producing the pointer we're storing,
8228     // then *this* store is dead (X = load P; store X -> P).
8229     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8230       if (LI == Val && LI->getOperand(0) == Ptr) {
8231         EraseInstFromFunction(SI);
8232         ++NumCombined;
8233         return 0;
8234       }
8235       // Otherwise, this is a load from some other location.  Stores before it
8236       // may not be dead.
8237       break;
8238     }
8239     
8240     // Don't skip over loads or things that can modify memory.
8241     if (BBI->mayWriteToMemory())
8242       break;
8243   }
8244   
8245   
8246   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
8247
8248   // store X, null    -> turns into 'unreachable' in SimplifyCFG
8249   if (isa<ConstantPointerNull>(Ptr)) {
8250     if (!isa<UndefValue>(Val)) {
8251       SI.setOperand(0, UndefValue::get(Val->getType()));
8252       if (Instruction *U = dyn_cast<Instruction>(Val))
8253         WorkList.push_back(U);  // Dropped a use.
8254       ++NumCombined;
8255     }
8256     return 0;  // Do not modify these!
8257   }
8258
8259   // store undef, Ptr -> noop
8260   if (isa<UndefValue>(Val)) {
8261     EraseInstFromFunction(SI);
8262     ++NumCombined;
8263     return 0;
8264   }
8265
8266   // If the pointer destination is a cast, see if we can fold the cast into the
8267   // source instead.
8268   if (isa<CastInst>(Ptr))
8269     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8270       return Res;
8271   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8272     if (CE->isCast())
8273       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8274         return Res;
8275
8276   
8277   // If this store is the last instruction in the basic block, and if the block
8278   // ends with an unconditional branch, try to move it to the successor block.
8279   BBI = &SI; ++BBI;
8280   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8281     if (BI->isUnconditional()) {
8282       // Check to see if the successor block has exactly two incoming edges.  If
8283       // so, see if the other predecessor contains a store to the same location.
8284       // if so, insert a PHI node (if needed) and move the stores down.
8285       BasicBlock *Dest = BI->getSuccessor(0);
8286
8287       pred_iterator PI = pred_begin(Dest);
8288       BasicBlock *Other = 0;
8289       if (*PI != BI->getParent())
8290         Other = *PI;
8291       ++PI;
8292       if (PI != pred_end(Dest)) {
8293         if (*PI != BI->getParent())
8294           if (Other)
8295             Other = 0;
8296           else
8297             Other = *PI;
8298         if (++PI != pred_end(Dest))
8299           Other = 0;
8300       }
8301       if (Other) {  // If only one other pred...
8302         BBI = Other->getTerminator();
8303         // Make sure this other block ends in an unconditional branch and that
8304         // there is an instruction before the branch.
8305         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8306             BBI != Other->begin()) {
8307           --BBI;
8308           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8309           
8310           // If this instruction is a store to the same location.
8311           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8312             // Okay, we know we can perform this transformation.  Insert a PHI
8313             // node now if we need it.
8314             Value *MergedVal = OtherStore->getOperand(0);
8315             if (MergedVal != SI.getOperand(0)) {
8316               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8317               PN->reserveOperandSpace(2);
8318               PN->addIncoming(SI.getOperand(0), SI.getParent());
8319               PN->addIncoming(OtherStore->getOperand(0), Other);
8320               MergedVal = InsertNewInstBefore(PN, Dest->front());
8321             }
8322             
8323             // Advance to a place where it is safe to insert the new store and
8324             // insert it.
8325             BBI = Dest->begin();
8326             while (isa<PHINode>(BBI)) ++BBI;
8327             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8328                                               OtherStore->isVolatile()), *BBI);
8329
8330             // Nuke the old stores.
8331             EraseInstFromFunction(SI);
8332             EraseInstFromFunction(*OtherStore);
8333             ++NumCombined;
8334             return 0;
8335           }
8336         }
8337       }
8338     }
8339   
8340   return 0;
8341 }
8342
8343
8344 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8345   // Change br (not X), label True, label False to: br X, label False, True
8346   Value *X = 0;
8347   BasicBlock *TrueDest;
8348   BasicBlock *FalseDest;
8349   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8350       !isa<Constant>(X)) {
8351     // Swap Destinations and condition...
8352     BI.setCondition(X);
8353     BI.setSuccessor(0, FalseDest);
8354     BI.setSuccessor(1, TrueDest);
8355     return &BI;
8356   }
8357
8358   // Cannonicalize fcmp_one -> fcmp_oeq
8359   FCmpInst::Predicate FPred; Value *Y;
8360   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
8361                              TrueDest, FalseDest)))
8362     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8363          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8364       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
8365       std::string Name = I->getName(); I->setName("");
8366       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8367       Value *NewSCC =  new FCmpInst(NewPred, X, Y, Name, I);
8368       // Swap Destinations and condition...
8369       BI.setCondition(NewSCC);
8370       BI.setSuccessor(0, FalseDest);
8371       BI.setSuccessor(1, TrueDest);
8372       removeFromWorkList(I);
8373       I->getParent()->getInstList().erase(I);
8374       WorkList.push_back(cast<Instruction>(NewSCC));
8375       return &BI;
8376     }
8377
8378   // Cannonicalize icmp_ne -> icmp_eq
8379   ICmpInst::Predicate IPred;
8380   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8381                       TrueDest, FalseDest)))
8382     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
8383          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8384          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8385       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8386       std::string Name = I->getName(); I->setName("");
8387       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8388       Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
8389       // Swap Destinations and condition...
8390       BI.setCondition(NewSCC);
8391       BI.setSuccessor(0, FalseDest);
8392       BI.setSuccessor(1, TrueDest);
8393       removeFromWorkList(I);
8394       I->getParent()->getInstList().erase(I);
8395       WorkList.push_back(cast<Instruction>(NewSCC));
8396       return &BI;
8397     }
8398
8399   return 0;
8400 }
8401
8402 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8403   Value *Cond = SI.getCondition();
8404   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8405     if (I->getOpcode() == Instruction::Add)
8406       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8407         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8408         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8409           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8410                                                 AddRHS));
8411         SI.setOperand(0, I->getOperand(0));
8412         WorkList.push_back(I);
8413         return &SI;
8414       }
8415   }
8416   return 0;
8417 }
8418
8419 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8420 /// is to leave as a vector operation.
8421 static bool CheapToScalarize(Value *V, bool isConstant) {
8422   if (isa<ConstantAggregateZero>(V)) 
8423     return true;
8424   if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8425     if (isConstant) return true;
8426     // If all elts are the same, we can extract.
8427     Constant *Op0 = C->getOperand(0);
8428     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8429       if (C->getOperand(i) != Op0)
8430         return false;
8431     return true;
8432   }
8433   Instruction *I = dyn_cast<Instruction>(V);
8434   if (!I) return false;
8435   
8436   // Insert element gets simplified to the inserted element or is deleted if
8437   // this is constant idx extract element and its a constant idx insertelt.
8438   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8439       isa<ConstantInt>(I->getOperand(2)))
8440     return true;
8441   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8442     return true;
8443   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8444     if (BO->hasOneUse() &&
8445         (CheapToScalarize(BO->getOperand(0), isConstant) ||
8446          CheapToScalarize(BO->getOperand(1), isConstant)))
8447       return true;
8448   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8449     if (CI->hasOneUse() &&
8450         (CheapToScalarize(CI->getOperand(0), isConstant) ||
8451          CheapToScalarize(CI->getOperand(1), isConstant)))
8452       return true;
8453   
8454   return false;
8455 }
8456
8457 /// getShuffleMask - Read and decode a shufflevector mask.  It turns undef
8458 /// elements into values that are larger than the #elts in the input.
8459 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8460   unsigned NElts = SVI->getType()->getNumElements();
8461   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8462     return std::vector<unsigned>(NElts, 0);
8463   if (isa<UndefValue>(SVI->getOperand(2)))
8464     return std::vector<unsigned>(NElts, 2*NElts);
8465
8466   std::vector<unsigned> Result;
8467   const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8468   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8469     if (isa<UndefValue>(CP->getOperand(i)))
8470       Result.push_back(NElts*2);  // undef -> 8
8471     else
8472       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8473   return Result;
8474 }
8475
8476 /// FindScalarElement - Given a vector and an element number, see if the scalar
8477 /// value is already around as a register, for example if it were inserted then
8478 /// extracted from the vector.
8479 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8480   assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8481   const PackedType *PTy = cast<PackedType>(V->getType());
8482   unsigned Width = PTy->getNumElements();
8483   if (EltNo >= Width)  // Out of range access.
8484     return UndefValue::get(PTy->getElementType());
8485   
8486   if (isa<UndefValue>(V))
8487     return UndefValue::get(PTy->getElementType());
8488   else if (isa<ConstantAggregateZero>(V))
8489     return Constant::getNullValue(PTy->getElementType());
8490   else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8491     return CP->getOperand(EltNo);
8492   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8493     // If this is an insert to a variable element, we don't know what it is.
8494     if (!isa<ConstantInt>(III->getOperand(2))) 
8495       return 0;
8496     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8497     
8498     // If this is an insert to the element we are looking for, return the
8499     // inserted value.
8500     if (EltNo == IIElt) 
8501       return III->getOperand(1);
8502     
8503     // Otherwise, the insertelement doesn't modify the value, recurse on its
8504     // vector input.
8505     return FindScalarElement(III->getOperand(0), EltNo);
8506   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8507     unsigned InEl = getShuffleMask(SVI)[EltNo];
8508     if (InEl < Width)
8509       return FindScalarElement(SVI->getOperand(0), InEl);
8510     else if (InEl < Width*2)
8511       return FindScalarElement(SVI->getOperand(1), InEl - Width);
8512     else
8513       return UndefValue::get(PTy->getElementType());
8514   }
8515   
8516   // Otherwise, we don't know.
8517   return 0;
8518 }
8519
8520 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8521
8522   // If packed val is undef, replace extract with scalar undef.
8523   if (isa<UndefValue>(EI.getOperand(0)))
8524     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8525
8526   // If packed val is constant 0, replace extract with scalar 0.
8527   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8528     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8529   
8530   if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8531     // If packed val is constant with uniform operands, replace EI
8532     // with that operand
8533     Constant *op0 = C->getOperand(0);
8534     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8535       if (C->getOperand(i) != op0) {
8536         op0 = 0; 
8537         break;
8538       }
8539     if (op0)
8540       return ReplaceInstUsesWith(EI, op0);
8541   }
8542   
8543   // If extracting a specified index from the vector, see if we can recursively
8544   // find a previously computed scalar that was inserted into the vector.
8545   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8546     // This instruction only demands the single element from the input vector.
8547     // If the input vector has a single use, simplify it based on this use
8548     // property.
8549     uint64_t IndexVal = IdxC->getZExtValue();
8550     if (EI.getOperand(0)->hasOneUse()) {
8551       uint64_t UndefElts;
8552       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8553                                                 1 << IndexVal,
8554                                                 UndefElts)) {
8555         EI.setOperand(0, V);
8556         return &EI;
8557       }
8558     }
8559     
8560     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8561       return ReplaceInstUsesWith(EI, Elt);
8562   }
8563   
8564   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8565     if (I->hasOneUse()) {
8566       // Push extractelement into predecessor operation if legal and
8567       // profitable to do so
8568       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8569         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8570         if (CheapToScalarize(BO, isConstantElt)) {
8571           ExtractElementInst *newEI0 = 
8572             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8573                                    EI.getName()+".lhs");
8574           ExtractElementInst *newEI1 =
8575             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8576                                    EI.getName()+".rhs");
8577           InsertNewInstBefore(newEI0, EI);
8578           InsertNewInstBefore(newEI1, EI);
8579           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8580         }
8581       } else if (isa<LoadInst>(I)) {
8582         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
8583                                       PointerType::get(EI.getType()), EI);
8584         GetElementPtrInst *GEP = 
8585           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8586         InsertNewInstBefore(GEP, EI);
8587         return new LoadInst(GEP);
8588       }
8589     }
8590     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8591       // Extracting the inserted element?
8592       if (IE->getOperand(2) == EI.getOperand(1))
8593         return ReplaceInstUsesWith(EI, IE->getOperand(1));
8594       // If the inserted and extracted elements are constants, they must not
8595       // be the same value, extract from the pre-inserted value instead.
8596       if (isa<Constant>(IE->getOperand(2)) &&
8597           isa<Constant>(EI.getOperand(1))) {
8598         AddUsesToWorkList(EI);
8599         EI.setOperand(0, IE->getOperand(0));
8600         return &EI;
8601       }
8602     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8603       // If this is extracting an element from a shufflevector, figure out where
8604       // it came from and extract from the appropriate input element instead.
8605       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8606         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8607         Value *Src;
8608         if (SrcIdx < SVI->getType()->getNumElements())
8609           Src = SVI->getOperand(0);
8610         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8611           SrcIdx -= SVI->getType()->getNumElements();
8612           Src = SVI->getOperand(1);
8613         } else {
8614           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8615         }
8616         return new ExtractElementInst(Src, SrcIdx);
8617       }
8618     }
8619   }
8620   return 0;
8621 }
8622
8623 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8624 /// elements from either LHS or RHS, return the shuffle mask and true. 
8625 /// Otherwise, return false.
8626 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8627                                          std::vector<Constant*> &Mask) {
8628   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8629          "Invalid CollectSingleShuffleElements");
8630   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8631
8632   if (isa<UndefValue>(V)) {
8633     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8634     return true;
8635   } else if (V == LHS) {
8636     for (unsigned i = 0; i != NumElts; ++i)
8637       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8638     return true;
8639   } else if (V == RHS) {
8640     for (unsigned i = 0; i != NumElts; ++i)
8641       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
8642     return true;
8643   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8644     // If this is an insert of an extract from some other vector, include it.
8645     Value *VecOp    = IEI->getOperand(0);
8646     Value *ScalarOp = IEI->getOperand(1);
8647     Value *IdxOp    = IEI->getOperand(2);
8648     
8649     if (!isa<ConstantInt>(IdxOp))
8650       return false;
8651     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8652     
8653     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
8654       // Okay, we can handle this if the vector we are insertinting into is
8655       // transitively ok.
8656       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8657         // If so, update the mask to reflect the inserted undef.
8658         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
8659         return true;
8660       }      
8661     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8662       if (isa<ConstantInt>(EI->getOperand(1)) &&
8663           EI->getOperand(0)->getType() == V->getType()) {
8664         unsigned ExtractedIdx =
8665           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8666         
8667         // This must be extracting from either LHS or RHS.
8668         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8669           // Okay, we can handle this if the vector we are insertinting into is
8670           // transitively ok.
8671           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8672             // If so, update the mask to reflect the inserted value.
8673             if (EI->getOperand(0) == LHS) {
8674               Mask[InsertedIdx & (NumElts-1)] = 
8675                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8676             } else {
8677               assert(EI->getOperand(0) == RHS);
8678               Mask[InsertedIdx & (NumElts-1)] = 
8679                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
8680               
8681             }
8682             return true;
8683           }
8684         }
8685       }
8686     }
8687   }
8688   // TODO: Handle shufflevector here!
8689   
8690   return false;
8691 }
8692
8693 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8694 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
8695 /// that computes V and the LHS value of the shuffle.
8696 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8697                                      Value *&RHS) {
8698   assert(isa<PackedType>(V->getType()) && 
8699          (RHS == 0 || V->getType() == RHS->getType()) &&
8700          "Invalid shuffle!");
8701   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8702
8703   if (isa<UndefValue>(V)) {
8704     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8705     return V;
8706   } else if (isa<ConstantAggregateZero>(V)) {
8707     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
8708     return V;
8709   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8710     // If this is an insert of an extract from some other vector, include it.
8711     Value *VecOp    = IEI->getOperand(0);
8712     Value *ScalarOp = IEI->getOperand(1);
8713     Value *IdxOp    = IEI->getOperand(2);
8714     
8715     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8716       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8717           EI->getOperand(0)->getType() == V->getType()) {
8718         unsigned ExtractedIdx =
8719           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8720         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8721         
8722         // Either the extracted from or inserted into vector must be RHSVec,
8723         // otherwise we'd end up with a shuffle of three inputs.
8724         if (EI->getOperand(0) == RHS || RHS == 0) {
8725           RHS = EI->getOperand(0);
8726           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8727           Mask[InsertedIdx & (NumElts-1)] = 
8728             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
8729           return V;
8730         }
8731         
8732         if (VecOp == RHS) {
8733           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8734           // Everything but the extracted element is replaced with the RHS.
8735           for (unsigned i = 0; i != NumElts; ++i) {
8736             if (i != InsertedIdx)
8737               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
8738           }
8739           return V;
8740         }
8741         
8742         // If this insertelement is a chain that comes from exactly these two
8743         // vectors, return the vector and the effective shuffle.
8744         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8745           return EI->getOperand(0);
8746         
8747       }
8748     }
8749   }
8750   // TODO: Handle shufflevector here!
8751   
8752   // Otherwise, can't do anything fancy.  Return an identity vector.
8753   for (unsigned i = 0; i != NumElts; ++i)
8754     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8755   return V;
8756 }
8757
8758 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8759   Value *VecOp    = IE.getOperand(0);
8760   Value *ScalarOp = IE.getOperand(1);
8761   Value *IdxOp    = IE.getOperand(2);
8762   
8763   // If the inserted element was extracted from some other vector, and if the 
8764   // indexes are constant, try to turn this into a shufflevector operation.
8765   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8766     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8767         EI->getOperand(0)->getType() == IE.getType()) {
8768       unsigned NumVectorElts = IE.getType()->getNumElements();
8769       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8770       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8771       
8772       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8773         return ReplaceInstUsesWith(IE, VecOp);
8774       
8775       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
8776         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8777       
8778       // If we are extracting a value from a vector, then inserting it right
8779       // back into the same place, just use the input vector.
8780       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8781         return ReplaceInstUsesWith(IE, VecOp);      
8782       
8783       // We could theoretically do this for ANY input.  However, doing so could
8784       // turn chains of insertelement instructions into a chain of shufflevector
8785       // instructions, and right now we do not merge shufflevectors.  As such,
8786       // only do this in a situation where it is clear that there is benefit.
8787       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8788         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
8789         // the values of VecOp, except then one read from EIOp0.
8790         // Build a new shuffle mask.
8791         std::vector<Constant*> Mask;
8792         if (isa<UndefValue>(VecOp))
8793           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
8794         else {
8795           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8796           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
8797                                                        NumVectorElts));
8798         } 
8799         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8800         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8801                                      ConstantPacked::get(Mask));
8802       }
8803       
8804       // If this insertelement isn't used by some other insertelement, turn it
8805       // (and any insertelements it points to), into one big shuffle.
8806       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8807         std::vector<Constant*> Mask;
8808         Value *RHS = 0;
8809         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8810         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8811         // We now have a shuffle of LHS, RHS, Mask.
8812         return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8813       }
8814     }
8815   }
8816
8817   return 0;
8818 }
8819
8820
8821 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8822   Value *LHS = SVI.getOperand(0);
8823   Value *RHS = SVI.getOperand(1);
8824   std::vector<unsigned> Mask = getShuffleMask(&SVI);
8825
8826   bool MadeChange = false;
8827   
8828   // Undefined shuffle mask -> undefined value.
8829   if (isa<UndefValue>(SVI.getOperand(2)))
8830     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8831   
8832   // If we have shuffle(x, undef, mask) and any elements of mask refer to
8833   // the undef, change them to undefs.
8834   if (isa<UndefValue>(SVI.getOperand(1))) {
8835     // Scan to see if there are any references to the RHS.  If so, replace them
8836     // with undef element refs and set MadeChange to true.
8837     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8838       if (Mask[i] >= e && Mask[i] != 2*e) {
8839         Mask[i] = 2*e;
8840         MadeChange = true;
8841       }
8842     }
8843     
8844     if (MadeChange) {
8845       // Remap any references to RHS to use LHS.
8846       std::vector<Constant*> Elts;
8847       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8848         if (Mask[i] == 2*e)
8849           Elts.push_back(UndefValue::get(Type::Int32Ty));
8850         else
8851           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8852       }
8853       SVI.setOperand(2, ConstantPacked::get(Elts));
8854     }
8855   }
8856   
8857   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
8858   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8859   if (LHS == RHS || isa<UndefValue>(LHS)) {
8860     if (isa<UndefValue>(LHS) && LHS == RHS) {
8861       // shuffle(undef,undef,mask) -> undef.
8862       return ReplaceInstUsesWith(SVI, LHS);
8863     }
8864     
8865     // Remap any references to RHS to use LHS.
8866     std::vector<Constant*> Elts;
8867     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8868       if (Mask[i] >= 2*e)
8869         Elts.push_back(UndefValue::get(Type::Int32Ty));
8870       else {
8871         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8872             (Mask[i] <  e && isa<UndefValue>(LHS)))
8873           Mask[i] = 2*e;     // Turn into undef.
8874         else
8875           Mask[i] &= (e-1);  // Force to LHS.
8876         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8877       }
8878     }
8879     SVI.setOperand(0, SVI.getOperand(1));
8880     SVI.setOperand(1, UndefValue::get(RHS->getType()));
8881     SVI.setOperand(2, ConstantPacked::get(Elts));
8882     LHS = SVI.getOperand(0);
8883     RHS = SVI.getOperand(1);
8884     MadeChange = true;
8885   }
8886   
8887   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8888   bool isLHSID = true, isRHSID = true;
8889     
8890   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8891     if (Mask[i] >= e*2) continue;  // Ignore undef values.
8892     // Is this an identity shuffle of the LHS value?
8893     isLHSID &= (Mask[i] == i);
8894       
8895     // Is this an identity shuffle of the RHS value?
8896     isRHSID &= (Mask[i]-e == i);
8897   }
8898
8899   // Eliminate identity shuffles.
8900   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8901   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8902   
8903   // If the LHS is a shufflevector itself, see if we can combine it with this
8904   // one without producing an unusual shuffle.  Here we are really conservative:
8905   // we are absolutely afraid of producing a shuffle mask not in the input
8906   // program, because the code gen may not be smart enough to turn a merged
8907   // shuffle into two specific shuffles: it may produce worse code.  As such,
8908   // we only merge two shuffles if the result is one of the two input shuffle
8909   // masks.  In this case, merging the shuffles just removes one instruction,
8910   // which we know is safe.  This is good for things like turning:
8911   // (splat(splat)) -> splat.
8912   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8913     if (isa<UndefValue>(RHS)) {
8914       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8915
8916       std::vector<unsigned> NewMask;
8917       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8918         if (Mask[i] >= 2*e)
8919           NewMask.push_back(2*e);
8920         else
8921           NewMask.push_back(LHSMask[Mask[i]]);
8922       
8923       // If the result mask is equal to the src shuffle or this shuffle mask, do
8924       // the replacement.
8925       if (NewMask == LHSMask || NewMask == Mask) {
8926         std::vector<Constant*> Elts;
8927         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8928           if (NewMask[i] >= e*2) {
8929             Elts.push_back(UndefValue::get(Type::Int32Ty));
8930           } else {
8931             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
8932           }
8933         }
8934         return new ShuffleVectorInst(LHSSVI->getOperand(0),
8935                                      LHSSVI->getOperand(1),
8936                                      ConstantPacked::get(Elts));
8937       }
8938     }
8939   }
8940   
8941   return MadeChange ? &SVI : 0;
8942 }
8943
8944
8945
8946 void InstCombiner::removeFromWorkList(Instruction *I) {
8947   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8948                  WorkList.end());
8949 }
8950
8951
8952 /// TryToSinkInstruction - Try to move the specified instruction from its
8953 /// current block into the beginning of DestBlock, which can only happen if it's
8954 /// safe to move the instruction past all of the instructions between it and the
8955 /// end of its block.
8956 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8957   assert(I->hasOneUse() && "Invariants didn't hold!");
8958
8959   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8960   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
8961
8962   // Do not sink alloca instructions out of the entry block.
8963   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8964     return false;
8965
8966   // We can only sink load instructions if there is nothing between the load and
8967   // the end of block that could change the value.
8968   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8969     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8970          Scan != E; ++Scan)
8971       if (Scan->mayWriteToMemory())
8972         return false;
8973   }
8974
8975   BasicBlock::iterator InsertPos = DestBlock->begin();
8976   while (isa<PHINode>(InsertPos)) ++InsertPos;
8977
8978   I->moveBefore(InsertPos);
8979   ++NumSunkInst;
8980   return true;
8981 }
8982
8983 /// OptimizeConstantExpr - Given a constant expression and target data layout
8984 /// information, symbolically evaluate the constant expr to something simpler
8985 /// if possible.
8986 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8987   if (!TD) return CE;
8988   
8989   Constant *Ptr = CE->getOperand(0);
8990   if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8991       cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8992     // If this is a constant expr gep that is effectively computing an
8993     // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8994     bool isFoldableGEP = true;
8995     for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8996       if (!isa<ConstantInt>(CE->getOperand(i)))
8997         isFoldableGEP = false;
8998     if (isFoldableGEP) {
8999       std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
9000       uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
9001       Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
9002       return ConstantExpr::getIntToPtr(C, CE->getType());
9003     }
9004   }
9005   
9006   return CE;
9007 }
9008
9009
9010 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9011 /// all reachable code to the worklist.
9012 ///
9013 /// This has a couple of tricks to make the code faster and more powerful.  In
9014 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9015 /// them to the worklist (this significantly speeds up instcombine on code where
9016 /// many instructions are dead or constant).  Additionally, if we find a branch
9017 /// whose condition is a known constant, we only visit the reachable successors.
9018 ///
9019 static void AddReachableCodeToWorklist(BasicBlock *BB, 
9020                                        std::set<BasicBlock*> &Visited,
9021                                        std::vector<Instruction*> &WorkList,
9022                                        const TargetData *TD) {
9023   // We have now visited this block!  If we've already been here, bail out.
9024   if (!Visited.insert(BB).second) return;
9025     
9026   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9027     Instruction *Inst = BBI++;
9028     
9029     // DCE instruction if trivially dead.
9030     if (isInstructionTriviallyDead(Inst)) {
9031       ++NumDeadInst;
9032       DOUT << "IC: DCE: " << *Inst;
9033       Inst->eraseFromParent();
9034       continue;
9035     }
9036     
9037     // ConstantProp instruction if trivially constant.
9038     if (Constant *C = ConstantFoldInstruction(Inst)) {
9039       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9040         C = OptimizeConstantExpr(CE, TD);
9041       DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9042       Inst->replaceAllUsesWith(C);
9043       ++NumConstProp;
9044       Inst->eraseFromParent();
9045       continue;
9046     }
9047     
9048     WorkList.push_back(Inst);
9049   }
9050
9051   // Recursively visit successors.  If this is a branch or switch on a constant,
9052   // only visit the reachable successor.
9053   TerminatorInst *TI = BB->getTerminator();
9054   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9055     if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9056       bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9057       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9058                                  TD);
9059       return;
9060     }
9061   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9062     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9063       // See if this is an explicit destination.
9064       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9065         if (SI->getCaseValue(i) == Cond) {
9066           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
9067           return;
9068         }
9069       
9070       // Otherwise it is the default destination.
9071       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
9072       return;
9073     }
9074   }
9075   
9076   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9077     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
9078 }
9079
9080 bool InstCombiner::runOnFunction(Function &F) {
9081   bool Changed = false;
9082   TD = &getAnalysis<TargetData>();
9083
9084   {
9085     // Do a depth-first traversal of the function, populate the worklist with
9086     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
9087     // track of which blocks we visit.
9088     std::set<BasicBlock*> Visited;
9089     AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
9090
9091     // Do a quick scan over the function.  If we find any blocks that are
9092     // unreachable, remove any instructions inside of them.  This prevents
9093     // the instcombine code from having to deal with some bad special cases.
9094     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9095       if (!Visited.count(BB)) {
9096         Instruction *Term = BB->getTerminator();
9097         while (Term != BB->begin()) {   // Remove instrs bottom-up
9098           BasicBlock::iterator I = Term; --I;
9099
9100           DOUT << "IC: DCE: " << *I;
9101           ++NumDeadInst;
9102
9103           if (!I->use_empty())
9104             I->replaceAllUsesWith(UndefValue::get(I->getType()));
9105           I->eraseFromParent();
9106         }
9107       }
9108   }
9109
9110   while (!WorkList.empty()) {
9111     Instruction *I = WorkList.back();  // Get an instruction from the worklist
9112     WorkList.pop_back();
9113
9114     // Check to see if we can DCE the instruction.
9115     if (isInstructionTriviallyDead(I)) {
9116       // Add operands to the worklist.
9117       if (I->getNumOperands() < 4)
9118         AddUsesToWorkList(*I);
9119       ++NumDeadInst;
9120
9121       DOUT << "IC: DCE: " << *I;
9122
9123       I->eraseFromParent();
9124       removeFromWorkList(I);
9125       continue;
9126     }
9127
9128     // Instruction isn't dead, see if we can constant propagate it.
9129     if (Constant *C = ConstantFoldInstruction(I)) {
9130       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9131         C = OptimizeConstantExpr(CE, TD);
9132       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9133
9134       // Add operands to the worklist.
9135       AddUsesToWorkList(*I);
9136       ReplaceInstUsesWith(*I, C);
9137
9138       ++NumConstProp;
9139       I->eraseFromParent();
9140       removeFromWorkList(I);
9141       continue;
9142     }
9143
9144     // See if we can trivially sink this instruction to a successor basic block.
9145     if (I->hasOneUse()) {
9146       BasicBlock *BB = I->getParent();
9147       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9148       if (UserParent != BB) {
9149         bool UserIsSuccessor = false;
9150         // See if the user is one of our successors.
9151         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9152           if (*SI == UserParent) {
9153             UserIsSuccessor = true;
9154             break;
9155           }
9156
9157         // If the user is one of our immediate successors, and if that successor
9158         // only has us as a predecessors (we'd have to split the critical edge
9159         // otherwise), we can keep going.
9160         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9161             next(pred_begin(UserParent)) == pred_end(UserParent))
9162           // Okay, the CFG is simple enough, try to sink this instruction.
9163           Changed |= TryToSinkInstruction(I, UserParent);
9164       }
9165     }
9166
9167     // Now that we have an instruction, try combining it to simplify it...
9168     if (Instruction *Result = visit(*I)) {
9169       ++NumCombined;
9170       // Should we replace the old instruction with a new one?
9171       if (Result != I) {
9172         DOUT << "IC: Old = " << *I
9173              << "    New = " << *Result;
9174
9175         // Everything uses the new instruction now.
9176         I->replaceAllUsesWith(Result);
9177
9178         // Push the new instruction and any users onto the worklist.
9179         WorkList.push_back(Result);
9180         AddUsersToWorkList(*Result);
9181
9182         // Move the name to the new instruction first...
9183         std::string OldName = I->getName(); I->setName("");
9184         Result->setName(OldName);
9185
9186         // Insert the new instruction into the basic block...
9187         BasicBlock *InstParent = I->getParent();
9188         BasicBlock::iterator InsertPos = I;
9189
9190         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
9191           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9192             ++InsertPos;
9193
9194         InstParent->getInstList().insert(InsertPos, Result);
9195
9196         // Make sure that we reprocess all operands now that we reduced their
9197         // use counts.
9198         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9199           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9200             WorkList.push_back(OpI);
9201
9202         // Instructions can end up on the worklist more than once.  Make sure
9203         // we do not process an instruction that has been deleted.
9204         removeFromWorkList(I);
9205
9206         // Erase the old instruction.
9207         InstParent->getInstList().erase(I);
9208       } else {
9209         DOUT << "IC: MOD = " << *I;
9210
9211         // If the instruction was modified, it's possible that it is now dead.
9212         // if so, remove it.
9213         if (isInstructionTriviallyDead(I)) {
9214           // Make sure we process all operands now that we are reducing their
9215           // use counts.
9216           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9217             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9218               WorkList.push_back(OpI);
9219
9220           // Instructions may end up in the worklist more than once.  Erase all
9221           // occurrences of this instruction.
9222           removeFromWorkList(I);
9223           I->eraseFromParent();
9224         } else {
9225           WorkList.push_back(Result);
9226           AddUsersToWorkList(*Result);
9227         }
9228       }
9229       Changed = true;
9230     }
9231   }
9232
9233   return Changed;
9234 }
9235
9236 FunctionPass *llvm::createInstructionCombiningPass() {
9237   return new InstCombiner();
9238 }
9239