Implement PR1345 and Transforms/InstCombine/bitcast-gep.ll
[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 i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/GetElementPtrTypeIterator.h"
49 #include "llvm/Support/InstVisitor.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/PatternMatch.h"
52 #include "llvm/Support/Compiler.h"
53 #include "llvm/ADT/DenseMap.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/SmallPtrSet.h"
56 #include "llvm/ADT/Statistic.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include <algorithm>
59 #include <sstream>
60 using namespace llvm;
61 using namespace llvm::PatternMatch;
62
63 STATISTIC(NumCombined , "Number of insts combined");
64 STATISTIC(NumConstProp, "Number of constant folds");
65 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
67 STATISTIC(NumSunkInst , "Number of instructions sunk");
68
69 namespace {
70   class VISIBILITY_HIDDEN InstCombiner
71     : public FunctionPass,
72       public InstVisitor<InstCombiner, Instruction*> {
73     // Worklist of all of the instructions that need to be simplified.
74     std::vector<Instruction*> Worklist;
75     DenseMap<Instruction*, unsigned> WorklistMap;
76     TargetData *TD;
77     bool MustPreserveLCSSA;
78   public:
79     /// AddToWorkList - Add the specified instruction to the worklist if it
80     /// isn't already in it.
81     void AddToWorkList(Instruction *I) {
82       if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
83         Worklist.push_back(I);
84     }
85     
86     // RemoveFromWorkList - remove I from the worklist if it exists.
87     void RemoveFromWorkList(Instruction *I) {
88       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
89       if (It == WorklistMap.end()) return; // Not in worklist.
90       
91       // Don't bother moving everything down, just null out the slot.
92       Worklist[It->second] = 0;
93       
94       WorklistMap.erase(It);
95     }
96     
97     Instruction *RemoveOneFromWorkList() {
98       Instruction *I = Worklist.back();
99       Worklist.pop_back();
100       WorklistMap.erase(I);
101       return I;
102     }
103
104     
105     /// AddUsersToWorkList - When an instruction is simplified, add all users of
106     /// the instruction to the work lists because they might get more simplified
107     /// now.
108     ///
109     void AddUsersToWorkList(Value &I) {
110       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
111            UI != UE; ++UI)
112         AddToWorkList(cast<Instruction>(*UI));
113     }
114
115     /// AddUsesToWorkList - When an instruction is simplified, add operands to
116     /// the work lists because they might get more simplified now.
117     ///
118     void AddUsesToWorkList(Instruction &I) {
119       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
120         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
121           AddToWorkList(Op);
122     }
123     
124     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
125     /// dead.  Add all of its operands to the worklist, turning them into
126     /// undef's to reduce the number of uses of those instructions.
127     ///
128     /// Return the specified operand before it is turned into an undef.
129     ///
130     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
131       Value *R = I.getOperand(op);
132       
133       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
134         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
135           AddToWorkList(Op);
136           // Set the operand to undef to drop the use.
137           I.setOperand(i, UndefValue::get(Op->getType()));
138         }
139       
140       return R;
141     }
142
143   public:
144     virtual bool runOnFunction(Function &F);
145     
146     bool DoOneIteration(Function &F, unsigned ItNum);
147
148     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
149       AU.addRequired<TargetData>();
150       AU.addPreservedID(LCSSAID);
151       AU.setPreservesCFG();
152     }
153
154     TargetData &getTargetData() const { return *TD; }
155
156     // Visitation implementation - Implement instruction combining for different
157     // instruction types.  The semantics are as follows:
158     // Return Value:
159     //    null        - No change was made
160     //     I          - Change was made, I is still valid, I may be dead though
161     //   otherwise    - Change was made, replace I with returned instruction
162     //
163     Instruction *visitAdd(BinaryOperator &I);
164     Instruction *visitSub(BinaryOperator &I);
165     Instruction *visitMul(BinaryOperator &I);
166     Instruction *visitURem(BinaryOperator &I);
167     Instruction *visitSRem(BinaryOperator &I);
168     Instruction *visitFRem(BinaryOperator &I);
169     Instruction *commonRemTransforms(BinaryOperator &I);
170     Instruction *commonIRemTransforms(BinaryOperator &I);
171     Instruction *commonDivTransforms(BinaryOperator &I);
172     Instruction *commonIDivTransforms(BinaryOperator &I);
173     Instruction *visitUDiv(BinaryOperator &I);
174     Instruction *visitSDiv(BinaryOperator &I);
175     Instruction *visitFDiv(BinaryOperator &I);
176     Instruction *visitAnd(BinaryOperator &I);
177     Instruction *visitOr (BinaryOperator &I);
178     Instruction *visitXor(BinaryOperator &I);
179     Instruction *visitShl(BinaryOperator &I);
180     Instruction *visitAShr(BinaryOperator &I);
181     Instruction *visitLShr(BinaryOperator &I);
182     Instruction *commonShiftTransforms(BinaryOperator &I);
183     Instruction *visitFCmpInst(FCmpInst &I);
184     Instruction *visitICmpInst(ICmpInst &I);
185     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
186     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
187                                                 Instruction *LHS,
188                                                 ConstantInt *RHS);
189
190     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
191                              ICmpInst::Predicate Cond, Instruction &I);
192     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
193                                      BinaryOperator &I);
194     Instruction *commonCastTransforms(CastInst &CI);
195     Instruction *commonIntCastTransforms(CastInst &CI);
196     Instruction *commonPointerCastTransforms(CastInst &CI);
197     Instruction *visitTrunc(TruncInst &CI);
198     Instruction *visitZExt(ZExtInst &CI);
199     Instruction *visitSExt(SExtInst &CI);
200     Instruction *visitFPTrunc(CastInst &CI);
201     Instruction *visitFPExt(CastInst &CI);
202     Instruction *visitFPToUI(CastInst &CI);
203     Instruction *visitFPToSI(CastInst &CI);
204     Instruction *visitUIToFP(CastInst &CI);
205     Instruction *visitSIToFP(CastInst &CI);
206     Instruction *visitPtrToInt(CastInst &CI);
207     Instruction *visitIntToPtr(CastInst &CI);
208     Instruction *visitBitCast(BitCastInst &CI);
209     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
210                                 Instruction *FI);
211     Instruction *visitSelectInst(SelectInst &CI);
212     Instruction *visitCallInst(CallInst &CI);
213     Instruction *visitInvokeInst(InvokeInst &II);
214     Instruction *visitPHINode(PHINode &PN);
215     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
216     Instruction *visitAllocationInst(AllocationInst &AI);
217     Instruction *visitFreeInst(FreeInst &FI);
218     Instruction *visitLoadInst(LoadInst &LI);
219     Instruction *visitStoreInst(StoreInst &SI);
220     Instruction *visitBranchInst(BranchInst &BI);
221     Instruction *visitSwitchInst(SwitchInst &SI);
222     Instruction *visitInsertElementInst(InsertElementInst &IE);
223     Instruction *visitExtractElementInst(ExtractElementInst &EI);
224     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
225
226     // visitInstruction - Specify what to return for unhandled instructions...
227     Instruction *visitInstruction(Instruction &I) { return 0; }
228
229   private:
230     Instruction *visitCallSite(CallSite CS);
231     bool transformConstExprCastCall(CallSite CS);
232
233   public:
234     // InsertNewInstBefore - insert an instruction New before instruction Old
235     // in the program.  Add the new instruction to the worklist.
236     //
237     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
238       assert(New && New->getParent() == 0 &&
239              "New instruction already inserted into a basic block!");
240       BasicBlock *BB = Old.getParent();
241       BB->getInstList().insert(&Old, New);  // Insert inst
242       AddToWorkList(New);
243       return New;
244     }
245
246     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
247     /// This also adds the cast to the worklist.  Finally, this returns the
248     /// cast.
249     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
250                             Instruction &Pos) {
251       if (V->getType() == Ty) return V;
252
253       if (Constant *CV = dyn_cast<Constant>(V))
254         return ConstantExpr::getCast(opc, CV, Ty);
255       
256       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
257       AddToWorkList(C);
258       return C;
259     }
260
261     // ReplaceInstUsesWith - This method is to be used when an instruction is
262     // found to be dead, replacable with another preexisting expression.  Here
263     // we add all uses of I to the worklist, replace all uses of I with the new
264     // value, then return I, so that the inst combiner will know that I was
265     // modified.
266     //
267     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
268       AddUsersToWorkList(I);         // Add all modified instrs to worklist
269       if (&I != V) {
270         I.replaceAllUsesWith(V);
271         return &I;
272       } else {
273         // If we are replacing the instruction with itself, this must be in a
274         // segment of unreachable code, so just clobber the instruction.
275         I.replaceAllUsesWith(UndefValue::get(I.getType()));
276         return &I;
277       }
278     }
279
280     // UpdateValueUsesWith - This method is to be used when an value is
281     // found to be replacable with another preexisting expression or was
282     // updated.  Here we add all uses of I to the worklist, replace all uses of
283     // I with the new value (unless the instruction was just updated), then
284     // return true, so that the inst combiner will know that I was modified.
285     //
286     bool UpdateValueUsesWith(Value *Old, Value *New) {
287       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
288       if (Old != New)
289         Old->replaceAllUsesWith(New);
290       if (Instruction *I = dyn_cast<Instruction>(Old))
291         AddToWorkList(I);
292       if (Instruction *I = dyn_cast<Instruction>(New))
293         AddToWorkList(I);
294       return true;
295     }
296     
297     // EraseInstFromFunction - When dealing with an instruction that has side
298     // effects or produces a void value, we can't rely on DCE to delete the
299     // instruction.  Instead, visit methods should return the value returned by
300     // this function.
301     Instruction *EraseInstFromFunction(Instruction &I) {
302       assert(I.use_empty() && "Cannot erase instruction that is used!");
303       AddUsesToWorkList(I);
304       RemoveFromWorkList(&I);
305       I.eraseFromParent();
306       return 0;  // Don't do anything with FI
307     }
308
309   private:
310     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
311     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
312     /// casts that are known to not do anything...
313     ///
314     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
315                                    Value *V, const Type *DestTy,
316                                    Instruction *InsertBefore);
317
318     /// SimplifyCommutative - This performs a few simplifications for 
319     /// commutative operators.
320     bool SimplifyCommutative(BinaryOperator &I);
321
322     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
323     /// most-complex to least-complex order.
324     bool SimplifyCompare(CmpInst &I);
325
326     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
327     /// on the demanded bits.
328     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
329                               APInt& KnownZero, APInt& KnownOne,
330                               unsigned Depth = 0);
331
332     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
333                                       uint64_t &UndefElts, unsigned Depth = 0);
334       
335     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
336     // PHI node as operand #0, see if we can fold the instruction into the PHI
337     // (which is only possible if all operands to the PHI are constants).
338     Instruction *FoldOpIntoPhi(Instruction &I);
339
340     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
341     // operator and they all are only used by the PHI, PHI together their
342     // inputs, and do the operation once, to the result of the PHI.
343     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
344     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
345     
346     
347     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
348                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
349     
350     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
351                               bool isSub, Instruction &I);
352     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
353                                  bool isSigned, bool Inside, Instruction &IB);
354     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
355     Instruction *MatchBSwap(BinaryOperator &I);
356     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
357
358     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
359   };
360
361   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
362 }
363
364 // getComplexity:  Assign a complexity or rank value to LLVM Values...
365 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
366 static unsigned getComplexity(Value *V) {
367   if (isa<Instruction>(V)) {
368     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
369       return 3;
370     return 4;
371   }
372   if (isa<Argument>(V)) return 3;
373   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
374 }
375
376 // isOnlyUse - Return true if this instruction will be deleted if we stop using
377 // it.
378 static bool isOnlyUse(Value *V) {
379   return V->hasOneUse() || isa<Constant>(V);
380 }
381
382 // getPromotedType - Return the specified type promoted as it would be to pass
383 // though a va_arg area...
384 static const Type *getPromotedType(const Type *Ty) {
385   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
386     if (ITy->getBitWidth() < 32)
387       return Type::Int32Ty;
388   } else if (Ty == Type::FloatTy)
389     return Type::DoubleTy;
390   return Ty;
391 }
392
393 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
394 /// expression bitcast,  return the operand value, otherwise return null.
395 static Value *getBitCastOperand(Value *V) {
396   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
397     return I->getOperand(0);
398   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
399     if (CE->getOpcode() == Instruction::BitCast)
400       return CE->getOperand(0);
401   return 0;
402 }
403
404 /// This function is a wrapper around CastInst::isEliminableCastPair. It
405 /// simply extracts arguments and returns what that function returns.
406 static Instruction::CastOps 
407 isEliminableCastPair(
408   const CastInst *CI, ///< The first cast instruction
409   unsigned opcode,       ///< The opcode of the second cast instruction
410   const Type *DstTy,     ///< The target type for the second cast instruction
411   TargetData *TD         ///< The target data for pointer size
412 ) {
413   
414   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
415   const Type *MidTy = CI->getType();                  // B from above
416
417   // Get the opcodes of the two Cast instructions
418   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
419   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
420
421   return Instruction::CastOps(
422       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
423                                      DstTy, TD->getIntPtrType()));
424 }
425
426 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
427 /// in any code being generated.  It does not require codegen if V is simple
428 /// enough or if the cast can be folded into other casts.
429 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
430                               const Type *Ty, TargetData *TD) {
431   if (V->getType() == Ty || isa<Constant>(V)) return false;
432   
433   // If this is another cast that can be eliminated, it isn't codegen either.
434   if (const CastInst *CI = dyn_cast<CastInst>(V))
435     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
436       return false;
437   return true;
438 }
439
440 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
441 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
442 /// casts that are known to not do anything...
443 ///
444 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
445                                              Value *V, const Type *DestTy,
446                                              Instruction *InsertBefore) {
447   if (V->getType() == DestTy) return V;
448   if (Constant *C = dyn_cast<Constant>(V))
449     return ConstantExpr::getCast(opcode, C, DestTy);
450   
451   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
452 }
453
454 // SimplifyCommutative - This performs a few simplifications for commutative
455 // operators:
456 //
457 //  1. Order operands such that they are listed from right (least complex) to
458 //     left (most complex).  This puts constants before unary operators before
459 //     binary operators.
460 //
461 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
462 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
463 //
464 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
465   bool Changed = false;
466   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
467     Changed = !I.swapOperands();
468
469   if (!I.isAssociative()) return Changed;
470   Instruction::BinaryOps Opcode = I.getOpcode();
471   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
472     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
473       if (isa<Constant>(I.getOperand(1))) {
474         Constant *Folded = ConstantExpr::get(I.getOpcode(),
475                                              cast<Constant>(I.getOperand(1)),
476                                              cast<Constant>(Op->getOperand(1)));
477         I.setOperand(0, Op->getOperand(0));
478         I.setOperand(1, Folded);
479         return true;
480       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
481         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
482             isOnlyUse(Op) && isOnlyUse(Op1)) {
483           Constant *C1 = cast<Constant>(Op->getOperand(1));
484           Constant *C2 = cast<Constant>(Op1->getOperand(1));
485
486           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
487           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
488           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
489                                                     Op1->getOperand(0),
490                                                     Op1->getName(), &I);
491           AddToWorkList(New);
492           I.setOperand(0, New);
493           I.setOperand(1, Folded);
494           return true;
495         }
496     }
497   return Changed;
498 }
499
500 /// SimplifyCompare - For a CmpInst this function just orders the operands
501 /// so that theyare listed from right (least complex) to left (most complex).
502 /// This puts constants before unary operators before binary operators.
503 bool InstCombiner::SimplifyCompare(CmpInst &I) {
504   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
505     return false;
506   I.swapOperands();
507   // Compare instructions are not associative so there's nothing else we can do.
508   return true;
509 }
510
511 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
512 // if the LHS is a constant zero (which is the 'negate' form).
513 //
514 static inline Value *dyn_castNegVal(Value *V) {
515   if (BinaryOperator::isNeg(V))
516     return BinaryOperator::getNegArgument(V);
517
518   // Constants can be considered to be negated values if they can be folded.
519   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
520     return ConstantExpr::getNeg(C);
521   return 0;
522 }
523
524 static inline Value *dyn_castNotVal(Value *V) {
525   if (BinaryOperator::isNot(V))
526     return BinaryOperator::getNotArgument(V);
527
528   // Constants can be considered to be not'ed values...
529   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
530     return ConstantInt::get(~C->getValue());
531   return 0;
532 }
533
534 // dyn_castFoldableMul - If this value is a multiply that can be folded into
535 // other computations (because it has a constant operand), return the
536 // non-constant operand of the multiply, and set CST to point to the multiplier.
537 // Otherwise, return null.
538 //
539 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
540   if (V->hasOneUse() && V->getType()->isInteger())
541     if (Instruction *I = dyn_cast<Instruction>(V)) {
542       if (I->getOpcode() == Instruction::Mul)
543         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
544           return I->getOperand(0);
545       if (I->getOpcode() == Instruction::Shl)
546         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
547           // The multiplier is really 1 << CST.
548           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
549           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
550           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
551           return I->getOperand(0);
552         }
553     }
554   return 0;
555 }
556
557 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
558 /// expression, return it.
559 static User *dyn_castGetElementPtr(Value *V) {
560   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
561   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
562     if (CE->getOpcode() == Instruction::GetElementPtr)
563       return cast<User>(V);
564   return false;
565 }
566
567 /// AddOne - Add one to a ConstantInt
568 static ConstantInt *AddOne(ConstantInt *C) {
569   APInt Val(C->getValue());
570   return ConstantInt::get(++Val);
571 }
572 /// SubOne - Subtract one from a ConstantInt
573 static ConstantInt *SubOne(ConstantInt *C) {
574   APInt Val(C->getValue());
575   return ConstantInt::get(--Val);
576 }
577 /// Add - Add two ConstantInts together
578 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
579   return ConstantInt::get(C1->getValue() + C2->getValue());
580 }
581 /// And - Bitwise AND two ConstantInts together
582 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
583   return ConstantInt::get(C1->getValue() & C2->getValue());
584 }
585 /// Subtract - Subtract one ConstantInt from another
586 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
587   return ConstantInt::get(C1->getValue() - C2->getValue());
588 }
589 /// Multiply - Multiply two ConstantInts together
590 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
591   return ConstantInt::get(C1->getValue() * C2->getValue());
592 }
593
594 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
595 /// known to be either zero or one and return them in the KnownZero/KnownOne
596 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
597 /// processing.
598 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
599 /// we cannot optimize based on the assumption that it is zero without changing
600 /// it to be an explicit zero.  If we don't change it to zero, other code could
601 /// optimized based on the contradictory assumption that it is non-zero.
602 /// Because instcombine aggressively folds operations with undef args anyway,
603 /// this won't lose us code quality.
604 static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero, 
605                               APInt& KnownOne, unsigned Depth = 0) {
606   assert(V && "No Value?");
607   assert(Depth <= 6 && "Limit Search Depth");
608   uint32_t BitWidth = Mask.getBitWidth();
609   assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
610          KnownZero.getBitWidth() == BitWidth && 
611          KnownOne.getBitWidth() == BitWidth &&
612          "V, Mask, KnownOne and KnownZero should have same BitWidth");
613   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
614     // We know all of the bits for a constant!
615     KnownOne = CI->getValue() & Mask;
616     KnownZero = ~KnownOne & Mask;
617     return;
618   }
619
620   if (Depth == 6 || Mask == 0)
621     return;  // Limit search depth.
622
623   Instruction *I = dyn_cast<Instruction>(V);
624   if (!I) return;
625
626   KnownZero.clear(); KnownOne.clear();   // Don't know anything.
627   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
628   
629   switch (I->getOpcode()) {
630   case Instruction::And: {
631     // If either the LHS or the RHS are Zero, the result is zero.
632     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
633     APInt Mask2(Mask & ~KnownZero);
634     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
635     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
636     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
637     
638     // Output known-1 bits are only known if set in both the LHS & RHS.
639     KnownOne &= KnownOne2;
640     // Output known-0 are known to be clear if zero in either the LHS | RHS.
641     KnownZero |= KnownZero2;
642     return;
643   }
644   case Instruction::Or: {
645     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
646     APInt Mask2(Mask & ~KnownOne);
647     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
648     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
649     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
650     
651     // Output known-0 bits are only known if clear in both the LHS & RHS.
652     KnownZero &= KnownZero2;
653     // Output known-1 are known to be set if set in either the LHS | RHS.
654     KnownOne |= KnownOne2;
655     return;
656   }
657   case Instruction::Xor: {
658     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
659     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
660     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
661     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
662     
663     // Output known-0 bits are known if clear or set in both the LHS & RHS.
664     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
665     // Output known-1 are known to be set if set in only one of the LHS, RHS.
666     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
667     KnownZero = KnownZeroOut;
668     return;
669   }
670   case Instruction::Select:
671     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
672     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
673     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
674     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
675
676     // Only known if known in both the LHS and RHS.
677     KnownOne &= KnownOne2;
678     KnownZero &= KnownZero2;
679     return;
680   case Instruction::FPTrunc:
681   case Instruction::FPExt:
682   case Instruction::FPToUI:
683   case Instruction::FPToSI:
684   case Instruction::SIToFP:
685   case Instruction::PtrToInt:
686   case Instruction::UIToFP:
687   case Instruction::IntToPtr:
688     return; // Can't work with floating point or pointers
689   case Instruction::Trunc: {
690     // All these have integer operands
691     uint32_t SrcBitWidth = 
692       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
693     APInt MaskIn(Mask);
694     MaskIn.zext(SrcBitWidth);
695     KnownZero.zext(SrcBitWidth);
696     KnownOne.zext(SrcBitWidth);
697     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
698     KnownZero.trunc(BitWidth);
699     KnownOne.trunc(BitWidth);
700     return;
701   }
702   case Instruction::BitCast: {
703     const Type *SrcTy = I->getOperand(0)->getType();
704     if (SrcTy->isInteger()) {
705       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
706       return;
707     }
708     break;
709   }
710   case Instruction::ZExt:  {
711     // Compute the bits in the result that are not present in the input.
712     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
713     uint32_t SrcBitWidth = SrcTy->getBitWidth();
714       
715     APInt MaskIn(Mask);
716     MaskIn.trunc(SrcBitWidth);
717     KnownZero.trunc(SrcBitWidth);
718     KnownOne.trunc(SrcBitWidth);
719     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
720     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
721     // The top bits are known to be zero.
722     KnownZero.zext(BitWidth);
723     KnownOne.zext(BitWidth);
724     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
725     return;
726   }
727   case Instruction::SExt: {
728     // Compute the bits in the result that are not present in the input.
729     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
730     uint32_t SrcBitWidth = SrcTy->getBitWidth();
731       
732     APInt MaskIn(Mask); 
733     MaskIn.trunc(SrcBitWidth);
734     KnownZero.trunc(SrcBitWidth);
735     KnownOne.trunc(SrcBitWidth);
736     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
737     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
738     KnownZero.zext(BitWidth);
739     KnownOne.zext(BitWidth);
740
741     // If the sign bit of the input is known set or clear, then we know the
742     // top bits of the result.
743     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
744       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
745     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
746       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
747     return;
748   }
749   case Instruction::Shl:
750     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
751     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
752       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
753       APInt Mask2(Mask.lshr(ShiftAmt));
754       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
755       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
756       KnownZero <<= ShiftAmt;
757       KnownOne  <<= ShiftAmt;
758       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
759       return;
760     }
761     break;
762   case Instruction::LShr:
763     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
764     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
765       // Compute the new bits that are at the top now.
766       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
767       
768       // Unsigned shift right.
769       APInt Mask2(Mask.shl(ShiftAmt));
770       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
771       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
772       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
773       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
774       // high bits known zero.
775       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
776       return;
777     }
778     break;
779   case Instruction::AShr:
780     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
781     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
782       // Compute the new bits that are at the top now.
783       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
784       
785       // Signed shift right.
786       APInt Mask2(Mask.shl(ShiftAmt));
787       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
788       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
789       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
790       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
791         
792       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
793       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
794         KnownZero |= HighBits;
795       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
796         KnownOne |= HighBits;
797       return;
798     }
799     break;
800   }
801 }
802
803 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
804 /// this predicate to simplify operations downstream.  Mask is known to be zero
805 /// for bits that V cannot have.
806 static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
807   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
808   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
809   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
810   return (KnownZero & Mask) == Mask;
811 }
812
813 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
814 /// specified instruction is a constant integer.  If so, check to see if there
815 /// are any bits set in the constant that are not demanded.  If so, shrink the
816 /// constant and return true.
817 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
818                                    APInt Demanded) {
819   assert(I && "No instruction?");
820   assert(OpNo < I->getNumOperands() && "Operand index too large");
821
822   // If the operand is not a constant integer, nothing to do.
823   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
824   if (!OpC) return false;
825
826   // If there are no bits set that aren't demanded, nothing to do.
827   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
828   if ((~Demanded & OpC->getValue()) == 0)
829     return false;
830
831   // This instruction is producing bits that are not demanded. Shrink the RHS.
832   Demanded &= OpC->getValue();
833   I->setOperand(OpNo, ConstantInt::get(Demanded));
834   return true;
835 }
836
837 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
838 // set of known zero and one bits, compute the maximum and minimum values that
839 // could have the specified known zero and known one bits, returning them in
840 // min/max.
841 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
842                                                    const APInt& KnownZero,
843                                                    const APInt& KnownOne,
844                                                    APInt& Min, APInt& Max) {
845   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
846   assert(KnownZero.getBitWidth() == BitWidth && 
847          KnownOne.getBitWidth() == BitWidth &&
848          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
849          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
850   APInt UnknownBits = ~(KnownZero|KnownOne);
851
852   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
853   // bit if it is unknown.
854   Min = KnownOne;
855   Max = KnownOne|UnknownBits;
856   
857   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
858     Min.set(BitWidth-1);
859     Max.clear(BitWidth-1);
860   }
861 }
862
863 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
864 // a set of known zero and one bits, compute the maximum and minimum values that
865 // could have the specified known zero and known one bits, returning them in
866 // min/max.
867 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
868                                                      const APInt& KnownZero,
869                                                      const APInt& KnownOne,
870                                                      APInt& Min,
871                                                      APInt& Max) {
872   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
873   assert(KnownZero.getBitWidth() == BitWidth && 
874          KnownOne.getBitWidth() == BitWidth &&
875          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
876          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
877   APInt UnknownBits = ~(KnownZero|KnownOne);
878   
879   // The minimum value is when the unknown bits are all zeros.
880   Min = KnownOne;
881   // The maximum value is when the unknown bits are all ones.
882   Max = KnownOne|UnknownBits;
883 }
884
885 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
886 /// value based on the demanded bits. When this function is called, it is known
887 /// that only the bits set in DemandedMask of the result of V are ever used
888 /// downstream. Consequently, depending on the mask and V, it may be possible
889 /// to replace V with a constant or one of its operands. In such cases, this
890 /// function does the replacement and returns true. In all other cases, it
891 /// returns false after analyzing the expression and setting KnownOne and known
892 /// to be one in the expression. KnownZero contains all the bits that are known
893 /// to be zero in the expression. These are provided to potentially allow the
894 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
895 /// the expression. KnownOne and KnownZero always follow the invariant that 
896 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
897 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
898 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
899 /// and KnownOne must all be the same.
900 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
901                                         APInt& KnownZero, APInt& KnownOne,
902                                         unsigned Depth) {
903   assert(V != 0 && "Null pointer of Value???");
904   assert(Depth <= 6 && "Limit Search Depth");
905   uint32_t BitWidth = DemandedMask.getBitWidth();
906   const IntegerType *VTy = cast<IntegerType>(V->getType());
907   assert(VTy->getBitWidth() == BitWidth && 
908          KnownZero.getBitWidth() == BitWidth && 
909          KnownOne.getBitWidth() == BitWidth &&
910          "Value *V, DemandedMask, KnownZero and KnownOne \
911           must have same BitWidth");
912   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
913     // We know all of the bits for a constant!
914     KnownOne = CI->getValue() & DemandedMask;
915     KnownZero = ~KnownOne & DemandedMask;
916     return false;
917   }
918   
919   KnownZero.clear(); 
920   KnownOne.clear();
921   if (!V->hasOneUse()) {    // Other users may use these bits.
922     if (Depth != 0) {       // Not at the root.
923       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
924       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
925       return false;
926     }
927     // If this is the root being simplified, allow it to have multiple uses,
928     // just set the DemandedMask to all bits.
929     DemandedMask = APInt::getAllOnesValue(BitWidth);
930   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
931     if (V != UndefValue::get(VTy))
932       return UpdateValueUsesWith(V, UndefValue::get(VTy));
933     return false;
934   } else if (Depth == 6) {        // Limit search depth.
935     return false;
936   }
937   
938   Instruction *I = dyn_cast<Instruction>(V);
939   if (!I) return false;        // Only analyze instructions.
940
941   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
942   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
943   switch (I->getOpcode()) {
944   default: break;
945   case Instruction::And:
946     // If either the LHS or the RHS are Zero, the result is zero.
947     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
948                              RHSKnownZero, RHSKnownOne, Depth+1))
949       return true;
950     assert((RHSKnownZero & RHSKnownOne) == 0 && 
951            "Bits known to be one AND zero?"); 
952
953     // If something is known zero on the RHS, the bits aren't demanded on the
954     // LHS.
955     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
956                              LHSKnownZero, LHSKnownOne, Depth+1))
957       return true;
958     assert((LHSKnownZero & LHSKnownOne) == 0 && 
959            "Bits known to be one AND zero?"); 
960
961     // If all of the demanded bits are known 1 on one side, return the other.
962     // These bits cannot contribute to the result of the 'and'.
963     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
964         (DemandedMask & ~LHSKnownZero))
965       return UpdateValueUsesWith(I, I->getOperand(0));
966     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
967         (DemandedMask & ~RHSKnownZero))
968       return UpdateValueUsesWith(I, I->getOperand(1));
969     
970     // If all of the demanded bits in the inputs are known zeros, return zero.
971     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
972       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
973       
974     // If the RHS is a constant, see if we can simplify it.
975     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
976       return UpdateValueUsesWith(I, I);
977       
978     // Output known-1 bits are only known if set in both the LHS & RHS.
979     RHSKnownOne &= LHSKnownOne;
980     // Output known-0 are known to be clear if zero in either the LHS | RHS.
981     RHSKnownZero |= LHSKnownZero;
982     break;
983   case Instruction::Or:
984     // If either the LHS or the RHS are One, the result is One.
985     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
986                              RHSKnownZero, RHSKnownOne, Depth+1))
987       return true;
988     assert((RHSKnownZero & RHSKnownOne) == 0 && 
989            "Bits known to be one AND zero?"); 
990     // If something is known one on the RHS, the bits aren't demanded on the
991     // LHS.
992     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
993                              LHSKnownZero, LHSKnownOne, Depth+1))
994       return true;
995     assert((LHSKnownZero & LHSKnownOne) == 0 && 
996            "Bits known to be one AND zero?"); 
997     
998     // If all of the demanded bits are known zero on one side, return the other.
999     // These bits cannot contribute to the result of the 'or'.
1000     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1001         (DemandedMask & ~LHSKnownOne))
1002       return UpdateValueUsesWith(I, I->getOperand(0));
1003     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1004         (DemandedMask & ~RHSKnownOne))
1005       return UpdateValueUsesWith(I, I->getOperand(1));
1006
1007     // If all of the potentially set bits on one side are known to be set on
1008     // the other side, just use the 'other' side.
1009     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1010         (DemandedMask & (~RHSKnownZero)))
1011       return UpdateValueUsesWith(I, I->getOperand(0));
1012     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1013         (DemandedMask & (~LHSKnownZero)))
1014       return UpdateValueUsesWith(I, I->getOperand(1));
1015         
1016     // If the RHS is a constant, see if we can simplify it.
1017     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1018       return UpdateValueUsesWith(I, I);
1019           
1020     // Output known-0 bits are only known if clear in both the LHS & RHS.
1021     RHSKnownZero &= LHSKnownZero;
1022     // Output known-1 are known to be set if set in either the LHS | RHS.
1023     RHSKnownOne |= LHSKnownOne;
1024     break;
1025   case Instruction::Xor: {
1026     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1027                              RHSKnownZero, RHSKnownOne, Depth+1))
1028       return true;
1029     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1030            "Bits known to be one AND zero?"); 
1031     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1032                              LHSKnownZero, LHSKnownOne, Depth+1))
1033       return true;
1034     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1035            "Bits known to be one AND zero?"); 
1036     
1037     // If all of the demanded bits are known zero on one side, return the other.
1038     // These bits cannot contribute to the result of the 'xor'.
1039     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1040       return UpdateValueUsesWith(I, I->getOperand(0));
1041     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1042       return UpdateValueUsesWith(I, I->getOperand(1));
1043     
1044     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1045     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1046                          (RHSKnownOne & LHSKnownOne);
1047     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1048     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1049                         (RHSKnownOne & LHSKnownZero);
1050     
1051     // If all of the demanded bits are known to be zero on one side or the
1052     // other, turn this into an *inclusive* or.
1053     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1054     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1055       Instruction *Or =
1056         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1057                                  I->getName());
1058       InsertNewInstBefore(Or, *I);
1059       return UpdateValueUsesWith(I, Or);
1060     }
1061     
1062     // If all of the demanded bits on one side are known, and all of the set
1063     // bits on that side are also known to be set on the other side, turn this
1064     // into an AND, as we know the bits will be cleared.
1065     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1066     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1067       // all known
1068       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1069         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1070         Instruction *And = 
1071           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1072         InsertNewInstBefore(And, *I);
1073         return UpdateValueUsesWith(I, And);
1074       }
1075     }
1076     
1077     // If the RHS is a constant, see if we can simplify it.
1078     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1079     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1080       return UpdateValueUsesWith(I, I);
1081     
1082     RHSKnownZero = KnownZeroOut;
1083     RHSKnownOne  = KnownOneOut;
1084     break;
1085   }
1086   case Instruction::Select:
1087     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1088                              RHSKnownZero, RHSKnownOne, Depth+1))
1089       return true;
1090     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1091                              LHSKnownZero, LHSKnownOne, Depth+1))
1092       return true;
1093     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1094            "Bits known to be one AND zero?"); 
1095     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1096            "Bits known to be one AND zero?"); 
1097     
1098     // If the operands are constants, see if we can simplify them.
1099     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1100       return UpdateValueUsesWith(I, I);
1101     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1102       return UpdateValueUsesWith(I, I);
1103     
1104     // Only known if known in both the LHS and RHS.
1105     RHSKnownOne &= LHSKnownOne;
1106     RHSKnownZero &= LHSKnownZero;
1107     break;
1108   case Instruction::Trunc: {
1109     uint32_t truncBf = 
1110       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1111     DemandedMask.zext(truncBf);
1112     RHSKnownZero.zext(truncBf);
1113     RHSKnownOne.zext(truncBf);
1114     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1115                              RHSKnownZero, RHSKnownOne, Depth+1))
1116       return true;
1117     DemandedMask.trunc(BitWidth);
1118     RHSKnownZero.trunc(BitWidth);
1119     RHSKnownOne.trunc(BitWidth);
1120     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1121            "Bits known to be one AND zero?"); 
1122     break;
1123   }
1124   case Instruction::BitCast:
1125     if (!I->getOperand(0)->getType()->isInteger())
1126       return false;
1127       
1128     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1129                              RHSKnownZero, RHSKnownOne, Depth+1))
1130       return true;
1131     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1132            "Bits known to be one AND zero?"); 
1133     break;
1134   case Instruction::ZExt: {
1135     // Compute the bits in the result that are not present in the input.
1136     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1137     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1138     
1139     DemandedMask.trunc(SrcBitWidth);
1140     RHSKnownZero.trunc(SrcBitWidth);
1141     RHSKnownOne.trunc(SrcBitWidth);
1142     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1143                              RHSKnownZero, RHSKnownOne, Depth+1))
1144       return true;
1145     DemandedMask.zext(BitWidth);
1146     RHSKnownZero.zext(BitWidth);
1147     RHSKnownOne.zext(BitWidth);
1148     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1149            "Bits known to be one AND zero?"); 
1150     // The top bits are known to be zero.
1151     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1152     break;
1153   }
1154   case Instruction::SExt: {
1155     // Compute the bits in the result that are not present in the input.
1156     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1157     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1158     
1159     APInt InputDemandedBits = DemandedMask & 
1160                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1161
1162     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1163     // If any of the sign extended bits are demanded, we know that the sign
1164     // bit is demanded.
1165     if ((NewBits & DemandedMask) != 0)
1166       InputDemandedBits.set(SrcBitWidth-1);
1167       
1168     InputDemandedBits.trunc(SrcBitWidth);
1169     RHSKnownZero.trunc(SrcBitWidth);
1170     RHSKnownOne.trunc(SrcBitWidth);
1171     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1172                              RHSKnownZero, RHSKnownOne, Depth+1))
1173       return true;
1174     InputDemandedBits.zext(BitWidth);
1175     RHSKnownZero.zext(BitWidth);
1176     RHSKnownOne.zext(BitWidth);
1177     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1178            "Bits known to be one AND zero?"); 
1179       
1180     // If the sign bit of the input is known set or clear, then we know the
1181     // top bits of the result.
1182
1183     // If the input sign bit is known zero, or if the NewBits are not demanded
1184     // convert this into a zero extension.
1185     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1186     {
1187       // Convert to ZExt cast
1188       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1189       return UpdateValueUsesWith(I, NewCast);
1190     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1191       RHSKnownOne |= NewBits;
1192     }
1193     break;
1194   }
1195   case Instruction::Add: {
1196     // Figure out what the input bits are.  If the top bits of the and result
1197     // are not demanded, then the add doesn't demand them from its input
1198     // either.
1199     uint32_t NLZ = DemandedMask.countLeadingZeros();
1200       
1201     // If there is a constant on the RHS, there are a variety of xformations
1202     // we can do.
1203     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1204       // If null, this should be simplified elsewhere.  Some of the xforms here
1205       // won't work if the RHS is zero.
1206       if (RHS->isZero())
1207         break;
1208       
1209       // If the top bit of the output is demanded, demand everything from the
1210       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1211       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1212
1213       // Find information about known zero/one bits in the input.
1214       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1215                                LHSKnownZero, LHSKnownOne, Depth+1))
1216         return true;
1217
1218       // If the RHS of the add has bits set that can't affect the input, reduce
1219       // the constant.
1220       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1221         return UpdateValueUsesWith(I, I);
1222       
1223       // Avoid excess work.
1224       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1225         break;
1226       
1227       // Turn it into OR if input bits are zero.
1228       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1229         Instruction *Or =
1230           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1231                                    I->getName());
1232         InsertNewInstBefore(Or, *I);
1233         return UpdateValueUsesWith(I, Or);
1234       }
1235       
1236       // We can say something about the output known-zero and known-one bits,
1237       // depending on potential carries from the input constant and the
1238       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1239       // bits set and the RHS constant is 0x01001, then we know we have a known
1240       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1241       
1242       // To compute this, we first compute the potential carry bits.  These are
1243       // the bits which may be modified.  I'm not aware of a better way to do
1244       // this scan.
1245       const APInt& RHSVal = RHS->getValue();
1246       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1247       
1248       // Now that we know which bits have carries, compute the known-1/0 sets.
1249       
1250       // Bits are known one if they are known zero in one operand and one in the
1251       // other, and there is no input carry.
1252       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1253                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1254       
1255       // Bits are known zero if they are known zero in both operands and there
1256       // is no input carry.
1257       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1258     } else {
1259       // If the high-bits of this ADD are not demanded, then it does not demand
1260       // the high bits of its LHS or RHS.
1261       if (DemandedMask[BitWidth-1] == 0) {
1262         // Right fill the mask of bits for this ADD to demand the most
1263         // significant bit and all those below it.
1264         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1265         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1266                                  LHSKnownZero, LHSKnownOne, Depth+1))
1267           return true;
1268         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1269                                  LHSKnownZero, LHSKnownOne, Depth+1))
1270           return true;
1271       }
1272     }
1273     break;
1274   }
1275   case Instruction::Sub:
1276     // If the high-bits of this SUB are not demanded, then it does not demand
1277     // the high bits of its LHS or RHS.
1278     if (DemandedMask[BitWidth-1] == 0) {
1279       // Right fill the mask of bits for this SUB to demand the most
1280       // significant bit and all those below it.
1281       uint32_t NLZ = DemandedMask.countLeadingZeros();
1282       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1283       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1284                                LHSKnownZero, LHSKnownOne, Depth+1))
1285         return true;
1286       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1287                                LHSKnownZero, LHSKnownOne, Depth+1))
1288         return true;
1289     }
1290     break;
1291   case Instruction::Shl:
1292     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1293       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1294       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1295       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1296                                RHSKnownZero, RHSKnownOne, Depth+1))
1297         return true;
1298       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1299              "Bits known to be one AND zero?"); 
1300       RHSKnownZero <<= ShiftAmt;
1301       RHSKnownOne  <<= ShiftAmt;
1302       // low bits known zero.
1303       if (ShiftAmt)
1304         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1305     }
1306     break;
1307   case Instruction::LShr:
1308     // For a logical shift right
1309     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1310       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1311       
1312       // Unsigned shift right.
1313       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1314       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1315                                RHSKnownZero, RHSKnownOne, Depth+1))
1316         return true;
1317       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1318              "Bits known to be one AND zero?"); 
1319       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1320       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1321       if (ShiftAmt) {
1322         // Compute the new bits that are at the top now.
1323         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1324         RHSKnownZero |= HighBits;  // high bits known zero.
1325       }
1326     }
1327     break;
1328   case Instruction::AShr:
1329     // If this is an arithmetic shift right and only the low-bit is set, we can
1330     // always convert this into a logical shr, even if the shift amount is
1331     // variable.  The low bit of the shift cannot be an input sign bit unless
1332     // the shift amount is >= the size of the datatype, which is undefined.
1333     if (DemandedMask == 1) {
1334       // Perform the logical shift right.
1335       Value *NewVal = BinaryOperator::createLShr(
1336                         I->getOperand(0), I->getOperand(1), I->getName());
1337       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1338       return UpdateValueUsesWith(I, NewVal);
1339     }    
1340     
1341     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1342       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1343       
1344       // Signed shift right.
1345       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1346       if (SimplifyDemandedBits(I->getOperand(0),
1347                                DemandedMaskIn,
1348                                RHSKnownZero, RHSKnownOne, Depth+1))
1349         return true;
1350       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1351              "Bits known to be one AND zero?"); 
1352       // Compute the new bits that are at the top now.
1353       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1354       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1355       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1356         
1357       // Handle the sign bits.
1358       APInt SignBit(APInt::getSignBit(BitWidth));
1359       // Adjust to where it is now in the mask.
1360       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1361         
1362       // If the input sign bit is known to be zero, or if none of the top bits
1363       // are demanded, turn this into an unsigned shift right.
1364       if (RHSKnownZero[BitWidth-ShiftAmt-1] || 
1365           (HighBits & ~DemandedMask) == HighBits) {
1366         // Perform the logical shift right.
1367         Value *NewVal = BinaryOperator::createLShr(
1368                           I->getOperand(0), SA, I->getName());
1369         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1370         return UpdateValueUsesWith(I, NewVal);
1371       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1372         RHSKnownOne |= HighBits;
1373       }
1374     }
1375     break;
1376   }
1377   
1378   // If the client is only demanding bits that we know, return the known
1379   // constant.
1380   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1381     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1382   return false;
1383 }
1384
1385
1386 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1387 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1388 /// actually used by the caller.  This method analyzes which elements of the
1389 /// operand are undef and returns that information in UndefElts.
1390 ///
1391 /// If the information about demanded elements can be used to simplify the
1392 /// operation, the operation is simplified, then the resultant value is
1393 /// returned.  This returns null if no change was made.
1394 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1395                                                 uint64_t &UndefElts,
1396                                                 unsigned Depth) {
1397   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1398   assert(VWidth <= 64 && "Vector too wide to analyze!");
1399   uint64_t EltMask = ~0ULL >> (64-VWidth);
1400   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1401          "Invalid DemandedElts!");
1402
1403   if (isa<UndefValue>(V)) {
1404     // If the entire vector is undefined, just return this info.
1405     UndefElts = EltMask;
1406     return 0;
1407   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1408     UndefElts = EltMask;
1409     return UndefValue::get(V->getType());
1410   }
1411   
1412   UndefElts = 0;
1413   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1414     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1415     Constant *Undef = UndefValue::get(EltTy);
1416
1417     std::vector<Constant*> Elts;
1418     for (unsigned i = 0; i != VWidth; ++i)
1419       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1420         Elts.push_back(Undef);
1421         UndefElts |= (1ULL << i);
1422       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1423         Elts.push_back(Undef);
1424         UndefElts |= (1ULL << i);
1425       } else {                               // Otherwise, defined.
1426         Elts.push_back(CP->getOperand(i));
1427       }
1428         
1429     // If we changed the constant, return it.
1430     Constant *NewCP = ConstantVector::get(Elts);
1431     return NewCP != CP ? NewCP : 0;
1432   } else if (isa<ConstantAggregateZero>(V)) {
1433     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1434     // set to undef.
1435     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1436     Constant *Zero = Constant::getNullValue(EltTy);
1437     Constant *Undef = UndefValue::get(EltTy);
1438     std::vector<Constant*> Elts;
1439     for (unsigned i = 0; i != VWidth; ++i)
1440       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1441     UndefElts = DemandedElts ^ EltMask;
1442     return ConstantVector::get(Elts);
1443   }
1444   
1445   if (!V->hasOneUse()) {    // Other users may use these bits.
1446     if (Depth != 0) {       // Not at the root.
1447       // TODO: Just compute the UndefElts information recursively.
1448       return false;
1449     }
1450     return false;
1451   } else if (Depth == 10) {        // Limit search depth.
1452     return false;
1453   }
1454   
1455   Instruction *I = dyn_cast<Instruction>(V);
1456   if (!I) return false;        // Only analyze instructions.
1457   
1458   bool MadeChange = false;
1459   uint64_t UndefElts2;
1460   Value *TmpV;
1461   switch (I->getOpcode()) {
1462   default: break;
1463     
1464   case Instruction::InsertElement: {
1465     // If this is a variable index, we don't know which element it overwrites.
1466     // demand exactly the same input as we produce.
1467     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1468     if (Idx == 0) {
1469       // Note that we can't propagate undef elt info, because we don't know
1470       // which elt is getting updated.
1471       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1472                                         UndefElts2, Depth+1);
1473       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1474       break;
1475     }
1476     
1477     // If this is inserting an element that isn't demanded, remove this
1478     // insertelement.
1479     unsigned IdxNo = Idx->getZExtValue();
1480     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1481       return AddSoonDeadInstToWorklist(*I, 0);
1482     
1483     // Otherwise, the element inserted overwrites whatever was there, so the
1484     // input demanded set is simpler than the output set.
1485     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1486                                       DemandedElts & ~(1ULL << IdxNo),
1487                                       UndefElts, Depth+1);
1488     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1489
1490     // The inserted element is defined.
1491     UndefElts |= 1ULL << IdxNo;
1492     break;
1493   }
1494   case Instruction::BitCast: {
1495     // Packed->packed casts only.
1496     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1497     if (!VTy) break;
1498     unsigned InVWidth = VTy->getNumElements();
1499     uint64_t InputDemandedElts = 0;
1500     unsigned Ratio;
1501
1502     if (VWidth == InVWidth) {
1503       // If we are converting from <4x i32> -> <4 x f32>, we demand the same
1504       // elements as are demanded of us.
1505       Ratio = 1;
1506       InputDemandedElts = DemandedElts;
1507     } else if (VWidth > InVWidth) {
1508       // Untested so far.
1509       break;
1510       
1511       // If there are more elements in the result than there are in the source,
1512       // then an input element is live if any of the corresponding output
1513       // elements are live.
1514       Ratio = VWidth/InVWidth;
1515       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1516         if (DemandedElts & (1ULL << OutIdx))
1517           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1518       }
1519     } else {
1520       // Untested so far.
1521       break;
1522       
1523       // If there are more elements in the source than there are in the result,
1524       // then an input element is live if the corresponding output element is
1525       // live.
1526       Ratio = InVWidth/VWidth;
1527       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1528         if (DemandedElts & (1ULL << InIdx/Ratio))
1529           InputDemandedElts |= 1ULL << InIdx;
1530     }
1531     
1532     // div/rem demand all inputs, because they don't want divide by zero.
1533     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1534                                       UndefElts2, Depth+1);
1535     if (TmpV) {
1536       I->setOperand(0, TmpV);
1537       MadeChange = true;
1538     }
1539     
1540     UndefElts = UndefElts2;
1541     if (VWidth > InVWidth) {
1542       assert(0 && "Unimp");
1543       // If there are more elements in the result than there are in the source,
1544       // then an output element is undef if the corresponding input element is
1545       // undef.
1546       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1547         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1548           UndefElts |= 1ULL << OutIdx;
1549     } else if (VWidth < InVWidth) {
1550       assert(0 && "Unimp");
1551       // If there are more elements in the source than there are in the result,
1552       // then a result element is undef if all of the corresponding input
1553       // elements are undef.
1554       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1555       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1556         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1557           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1558     }
1559     break;
1560   }
1561   case Instruction::And:
1562   case Instruction::Or:
1563   case Instruction::Xor:
1564   case Instruction::Add:
1565   case Instruction::Sub:
1566   case Instruction::Mul:
1567     // div/rem demand all inputs, because they don't want divide by zero.
1568     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1569                                       UndefElts, Depth+1);
1570     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1571     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1572                                       UndefElts2, Depth+1);
1573     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1574       
1575     // Output elements are undefined if both are undefined.  Consider things
1576     // like undef&0.  The result is known zero, not undef.
1577     UndefElts &= UndefElts2;
1578     break;
1579     
1580   case Instruction::Call: {
1581     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1582     if (!II) break;
1583     switch (II->getIntrinsicID()) {
1584     default: break;
1585       
1586     // Binary vector operations that work column-wise.  A dest element is a
1587     // function of the corresponding input elements from the two inputs.
1588     case Intrinsic::x86_sse_sub_ss:
1589     case Intrinsic::x86_sse_mul_ss:
1590     case Intrinsic::x86_sse_min_ss:
1591     case Intrinsic::x86_sse_max_ss:
1592     case Intrinsic::x86_sse2_sub_sd:
1593     case Intrinsic::x86_sse2_mul_sd:
1594     case Intrinsic::x86_sse2_min_sd:
1595     case Intrinsic::x86_sse2_max_sd:
1596       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1597                                         UndefElts, Depth+1);
1598       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1599       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1600                                         UndefElts2, Depth+1);
1601       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1602
1603       // If only the low elt is demanded and this is a scalarizable intrinsic,
1604       // scalarize it now.
1605       if (DemandedElts == 1) {
1606         switch (II->getIntrinsicID()) {
1607         default: break;
1608         case Intrinsic::x86_sse_sub_ss:
1609         case Intrinsic::x86_sse_mul_ss:
1610         case Intrinsic::x86_sse2_sub_sd:
1611         case Intrinsic::x86_sse2_mul_sd:
1612           // TODO: Lower MIN/MAX/ABS/etc
1613           Value *LHS = II->getOperand(1);
1614           Value *RHS = II->getOperand(2);
1615           // Extract the element as scalars.
1616           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1617           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1618           
1619           switch (II->getIntrinsicID()) {
1620           default: assert(0 && "Case stmts out of sync!");
1621           case Intrinsic::x86_sse_sub_ss:
1622           case Intrinsic::x86_sse2_sub_sd:
1623             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1624                                                         II->getName()), *II);
1625             break;
1626           case Intrinsic::x86_sse_mul_ss:
1627           case Intrinsic::x86_sse2_mul_sd:
1628             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1629                                                          II->getName()), *II);
1630             break;
1631           }
1632           
1633           Instruction *New =
1634             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1635                                   II->getName());
1636           InsertNewInstBefore(New, *II);
1637           AddSoonDeadInstToWorklist(*II, 0);
1638           return New;
1639         }            
1640       }
1641         
1642       // Output elements are undefined if both are undefined.  Consider things
1643       // like undef&0.  The result is known zero, not undef.
1644       UndefElts &= UndefElts2;
1645       break;
1646     }
1647     break;
1648   }
1649   }
1650   return MadeChange ? I : 0;
1651 }
1652
1653 /// @returns true if the specified compare instruction is
1654 /// true when both operands are equal...
1655 /// @brief Determine if the ICmpInst returns true if both operands are equal
1656 static bool isTrueWhenEqual(ICmpInst &ICI) {
1657   ICmpInst::Predicate pred = ICI.getPredicate();
1658   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1659          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1660          pred == ICmpInst::ICMP_SLE;
1661 }
1662
1663 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1664 /// function is designed to check a chain of associative operators for a
1665 /// potential to apply a certain optimization.  Since the optimization may be
1666 /// applicable if the expression was reassociated, this checks the chain, then
1667 /// reassociates the expression as necessary to expose the optimization
1668 /// opportunity.  This makes use of a special Functor, which must define
1669 /// 'shouldApply' and 'apply' methods.
1670 ///
1671 template<typename Functor>
1672 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1673   unsigned Opcode = Root.getOpcode();
1674   Value *LHS = Root.getOperand(0);
1675
1676   // Quick check, see if the immediate LHS matches...
1677   if (F.shouldApply(LHS))
1678     return F.apply(Root);
1679
1680   // Otherwise, if the LHS is not of the same opcode as the root, return.
1681   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1682   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1683     // Should we apply this transform to the RHS?
1684     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1685
1686     // If not to the RHS, check to see if we should apply to the LHS...
1687     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1688       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1689       ShouldApply = true;
1690     }
1691
1692     // If the functor wants to apply the optimization to the RHS of LHSI,
1693     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1694     if (ShouldApply) {
1695       BasicBlock *BB = Root.getParent();
1696
1697       // Now all of the instructions are in the current basic block, go ahead
1698       // and perform the reassociation.
1699       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1700
1701       // First move the selected RHS to the LHS of the root...
1702       Root.setOperand(0, LHSI->getOperand(1));
1703
1704       // Make what used to be the LHS of the root be the user of the root...
1705       Value *ExtraOperand = TmpLHSI->getOperand(1);
1706       if (&Root == TmpLHSI) {
1707         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1708         return 0;
1709       }
1710       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1711       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1712       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1713       BasicBlock::iterator ARI = &Root; ++ARI;
1714       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1715       ARI = Root;
1716
1717       // Now propagate the ExtraOperand down the chain of instructions until we
1718       // get to LHSI.
1719       while (TmpLHSI != LHSI) {
1720         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1721         // Move the instruction to immediately before the chain we are
1722         // constructing to avoid breaking dominance properties.
1723         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1724         BB->getInstList().insert(ARI, NextLHSI);
1725         ARI = NextLHSI;
1726
1727         Value *NextOp = NextLHSI->getOperand(1);
1728         NextLHSI->setOperand(1, ExtraOperand);
1729         TmpLHSI = NextLHSI;
1730         ExtraOperand = NextOp;
1731       }
1732
1733       // Now that the instructions are reassociated, have the functor perform
1734       // the transformation...
1735       return F.apply(Root);
1736     }
1737
1738     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1739   }
1740   return 0;
1741 }
1742
1743
1744 // AddRHS - Implements: X + X --> X << 1
1745 struct AddRHS {
1746   Value *RHS;
1747   AddRHS(Value *rhs) : RHS(rhs) {}
1748   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1749   Instruction *apply(BinaryOperator &Add) const {
1750     return BinaryOperator::createShl(Add.getOperand(0),
1751                                   ConstantInt::get(Add.getType(), 1));
1752   }
1753 };
1754
1755 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1756 //                 iff C1&C2 == 0
1757 struct AddMaskingAnd {
1758   Constant *C2;
1759   AddMaskingAnd(Constant *c) : C2(c) {}
1760   bool shouldApply(Value *LHS) const {
1761     ConstantInt *C1;
1762     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1763            ConstantExpr::getAnd(C1, C2)->isNullValue();
1764   }
1765   Instruction *apply(BinaryOperator &Add) const {
1766     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1767   }
1768 };
1769
1770 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1771                                              InstCombiner *IC) {
1772   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1773     if (Constant *SOC = dyn_cast<Constant>(SO))
1774       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1775
1776     return IC->InsertNewInstBefore(CastInst::create(
1777           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1778   }
1779
1780   // Figure out if the constant is the left or the right argument.
1781   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1782   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1783
1784   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1785     if (ConstIsRHS)
1786       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1787     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1788   }
1789
1790   Value *Op0 = SO, *Op1 = ConstOperand;
1791   if (!ConstIsRHS)
1792     std::swap(Op0, Op1);
1793   Instruction *New;
1794   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1795     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1796   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1797     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1798                           SO->getName()+".cmp");
1799   else {
1800     assert(0 && "Unknown binary instruction type!");
1801     abort();
1802   }
1803   return IC->InsertNewInstBefore(New, I);
1804 }
1805
1806 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1807 // constant as the other operand, try to fold the binary operator into the
1808 // select arguments.  This also works for Cast instructions, which obviously do
1809 // not have a second operand.
1810 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1811                                      InstCombiner *IC) {
1812   // Don't modify shared select instructions
1813   if (!SI->hasOneUse()) return 0;
1814   Value *TV = SI->getOperand(1);
1815   Value *FV = SI->getOperand(2);
1816
1817   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1818     // Bool selects with constant operands can be folded to logical ops.
1819     if (SI->getType() == Type::Int1Ty) return 0;
1820
1821     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1822     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1823
1824     return new SelectInst(SI->getCondition(), SelectTrueVal,
1825                           SelectFalseVal);
1826   }
1827   return 0;
1828 }
1829
1830
1831 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1832 /// node as operand #0, see if we can fold the instruction into the PHI (which
1833 /// is only possible if all operands to the PHI are constants).
1834 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1835   PHINode *PN = cast<PHINode>(I.getOperand(0));
1836   unsigned NumPHIValues = PN->getNumIncomingValues();
1837   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1838
1839   // Check to see if all of the operands of the PHI are constants.  If there is
1840   // one non-constant value, remember the BB it is.  If there is more than one
1841   // or if *it* is a PHI, bail out.
1842   BasicBlock *NonConstBB = 0;
1843   for (unsigned i = 0; i != NumPHIValues; ++i)
1844     if (!isa<Constant>(PN->getIncomingValue(i))) {
1845       if (NonConstBB) return 0;  // More than one non-const value.
1846       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1847       NonConstBB = PN->getIncomingBlock(i);
1848       
1849       // If the incoming non-constant value is in I's block, we have an infinite
1850       // loop.
1851       if (NonConstBB == I.getParent())
1852         return 0;
1853     }
1854   
1855   // If there is exactly one non-constant value, we can insert a copy of the
1856   // operation in that block.  However, if this is a critical edge, we would be
1857   // inserting the computation one some other paths (e.g. inside a loop).  Only
1858   // do this if the pred block is unconditionally branching into the phi block.
1859   if (NonConstBB) {
1860     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1861     if (!BI || !BI->isUnconditional()) return 0;
1862   }
1863
1864   // Okay, we can do the transformation: create the new PHI node.
1865   PHINode *NewPN = new PHINode(I.getType(), "");
1866   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1867   InsertNewInstBefore(NewPN, *PN);
1868   NewPN->takeName(PN);
1869
1870   // Next, add all of the operands to the PHI.
1871   if (I.getNumOperands() == 2) {
1872     Constant *C = cast<Constant>(I.getOperand(1));
1873     for (unsigned i = 0; i != NumPHIValues; ++i) {
1874       Value *InV;
1875       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1876         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1877           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1878         else
1879           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1880       } else {
1881         assert(PN->getIncomingBlock(i) == NonConstBB);
1882         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1883           InV = BinaryOperator::create(BO->getOpcode(),
1884                                        PN->getIncomingValue(i), C, "phitmp",
1885                                        NonConstBB->getTerminator());
1886         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1887           InV = CmpInst::create(CI->getOpcode(), 
1888                                 CI->getPredicate(),
1889                                 PN->getIncomingValue(i), C, "phitmp",
1890                                 NonConstBB->getTerminator());
1891         else
1892           assert(0 && "Unknown binop!");
1893         
1894         AddToWorkList(cast<Instruction>(InV));
1895       }
1896       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1897     }
1898   } else { 
1899     CastInst *CI = cast<CastInst>(&I);
1900     const Type *RetTy = CI->getType();
1901     for (unsigned i = 0; i != NumPHIValues; ++i) {
1902       Value *InV;
1903       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1904         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1905       } else {
1906         assert(PN->getIncomingBlock(i) == NonConstBB);
1907         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1908                                I.getType(), "phitmp", 
1909                                NonConstBB->getTerminator());
1910         AddToWorkList(cast<Instruction>(InV));
1911       }
1912       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1913     }
1914   }
1915   return ReplaceInstUsesWith(I, NewPN);
1916 }
1917
1918 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1919   bool Changed = SimplifyCommutative(I);
1920   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1921
1922   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1923     // X + undef -> undef
1924     if (isa<UndefValue>(RHS))
1925       return ReplaceInstUsesWith(I, RHS);
1926
1927     // X + 0 --> X
1928     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1929       if (RHSC->isNullValue())
1930         return ReplaceInstUsesWith(I, LHS);
1931     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1932       if (CFP->isExactlyValue(-0.0))
1933         return ReplaceInstUsesWith(I, LHS);
1934     }
1935
1936     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1937       // X + (signbit) --> X ^ signbit
1938       const APInt& Val = CI->getValue();
1939       uint32_t BitWidth = Val.getBitWidth();
1940       if (Val == APInt::getSignBit(BitWidth))
1941         return BinaryOperator::createXor(LHS, RHS);
1942       
1943       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1944       // (X & 254)+1 -> (X&254)|1
1945       if (!isa<VectorType>(I.getType())) {
1946         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1947         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1948                                  KnownZero, KnownOne))
1949           return &I;
1950       }
1951     }
1952
1953     if (isa<PHINode>(LHS))
1954       if (Instruction *NV = FoldOpIntoPhi(I))
1955         return NV;
1956     
1957     ConstantInt *XorRHS = 0;
1958     Value *XorLHS = 0;
1959     if (isa<ConstantInt>(RHSC) &&
1960         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1961       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1962       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1963       
1964       uint32_t Size = TySizeBits / 2;
1965       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1966       APInt CFF80Val(-C0080Val);
1967       do {
1968         if (TySizeBits > Size) {
1969           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1970           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1971           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1972               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1973             // This is a sign extend if the top bits are known zero.
1974             if (!MaskedValueIsZero(XorLHS, 
1975                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1976               Size = 0;  // Not a sign ext, but can't be any others either.
1977             break;
1978           }
1979         }
1980         Size >>= 1;
1981         C0080Val = APIntOps::lshr(C0080Val, Size);
1982         CFF80Val = APIntOps::ashr(CFF80Val, Size);
1983       } while (Size >= 1);
1984       
1985       // FIXME: This shouldn't be necessary. When the backends can handle types
1986       // with funny bit widths then this whole cascade of if statements should
1987       // be removed. It is just here to get the size of the "middle" type back
1988       // up to something that the back ends can handle.
1989       const Type *MiddleType = 0;
1990       switch (Size) {
1991         default: break;
1992         case 32: MiddleType = Type::Int32Ty; break;
1993         case 16: MiddleType = Type::Int16Ty; break;
1994         case  8: MiddleType = Type::Int8Ty; break;
1995       }
1996       if (MiddleType) {
1997         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1998         InsertNewInstBefore(NewTrunc, I);
1999         return new SExtInst(NewTrunc, I.getType(), I.getName());
2000       }
2001     }
2002   }
2003
2004   // X + X --> X << 1
2005   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2006     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2007
2008     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2009       if (RHSI->getOpcode() == Instruction::Sub)
2010         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2011           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2012     }
2013     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2014       if (LHSI->getOpcode() == Instruction::Sub)
2015         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2016           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2017     }
2018   }
2019
2020   // -A + B  -->  B - A
2021   if (Value *V = dyn_castNegVal(LHS))
2022     return BinaryOperator::createSub(RHS, V);
2023
2024   // A + -B  -->  A - B
2025   if (!isa<Constant>(RHS))
2026     if (Value *V = dyn_castNegVal(RHS))
2027       return BinaryOperator::createSub(LHS, V);
2028
2029
2030   ConstantInt *C2;
2031   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2032     if (X == RHS)   // X*C + X --> X * (C+1)
2033       return BinaryOperator::createMul(RHS, AddOne(C2));
2034
2035     // X*C1 + X*C2 --> X * (C1+C2)
2036     ConstantInt *C1;
2037     if (X == dyn_castFoldableMul(RHS, C1))
2038       return BinaryOperator::createMul(X, Add(C1, C2));
2039   }
2040
2041   // X + X*C --> X * (C+1)
2042   if (dyn_castFoldableMul(RHS, C2) == LHS)
2043     return BinaryOperator::createMul(LHS, AddOne(C2));
2044
2045   // X + ~X --> -1   since   ~X = -X-1
2046   if (dyn_castNotVal(LHS) == RHS ||
2047       dyn_castNotVal(RHS) == LHS)
2048     return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2049   
2050
2051   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2052   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2053     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2054       return R;
2055
2056   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2057     Value *X = 0;
2058     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2059       return BinaryOperator::createSub(SubOne(CRHS), X);
2060
2061     // (X & FF00) + xx00  -> (X+xx00) & FF00
2062     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2063       Constant *Anded = And(CRHS, C2);
2064       if (Anded == CRHS) {
2065         // See if all bits from the first bit set in the Add RHS up are included
2066         // in the mask.  First, get the rightmost bit.
2067         const APInt& AddRHSV = CRHS->getValue();
2068
2069         // Form a mask of all bits from the lowest bit added through the top.
2070         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2071
2072         // See if the and mask includes all of these bits.
2073         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2074
2075         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2076           // Okay, the xform is safe.  Insert the new add pronto.
2077           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2078                                                             LHS->getName()), I);
2079           return BinaryOperator::createAnd(NewAdd, C2);
2080         }
2081       }
2082     }
2083
2084     // Try to fold constant add into select arguments.
2085     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2086       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2087         return R;
2088   }
2089
2090   // add (cast *A to intptrtype) B -> 
2091   //   cast (GEP (cast *A to sbyte*) B) -> 
2092   //     intptrtype
2093   {
2094     CastInst *CI = dyn_cast<CastInst>(LHS);
2095     Value *Other = RHS;
2096     if (!CI) {
2097       CI = dyn_cast<CastInst>(RHS);
2098       Other = LHS;
2099     }
2100     if (CI && CI->getType()->isSized() && 
2101         (CI->getType()->getPrimitiveSizeInBits() == 
2102          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2103         && isa<PointerType>(CI->getOperand(0)->getType())) {
2104       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
2105                                    PointerType::get(Type::Int8Ty), I);
2106       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2107       return new PtrToIntInst(I2, CI->getType());
2108     }
2109   }
2110
2111   return Changed ? &I : 0;
2112 }
2113
2114 // isSignBit - Return true if the value represented by the constant only has the
2115 // highest order bit set.
2116 static bool isSignBit(ConstantInt *CI) {
2117   uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2118   return CI->getValue() == APInt::getSignBit(NumBits);
2119 }
2120
2121 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2122   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2123
2124   if (Op0 == Op1)         // sub X, X  -> 0
2125     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2126
2127   // If this is a 'B = x-(-A)', change to B = x+A...
2128   if (Value *V = dyn_castNegVal(Op1))
2129     return BinaryOperator::createAdd(Op0, V);
2130
2131   if (isa<UndefValue>(Op0))
2132     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2133   if (isa<UndefValue>(Op1))
2134     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2135
2136   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2137     // Replace (-1 - A) with (~A)...
2138     if (C->isAllOnesValue())
2139       return BinaryOperator::createNot(Op1);
2140
2141     // C - ~X == X + (1+C)
2142     Value *X = 0;
2143     if (match(Op1, m_Not(m_Value(X))))
2144       return BinaryOperator::createAdd(X, AddOne(C));
2145
2146     // -(X >>u 31) -> (X >>s 31)
2147     // -(X >>s 31) -> (X >>u 31)
2148     if (C->isZero()) {
2149       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2150         if (SI->getOpcode() == Instruction::LShr) {
2151           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2152             // Check to see if we are shifting out everything but the sign bit.
2153             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2154                 SI->getType()->getPrimitiveSizeInBits()-1) {
2155               // Ok, the transformation is safe.  Insert AShr.
2156               return BinaryOperator::create(Instruction::AShr, 
2157                                           SI->getOperand(0), CU, SI->getName());
2158             }
2159           }
2160         }
2161         else if (SI->getOpcode() == Instruction::AShr) {
2162           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2163             // Check to see if we are shifting out everything but the sign bit.
2164             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2165                 SI->getType()->getPrimitiveSizeInBits()-1) {
2166               // Ok, the transformation is safe.  Insert LShr. 
2167               return BinaryOperator::createLShr(
2168                                           SI->getOperand(0), CU, SI->getName());
2169             }
2170           }
2171         } 
2172     }
2173
2174     // Try to fold constant sub into select arguments.
2175     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2176       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2177         return R;
2178
2179     if (isa<PHINode>(Op0))
2180       if (Instruction *NV = FoldOpIntoPhi(I))
2181         return NV;
2182   }
2183
2184   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2185     if (Op1I->getOpcode() == Instruction::Add &&
2186         !Op0->getType()->isFPOrFPVector()) {
2187       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2188         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2189       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2190         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2191       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2192         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2193           // C1-(X+C2) --> (C1-C2)-X
2194           return BinaryOperator::createSub(Subtract(CI1, CI2), 
2195                                            Op1I->getOperand(0));
2196       }
2197     }
2198
2199     if (Op1I->hasOneUse()) {
2200       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2201       // is not used by anyone else...
2202       //
2203       if (Op1I->getOpcode() == Instruction::Sub &&
2204           !Op1I->getType()->isFPOrFPVector()) {
2205         // Swap the two operands of the subexpr...
2206         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2207         Op1I->setOperand(0, IIOp1);
2208         Op1I->setOperand(1, IIOp0);
2209
2210         // Create the new top level add instruction...
2211         return BinaryOperator::createAdd(Op0, Op1);
2212       }
2213
2214       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2215       //
2216       if (Op1I->getOpcode() == Instruction::And &&
2217           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2218         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2219
2220         Value *NewNot =
2221           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2222         return BinaryOperator::createAnd(Op0, NewNot);
2223       }
2224
2225       // 0 - (X sdiv C)  -> (X sdiv -C)
2226       if (Op1I->getOpcode() == Instruction::SDiv)
2227         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2228           if (CSI->isZero())
2229             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2230               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2231                                                ConstantExpr::getNeg(DivRHS));
2232
2233       // X - X*C --> X * (1-C)
2234       ConstantInt *C2 = 0;
2235       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2236         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2237         return BinaryOperator::createMul(Op0, CP1);
2238       }
2239     }
2240   }
2241
2242   if (!Op0->getType()->isFPOrFPVector())
2243     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2244       if (Op0I->getOpcode() == Instruction::Add) {
2245         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2246           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2247         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2248           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2249       } else if (Op0I->getOpcode() == Instruction::Sub) {
2250         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2251           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2252       }
2253
2254   ConstantInt *C1;
2255   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2256     if (X == Op1)  // X*C - X --> X * (C-1)
2257       return BinaryOperator::createMul(Op1, SubOne(C1));
2258
2259     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2260     if (X == dyn_castFoldableMul(Op1, C2))
2261       return BinaryOperator::createMul(Op1, Subtract(C1, C2));
2262   }
2263   return 0;
2264 }
2265
2266 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2267 /// really just returns true if the most significant (sign) bit is set.
2268 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2269   switch (pred) {
2270     case ICmpInst::ICMP_SLT: 
2271       // True if LHS s< RHS and RHS == 0
2272       return RHS->isZero();
2273     case ICmpInst::ICMP_SLE: 
2274       // True if LHS s<= RHS and RHS == -1
2275       return RHS->isAllOnesValue();
2276     case ICmpInst::ICMP_UGE: 
2277       // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2278       return RHS->getValue() == 
2279              APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2280     case ICmpInst::ICMP_UGT:
2281       // True if LHS u> RHS and RHS == high-bit-mask - 1
2282       return RHS->getValue() ==
2283              APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2284     default:
2285       return false;
2286   }
2287 }
2288
2289 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2290   bool Changed = SimplifyCommutative(I);
2291   Value *Op0 = I.getOperand(0);
2292
2293   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2294     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2295
2296   // Simplify mul instructions with a constant RHS...
2297   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2298     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2299
2300       // ((X << C1)*C2) == (X * (C2 << C1))
2301       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2302         if (SI->getOpcode() == Instruction::Shl)
2303           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2304             return BinaryOperator::createMul(SI->getOperand(0),
2305                                              ConstantExpr::getShl(CI, ShOp));
2306
2307       if (CI->isZero())
2308         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2309       if (CI->equalsInt(1))                  // X * 1  == X
2310         return ReplaceInstUsesWith(I, Op0);
2311       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2312         return BinaryOperator::createNeg(Op0, I.getName());
2313
2314       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2315       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2316         return BinaryOperator::createShl(Op0,
2317                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2318       }
2319     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2320       if (Op1F->isNullValue())
2321         return ReplaceInstUsesWith(I, Op1);
2322
2323       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2324       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2325       if (Op1F->getValue() == 1.0)
2326         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2327     }
2328     
2329     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2330       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2331           isa<ConstantInt>(Op0I->getOperand(1))) {
2332         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2333         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2334                                                      Op1, "tmp");
2335         InsertNewInstBefore(Add, I);
2336         Value *C1C2 = ConstantExpr::getMul(Op1, 
2337                                            cast<Constant>(Op0I->getOperand(1)));
2338         return BinaryOperator::createAdd(Add, C1C2);
2339         
2340       }
2341
2342     // Try to fold constant mul into select arguments.
2343     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2344       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2345         return R;
2346
2347     if (isa<PHINode>(Op0))
2348       if (Instruction *NV = FoldOpIntoPhi(I))
2349         return NV;
2350   }
2351
2352   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2353     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2354       return BinaryOperator::createMul(Op0v, Op1v);
2355
2356   // If one of the operands of the multiply is a cast from a boolean value, then
2357   // we know the bool is either zero or one, so this is a 'masking' multiply.
2358   // See if we can simplify things based on how the boolean was originally
2359   // formed.
2360   CastInst *BoolCast = 0;
2361   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2362     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2363       BoolCast = CI;
2364   if (!BoolCast)
2365     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2366       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2367         BoolCast = CI;
2368   if (BoolCast) {
2369     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2370       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2371       const Type *SCOpTy = SCIOp0->getType();
2372
2373       // If the icmp is true iff the sign bit of X is set, then convert this
2374       // multiply into a shift/and combination.
2375       if (isa<ConstantInt>(SCIOp1) &&
2376           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
2377         // Shift the X value right to turn it into "all signbits".
2378         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2379                                           SCOpTy->getPrimitiveSizeInBits()-1);
2380         Value *V =
2381           InsertNewInstBefore(
2382             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2383                                             BoolCast->getOperand(0)->getName()+
2384                                             ".mask"), I);
2385
2386         // If the multiply type is not the same as the source type, sign extend
2387         // or truncate to the multiply type.
2388         if (I.getType() != V->getType()) {
2389           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2390           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2391           Instruction::CastOps opcode = 
2392             (SrcBits == DstBits ? Instruction::BitCast : 
2393              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2394           V = InsertCastBefore(opcode, V, I.getType(), I);
2395         }
2396
2397         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2398         return BinaryOperator::createAnd(V, OtherOp);
2399       }
2400     }
2401   }
2402
2403   return Changed ? &I : 0;
2404 }
2405
2406 /// This function implements the transforms on div instructions that work
2407 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2408 /// used by the visitors to those instructions.
2409 /// @brief Transforms common to all three div instructions
2410 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2411   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2412
2413   // undef / X -> 0
2414   if (isa<UndefValue>(Op0))
2415     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2416
2417   // X / undef -> undef
2418   if (isa<UndefValue>(Op1))
2419     return ReplaceInstUsesWith(I, Op1);
2420
2421   // Handle cases involving: div X, (select Cond, Y, Z)
2422   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2423     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2424     // same basic block, then we replace the select with Y, and the condition 
2425     // of the select with false (if the cond value is in the same BB).  If the
2426     // select has uses other than the div, this allows them to be simplified
2427     // also. Note that div X, Y is just as good as div X, 0 (undef)
2428     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2429       if (ST->isNullValue()) {
2430         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2431         if (CondI && CondI->getParent() == I.getParent())
2432           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2433         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2434           I.setOperand(1, SI->getOperand(2));
2435         else
2436           UpdateValueUsesWith(SI, SI->getOperand(2));
2437         return &I;
2438       }
2439
2440     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2441     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2442       if (ST->isNullValue()) {
2443         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2444         if (CondI && CondI->getParent() == I.getParent())
2445           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2446         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2447           I.setOperand(1, SI->getOperand(1));
2448         else
2449           UpdateValueUsesWith(SI, SI->getOperand(1));
2450         return &I;
2451       }
2452   }
2453
2454   return 0;
2455 }
2456
2457 /// This function implements the transforms common to both integer division
2458 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2459 /// division instructions.
2460 /// @brief Common integer divide transforms
2461 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2462   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2463
2464   if (Instruction *Common = commonDivTransforms(I))
2465     return Common;
2466
2467   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2468     // div X, 1 == X
2469     if (RHS->equalsInt(1))
2470       return ReplaceInstUsesWith(I, Op0);
2471
2472     // (X / C1) / C2  -> X / (C1*C2)
2473     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2474       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2475         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2476           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2477                                         Multiply(RHS, LHSRHS));
2478         }
2479
2480     if (!RHS->isZero()) { // avoid X udiv 0
2481       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2482         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2483           return R;
2484       if (isa<PHINode>(Op0))
2485         if (Instruction *NV = FoldOpIntoPhi(I))
2486           return NV;
2487     }
2488   }
2489
2490   // 0 / X == 0, we don't need to preserve faults!
2491   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2492     if (LHS->equalsInt(0))
2493       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2494
2495   return 0;
2496 }
2497
2498 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2499   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2500
2501   // Handle the integer div common cases
2502   if (Instruction *Common = commonIDivTransforms(I))
2503     return Common;
2504
2505   // X udiv C^2 -> X >> C
2506   // Check to see if this is an unsigned division with an exact power of 2,
2507   // if so, convert to a right shift.
2508   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2509     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2510       return BinaryOperator::createLShr(Op0, 
2511                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2512   }
2513
2514   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2515   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2516     if (RHSI->getOpcode() == Instruction::Shl &&
2517         isa<ConstantInt>(RHSI->getOperand(0))) {
2518       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2519       if (C1.isPowerOf2()) {
2520         Value *N = RHSI->getOperand(1);
2521         const Type *NTy = N->getType();
2522         if (uint32_t C2 = C1.logBase2()) {
2523           Constant *C2V = ConstantInt::get(NTy, C2);
2524           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2525         }
2526         return BinaryOperator::createLShr(Op0, N);
2527       }
2528     }
2529   }
2530   
2531   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2532   // where C1&C2 are powers of two.
2533   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2534     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2535       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2536         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2537         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2538           // Compute the shift amounts
2539           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2540           // Construct the "on true" case of the select
2541           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2542           Instruction *TSI = BinaryOperator::createLShr(
2543                                                  Op0, TC, SI->getName()+".t");
2544           TSI = InsertNewInstBefore(TSI, I);
2545   
2546           // Construct the "on false" case of the select
2547           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2548           Instruction *FSI = BinaryOperator::createLShr(
2549                                                  Op0, FC, SI->getName()+".f");
2550           FSI = InsertNewInstBefore(FSI, I);
2551
2552           // construct the select instruction and return it.
2553           return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2554         }
2555       }
2556   return 0;
2557 }
2558
2559 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2560   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2561
2562   // Handle the integer div common cases
2563   if (Instruction *Common = commonIDivTransforms(I))
2564     return Common;
2565
2566   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2567     // sdiv X, -1 == -X
2568     if (RHS->isAllOnesValue())
2569       return BinaryOperator::createNeg(Op0);
2570
2571     // -X/C -> X/-C
2572     if (Value *LHSNeg = dyn_castNegVal(Op0))
2573       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2574   }
2575
2576   // If the sign bits of both operands are zero (i.e. we can prove they are
2577   // unsigned inputs), turn this into a udiv.
2578   if (I.getType()->isInteger()) {
2579     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2580     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2581       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2582     }
2583   }      
2584   
2585   return 0;
2586 }
2587
2588 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2589   return commonDivTransforms(I);
2590 }
2591
2592 /// GetFactor - If we can prove that the specified value is at least a multiple
2593 /// of some factor, return that factor.
2594 static Constant *GetFactor(Value *V) {
2595   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2596     return CI;
2597   
2598   // Unless we can be tricky, we know this is a multiple of 1.
2599   Constant *Result = ConstantInt::get(V->getType(), 1);
2600   
2601   Instruction *I = dyn_cast<Instruction>(V);
2602   if (!I) return Result;
2603   
2604   if (I->getOpcode() == Instruction::Mul) {
2605     // Handle multiplies by a constant, etc.
2606     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2607                                 GetFactor(I->getOperand(1)));
2608   } else if (I->getOpcode() == Instruction::Shl) {
2609     // (X<<C) -> X * (1 << C)
2610     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2611       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2612       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2613     }
2614   } else if (I->getOpcode() == Instruction::And) {
2615     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2616       // X & 0xFFF0 is known to be a multiple of 16.
2617       uint32_t Zeros = RHS->getValue().countTrailingZeros();
2618       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2619         return ConstantExpr::getShl(Result, 
2620                                     ConstantInt::get(Result->getType(), Zeros));
2621     }
2622   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2623     // Only handle int->int casts.
2624     if (!CI->isIntegerCast())
2625       return Result;
2626     Value *Op = CI->getOperand(0);
2627     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2628   }    
2629   return Result;
2630 }
2631
2632 /// This function implements the transforms on rem instructions that work
2633 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2634 /// is used by the visitors to those instructions.
2635 /// @brief Transforms common to all three rem instructions
2636 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2637   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2638
2639   // 0 % X == 0, we don't need to preserve faults!
2640   if (Constant *LHS = dyn_cast<Constant>(Op0))
2641     if (LHS->isNullValue())
2642       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2643
2644   if (isa<UndefValue>(Op0))              // undef % X -> 0
2645     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2646   if (isa<UndefValue>(Op1))
2647     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2648
2649   // Handle cases involving: rem X, (select Cond, Y, Z)
2650   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2651     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2652     // the same basic block, then we replace the select with Y, and the
2653     // condition of the select with false (if the cond value is in the same
2654     // BB).  If the select has uses other than the div, this allows them to be
2655     // simplified also.
2656     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2657       if (ST->isNullValue()) {
2658         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2659         if (CondI && CondI->getParent() == I.getParent())
2660           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2661         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2662           I.setOperand(1, SI->getOperand(2));
2663         else
2664           UpdateValueUsesWith(SI, SI->getOperand(2));
2665         return &I;
2666       }
2667     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2668     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2669       if (ST->isNullValue()) {
2670         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2671         if (CondI && CondI->getParent() == I.getParent())
2672           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2673         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2674           I.setOperand(1, SI->getOperand(1));
2675         else
2676           UpdateValueUsesWith(SI, SI->getOperand(1));
2677         return &I;
2678       }
2679   }
2680
2681   return 0;
2682 }
2683
2684 /// This function implements the transforms common to both integer remainder
2685 /// instructions (urem and srem). It is called by the visitors to those integer
2686 /// remainder instructions.
2687 /// @brief Common integer remainder transforms
2688 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2689   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2690
2691   if (Instruction *common = commonRemTransforms(I))
2692     return common;
2693
2694   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2695     // X % 0 == undef, we don't need to preserve faults!
2696     if (RHS->equalsInt(0))
2697       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2698     
2699     if (RHS->equalsInt(1))  // X % 1 == 0
2700       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2701
2702     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2703       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2704         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2705           return R;
2706       } else if (isa<PHINode>(Op0I)) {
2707         if (Instruction *NV = FoldOpIntoPhi(I))
2708           return NV;
2709       }
2710       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2711       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2712         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2713     }
2714   }
2715
2716   return 0;
2717 }
2718
2719 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2720   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2721
2722   if (Instruction *common = commonIRemTransforms(I))
2723     return common;
2724   
2725   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2726     // X urem C^2 -> X and C
2727     // Check to see if this is an unsigned remainder with an exact power of 2,
2728     // if so, convert to a bitwise and.
2729     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2730       if (C->getValue().isPowerOf2())
2731         return BinaryOperator::createAnd(Op0, SubOne(C));
2732   }
2733
2734   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2735     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2736     if (RHSI->getOpcode() == Instruction::Shl &&
2737         isa<ConstantInt>(RHSI->getOperand(0))) {
2738       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2739         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2740         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2741                                                                    "tmp"), I);
2742         return BinaryOperator::createAnd(Op0, Add);
2743       }
2744     }
2745   }
2746
2747   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2748   // where C1&C2 are powers of two.
2749   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2750     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2751       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2752         // STO == 0 and SFO == 0 handled above.
2753         if ((STO->getValue().isPowerOf2()) && 
2754             (SFO->getValue().isPowerOf2())) {
2755           Value *TrueAnd = InsertNewInstBefore(
2756             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2757           Value *FalseAnd = InsertNewInstBefore(
2758             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2759           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2760         }
2761       }
2762   }
2763   
2764   return 0;
2765 }
2766
2767 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2768   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2769
2770   if (Instruction *common = commonIRemTransforms(I))
2771     return common;
2772   
2773   if (Value *RHSNeg = dyn_castNegVal(Op1))
2774     if (!isa<ConstantInt>(RHSNeg) || 
2775         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2776       // X % -Y -> X % Y
2777       AddUsesToWorkList(I);
2778       I.setOperand(1, RHSNeg);
2779       return &I;
2780     }
2781  
2782   // If the top bits of both operands are zero (i.e. we can prove they are
2783   // unsigned inputs), turn this into a urem.
2784   APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2785   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2786     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2787     return BinaryOperator::createURem(Op0, Op1, I.getName());
2788   }
2789
2790   return 0;
2791 }
2792
2793 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2794   return commonRemTransforms(I);
2795 }
2796
2797 // isMaxValueMinusOne - return true if this is Max-1
2798 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2799   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2800   if (isSigned) {
2801     // Calculate 0111111111..11111
2802     APInt Val(APInt::getSignedMaxValue(TypeBits));
2803     return C->getValue() == Val-1;
2804   }
2805   return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2806 }
2807
2808 // isMinValuePlusOne - return true if this is Min+1
2809 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2810   if (isSigned) {
2811     // Calculate 1111111111000000000000
2812     uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2813     APInt Val(APInt::getSignedMinValue(TypeBits));
2814     return C->getValue() == Val+1;
2815   }
2816   return C->getValue() == 1; // unsigned
2817 }
2818
2819 // isOneBitSet - Return true if there is exactly one bit set in the specified
2820 // constant.
2821 static bool isOneBitSet(const ConstantInt *CI) {
2822   return CI->getValue().isPowerOf2();
2823 }
2824
2825 // isHighOnes - Return true if the constant is of the form 1+0+.
2826 // This is the same as lowones(~X).
2827 static bool isHighOnes(const ConstantInt *CI) {
2828   return (~CI->getValue() + 1).isPowerOf2();
2829 }
2830
2831 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2832 /// are carefully arranged to allow folding of expressions such as:
2833 ///
2834 ///      (A < B) | (A > B) --> (A != B)
2835 ///
2836 /// Note that this is only valid if the first and second predicates have the
2837 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2838 ///
2839 /// Three bits are used to represent the condition, as follows:
2840 ///   0  A > B
2841 ///   1  A == B
2842 ///   2  A < B
2843 ///
2844 /// <=>  Value  Definition
2845 /// 000     0   Always false
2846 /// 001     1   A >  B
2847 /// 010     2   A == B
2848 /// 011     3   A >= B
2849 /// 100     4   A <  B
2850 /// 101     5   A != B
2851 /// 110     6   A <= B
2852 /// 111     7   Always true
2853 ///  
2854 static unsigned getICmpCode(const ICmpInst *ICI) {
2855   switch (ICI->getPredicate()) {
2856     // False -> 0
2857   case ICmpInst::ICMP_UGT: return 1;  // 001
2858   case ICmpInst::ICMP_SGT: return 1;  // 001
2859   case ICmpInst::ICMP_EQ:  return 2;  // 010
2860   case ICmpInst::ICMP_UGE: return 3;  // 011
2861   case ICmpInst::ICMP_SGE: return 3;  // 011
2862   case ICmpInst::ICMP_ULT: return 4;  // 100
2863   case ICmpInst::ICMP_SLT: return 4;  // 100
2864   case ICmpInst::ICMP_NE:  return 5;  // 101
2865   case ICmpInst::ICMP_ULE: return 6;  // 110
2866   case ICmpInst::ICMP_SLE: return 6;  // 110
2867     // True -> 7
2868   default:
2869     assert(0 && "Invalid ICmp predicate!");
2870     return 0;
2871   }
2872 }
2873
2874 /// getICmpValue - This is the complement of getICmpCode, which turns an
2875 /// opcode and two operands into either a constant true or false, or a brand 
2876 /// new /// ICmp instruction. The sign is passed in to determine which kind
2877 /// of predicate to use in new icmp instructions.
2878 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2879   switch (code) {
2880   default: assert(0 && "Illegal ICmp code!");
2881   case  0: return ConstantInt::getFalse();
2882   case  1: 
2883     if (sign)
2884       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2885     else
2886       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2887   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
2888   case  3: 
2889     if (sign)
2890       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2891     else
2892       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2893   case  4: 
2894     if (sign)
2895       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2896     else
2897       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2898   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
2899   case  6: 
2900     if (sign)
2901       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2902     else
2903       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2904   case  7: return ConstantInt::getTrue();
2905   }
2906 }
2907
2908 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2909   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2910     (ICmpInst::isSignedPredicate(p1) && 
2911      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2912     (ICmpInst::isSignedPredicate(p2) && 
2913      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2914 }
2915
2916 namespace { 
2917 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2918 struct FoldICmpLogical {
2919   InstCombiner &IC;
2920   Value *LHS, *RHS;
2921   ICmpInst::Predicate pred;
2922   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2923     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2924       pred(ICI->getPredicate()) {}
2925   bool shouldApply(Value *V) const {
2926     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2927       if (PredicatesFoldable(pred, ICI->getPredicate()))
2928         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2929                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2930     return false;
2931   }
2932   Instruction *apply(Instruction &Log) const {
2933     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2934     if (ICI->getOperand(0) != LHS) {
2935       assert(ICI->getOperand(1) == LHS);
2936       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
2937     }
2938
2939     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
2940     unsigned LHSCode = getICmpCode(ICI);
2941     unsigned RHSCode = getICmpCode(RHSICI);
2942     unsigned Code;
2943     switch (Log.getOpcode()) {
2944     case Instruction::And: Code = LHSCode & RHSCode; break;
2945     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2946     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2947     default: assert(0 && "Illegal logical opcode!"); return 0;
2948     }
2949
2950     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
2951                     ICmpInst::isSignedPredicate(ICI->getPredicate());
2952       
2953     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
2954     if (Instruction *I = dyn_cast<Instruction>(RV))
2955       return I;
2956     // Otherwise, it's a constant boolean value...
2957     return IC.ReplaceInstUsesWith(Log, RV);
2958   }
2959 };
2960 } // end anonymous namespace
2961
2962 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2963 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2964 // guaranteed to be a binary operator.
2965 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2966                                     ConstantInt *OpRHS,
2967                                     ConstantInt *AndRHS,
2968                                     BinaryOperator &TheAnd) {
2969   Value *X = Op->getOperand(0);
2970   Constant *Together = 0;
2971   if (!Op->isShift())
2972     Together = And(AndRHS, OpRHS);
2973
2974   switch (Op->getOpcode()) {
2975   case Instruction::Xor:
2976     if (Op->hasOneUse()) {
2977       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2978       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
2979       InsertNewInstBefore(And, TheAnd);
2980       And->takeName(Op);
2981       return BinaryOperator::createXor(And, Together);
2982     }
2983     break;
2984   case Instruction::Or:
2985     if (Together == AndRHS) // (X | C) & C --> C
2986       return ReplaceInstUsesWith(TheAnd, AndRHS);
2987
2988     if (Op->hasOneUse() && Together != OpRHS) {
2989       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2990       Instruction *Or = BinaryOperator::createOr(X, Together);
2991       InsertNewInstBefore(Or, TheAnd);
2992       Or->takeName(Op);
2993       return BinaryOperator::createAnd(Or, AndRHS);
2994     }
2995     break;
2996   case Instruction::Add:
2997     if (Op->hasOneUse()) {
2998       // Adding a one to a single bit bit-field should be turned into an XOR
2999       // of the bit.  First thing to check is to see if this AND is with a
3000       // single bit constant.
3001       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3002
3003       // If there is only one bit set...
3004       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3005         // Ok, at this point, we know that we are masking the result of the
3006         // ADD down to exactly one bit.  If the constant we are adding has
3007         // no bits set below this bit, then we can eliminate the ADD.
3008         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3009
3010         // Check to see if any bits below the one bit set in AndRHSV are set.
3011         if ((AddRHS & (AndRHSV-1)) == 0) {
3012           // If not, the only thing that can effect the output of the AND is
3013           // the bit specified by AndRHSV.  If that bit is set, the effect of
3014           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3015           // no effect.
3016           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3017             TheAnd.setOperand(0, X);
3018             return &TheAnd;
3019           } else {
3020             // Pull the XOR out of the AND.
3021             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3022             InsertNewInstBefore(NewAnd, TheAnd);
3023             NewAnd->takeName(Op);
3024             return BinaryOperator::createXor(NewAnd, AndRHS);
3025           }
3026         }
3027       }
3028     }
3029     break;
3030
3031   case Instruction::Shl: {
3032     // We know that the AND will not produce any of the bits shifted in, so if
3033     // the anded constant includes them, clear them now!
3034     //
3035     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3036     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3037     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3038     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3039
3040     if (CI->getValue() == ShlMask) { 
3041     // Masking out bits that the shift already masks
3042       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3043     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3044       TheAnd.setOperand(1, CI);
3045       return &TheAnd;
3046     }
3047     break;
3048   }
3049   case Instruction::LShr:
3050   {
3051     // We know that the AND will not produce any of the bits shifted in, so if
3052     // the anded constant includes them, clear them now!  This only applies to
3053     // unsigned shifts, because a signed shr may bring in set bits!
3054     //
3055     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3056     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3057     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3058     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3059
3060     if (CI->getValue() == ShrMask) {   
3061     // Masking out bits that the shift already masks.
3062       return ReplaceInstUsesWith(TheAnd, Op);
3063     } else if (CI != AndRHS) {
3064       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3065       return &TheAnd;
3066     }
3067     break;
3068   }
3069   case Instruction::AShr:
3070     // Signed shr.
3071     // See if this is shifting in some sign extension, then masking it out
3072     // with an and.
3073     if (Op->hasOneUse()) {
3074       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3075       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3076       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3077       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3078       if (C == AndRHS) {          // Masking out bits shifted in.
3079         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3080         // Make the argument unsigned.
3081         Value *ShVal = Op->getOperand(0);
3082         ShVal = InsertNewInstBefore(
3083             BinaryOperator::createLShr(ShVal, OpRHS, 
3084                                    Op->getName()), TheAnd);
3085         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3086       }
3087     }
3088     break;
3089   }
3090   return 0;
3091 }
3092
3093
3094 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3095 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3096 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3097 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3098 /// insert new instructions.
3099 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3100                                            bool isSigned, bool Inside, 
3101                                            Instruction &IB) {
3102   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3103             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3104          "Lo is not <= Hi in range emission code!");
3105     
3106   if (Inside) {
3107     if (Lo == Hi)  // Trivially false.
3108       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3109
3110     // V >= Min && V < Hi --> V < Hi
3111     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3112       ICmpInst::Predicate pred = (isSigned ? 
3113         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3114       return new ICmpInst(pred, V, Hi);
3115     }
3116
3117     // Emit V-Lo <u Hi-Lo
3118     Constant *NegLo = ConstantExpr::getNeg(Lo);
3119     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3120     InsertNewInstBefore(Add, IB);
3121     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3122     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3123   }
3124
3125   if (Lo == Hi)  // Trivially true.
3126     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3127
3128   // V < Min || V >= Hi -> V > Hi-1
3129   Hi = SubOne(cast<ConstantInt>(Hi));
3130   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3131     ICmpInst::Predicate pred = (isSigned ? 
3132         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3133     return new ICmpInst(pred, V, Hi);
3134   }
3135
3136   // Emit V-Lo >u Hi-1-Lo
3137   // Note that Hi has already had one subtracted from it, above.
3138   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3139   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3140   InsertNewInstBefore(Add, IB);
3141   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3142   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3143 }
3144
3145 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3146 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3147 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3148 // not, since all 1s are not contiguous.
3149 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3150   const APInt& V = Val->getValue();
3151   uint32_t BitWidth = Val->getType()->getBitWidth();
3152   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3153
3154   // look for the first zero bit after the run of ones
3155   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3156   // look for the first non-zero bit
3157   ME = V.getActiveBits(); 
3158   return true;
3159 }
3160
3161 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3162 /// where isSub determines whether the operator is a sub.  If we can fold one of
3163 /// the following xforms:
3164 /// 
3165 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3166 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3167 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3168 ///
3169 /// return (A +/- B).
3170 ///
3171 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3172                                         ConstantInt *Mask, bool isSub,
3173                                         Instruction &I) {
3174   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3175   if (!LHSI || LHSI->getNumOperands() != 2 ||
3176       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3177
3178   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3179
3180   switch (LHSI->getOpcode()) {
3181   default: return 0;
3182   case Instruction::And:
3183     if (And(N, Mask) == Mask) {
3184       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3185       if ((Mask->getValue().countLeadingZeros() + 
3186            Mask->getValue().countPopulation()) == 
3187           Mask->getValue().getBitWidth())
3188         break;
3189
3190       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3191       // part, we don't need any explicit masks to take them out of A.  If that
3192       // is all N is, ignore it.
3193       uint32_t MB = 0, ME = 0;
3194       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3195         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3196         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3197         if (MaskedValueIsZero(RHS, Mask))
3198           break;
3199       }
3200     }
3201     return 0;
3202   case Instruction::Or:
3203   case Instruction::Xor:
3204     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3205     if ((Mask->getValue().countLeadingZeros() + 
3206          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3207         && And(N, Mask)->isZero())
3208       break;
3209     return 0;
3210   }
3211   
3212   Instruction *New;
3213   if (isSub)
3214     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3215   else
3216     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3217   return InsertNewInstBefore(New, I);
3218 }
3219
3220 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3221   bool Changed = SimplifyCommutative(I);
3222   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3223
3224   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3225     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3226
3227   // and X, X = X
3228   if (Op0 == Op1)
3229     return ReplaceInstUsesWith(I, Op1);
3230
3231   // See if we can simplify any instructions used by the instruction whose sole 
3232   // purpose is to compute bits we don't care about.
3233   if (!isa<VectorType>(I.getType())) {
3234     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3235     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3236     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3237                              KnownZero, KnownOne))
3238       return &I;
3239   } else {
3240     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3241       if (CP->isAllOnesValue())
3242         return ReplaceInstUsesWith(I, I.getOperand(0));
3243     }
3244   }
3245   
3246   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3247     const APInt& AndRHSMask = AndRHS->getValue();
3248     APInt NotAndRHS(~AndRHSMask);
3249
3250     // Optimize a variety of ((val OP C1) & C2) combinations...
3251     if (isa<BinaryOperator>(Op0)) {
3252       Instruction *Op0I = cast<Instruction>(Op0);
3253       Value *Op0LHS = Op0I->getOperand(0);
3254       Value *Op0RHS = Op0I->getOperand(1);
3255       switch (Op0I->getOpcode()) {
3256       case Instruction::Xor:
3257       case Instruction::Or:
3258         // If the mask is only needed on one incoming arm, push it up.
3259         if (Op0I->hasOneUse()) {
3260           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3261             // Not masking anything out for the LHS, move to RHS.
3262             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3263                                                    Op0RHS->getName()+".masked");
3264             InsertNewInstBefore(NewRHS, I);
3265             return BinaryOperator::create(
3266                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3267           }
3268           if (!isa<Constant>(Op0RHS) &&
3269               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3270             // Not masking anything out for the RHS, move to LHS.
3271             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3272                                                    Op0LHS->getName()+".masked");
3273             InsertNewInstBefore(NewLHS, I);
3274             return BinaryOperator::create(
3275                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3276           }
3277         }
3278
3279         break;
3280       case Instruction::Add:
3281         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3282         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3283         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3284         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3285           return BinaryOperator::createAnd(V, AndRHS);
3286         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3287           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3288         break;
3289
3290       case Instruction::Sub:
3291         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3292         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3293         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3294         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3295           return BinaryOperator::createAnd(V, AndRHS);
3296         break;
3297       }
3298
3299       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3300         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3301           return Res;
3302     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3303       // If this is an integer truncation or change from signed-to-unsigned, and
3304       // if the source is an and/or with immediate, transform it.  This
3305       // frequently occurs for bitfield accesses.
3306       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3307         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3308             CastOp->getNumOperands() == 2)
3309           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3310             if (CastOp->getOpcode() == Instruction::And) {
3311               // Change: and (cast (and X, C1) to T), C2
3312               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3313               // This will fold the two constants together, which may allow 
3314               // other simplifications.
3315               Instruction *NewCast = CastInst::createTruncOrBitCast(
3316                 CastOp->getOperand(0), I.getType(), 
3317                 CastOp->getName()+".shrunk");
3318               NewCast = InsertNewInstBefore(NewCast, I);
3319               // trunc_or_bitcast(C1)&C2
3320               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3321               C3 = ConstantExpr::getAnd(C3, AndRHS);
3322               return BinaryOperator::createAnd(NewCast, C3);
3323             } else if (CastOp->getOpcode() == Instruction::Or) {
3324               // Change: and (cast (or X, C1) to T), C2
3325               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3326               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3327               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3328                 return ReplaceInstUsesWith(I, AndRHS);
3329             }
3330       }
3331     }
3332
3333     // Try to fold constant and into select arguments.
3334     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3335       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3336         return R;
3337     if (isa<PHINode>(Op0))
3338       if (Instruction *NV = FoldOpIntoPhi(I))
3339         return NV;
3340   }
3341
3342   Value *Op0NotVal = dyn_castNotVal(Op0);
3343   Value *Op1NotVal = dyn_castNotVal(Op1);
3344
3345   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3346     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3347
3348   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3349   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3350     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3351                                                I.getName()+".demorgan");
3352     InsertNewInstBefore(Or, I);
3353     return BinaryOperator::createNot(Or);
3354   }
3355   
3356   {
3357     Value *A = 0, *B = 0;
3358     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3359       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3360         return ReplaceInstUsesWith(I, Op1);
3361     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3362       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3363         return ReplaceInstUsesWith(I, Op0);
3364     
3365     if (Op0->hasOneUse() &&
3366         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3367       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3368         I.swapOperands();     // Simplify below
3369         std::swap(Op0, Op1);
3370       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3371         cast<BinaryOperator>(Op0)->swapOperands();
3372         I.swapOperands();     // Simplify below
3373         std::swap(Op0, Op1);
3374       }
3375     }
3376     if (Op1->hasOneUse() &&
3377         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3378       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3379         cast<BinaryOperator>(Op1)->swapOperands();
3380         std::swap(A, B);
3381       }
3382       if (A == Op0) {                                // A&(A^B) -> A & ~B
3383         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3384         InsertNewInstBefore(NotB, I);
3385         return BinaryOperator::createAnd(A, NotB);
3386       }
3387     }
3388   }
3389   
3390   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3391     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3392     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3393       return R;
3394
3395     Value *LHSVal, *RHSVal;
3396     ConstantInt *LHSCst, *RHSCst;
3397     ICmpInst::Predicate LHSCC, RHSCC;
3398     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3399       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3400         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3401             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3402             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3403             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3404             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3405             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3406           // Ensure that the larger constant is on the RHS.
3407           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3408             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3409           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3410           ICmpInst *LHS = cast<ICmpInst>(Op0);
3411           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3412             std::swap(LHS, RHS);
3413             std::swap(LHSCst, RHSCst);
3414             std::swap(LHSCC, RHSCC);
3415           }
3416
3417           // At this point, we know we have have two icmp instructions
3418           // comparing a value against two constants and and'ing the result
3419           // together.  Because of the above check, we know that we only have
3420           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3421           // (from the FoldICmpLogical check above), that the two constants 
3422           // are not equal and that the larger constant is on the RHS
3423           assert(LHSCst != RHSCst && "Compares not folded above?");
3424
3425           switch (LHSCC) {
3426           default: assert(0 && "Unknown integer condition code!");
3427           case ICmpInst::ICMP_EQ:
3428             switch (RHSCC) {
3429             default: assert(0 && "Unknown integer condition code!");
3430             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3431             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3432             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3433               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3434             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3435             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3436             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3437               return ReplaceInstUsesWith(I, LHS);
3438             }
3439           case ICmpInst::ICMP_NE:
3440             switch (RHSCC) {
3441             default: assert(0 && "Unknown integer condition code!");
3442             case ICmpInst::ICMP_ULT:
3443               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3444                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3445               break;                        // (X != 13 & X u< 15) -> no change
3446             case ICmpInst::ICMP_SLT:
3447               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3448                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3449               break;                        // (X != 13 & X s< 15) -> no change
3450             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3451             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3452             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3453               return ReplaceInstUsesWith(I, RHS);
3454             case ICmpInst::ICMP_NE:
3455               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3456                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3457                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3458                                                       LHSVal->getName()+".off");
3459                 InsertNewInstBefore(Add, I);
3460                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3461                                     ConstantInt::get(Add->getType(), 1));
3462               }
3463               break;                        // (X != 13 & X != 15) -> no change
3464             }
3465             break;
3466           case ICmpInst::ICMP_ULT:
3467             switch (RHSCC) {
3468             default: assert(0 && "Unknown integer condition code!");
3469             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3470             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3471               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3472             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3473               break;
3474             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3475             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3476               return ReplaceInstUsesWith(I, LHS);
3477             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3478               break;
3479             }
3480             break;
3481           case ICmpInst::ICMP_SLT:
3482             switch (RHSCC) {
3483             default: assert(0 && "Unknown integer condition code!");
3484             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3485             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3486               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3487             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3488               break;
3489             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3490             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3491               return ReplaceInstUsesWith(I, LHS);
3492             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3493               break;
3494             }
3495             break;
3496           case ICmpInst::ICMP_UGT:
3497             switch (RHSCC) {
3498             default: assert(0 && "Unknown integer condition code!");
3499             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3500               return ReplaceInstUsesWith(I, LHS);
3501             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3502               return ReplaceInstUsesWith(I, RHS);
3503             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3504               break;
3505             case ICmpInst::ICMP_NE:
3506               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3507                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3508               break;                        // (X u> 13 & X != 15) -> no change
3509             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3510               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3511                                      true, I);
3512             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3513               break;
3514             }
3515             break;
3516           case ICmpInst::ICMP_SGT:
3517             switch (RHSCC) {
3518             default: assert(0 && "Unknown integer condition code!");
3519             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
3520               return ReplaceInstUsesWith(I, LHS);
3521             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3522               return ReplaceInstUsesWith(I, RHS);
3523             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3524               break;
3525             case ICmpInst::ICMP_NE:
3526               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3527                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3528               break;                        // (X s> 13 & X != 15) -> no change
3529             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3530               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3531                                      true, I);
3532             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3533               break;
3534             }
3535             break;
3536           }
3537         }
3538   }
3539
3540   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3541   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3542     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3543       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3544         const Type *SrcTy = Op0C->getOperand(0)->getType();
3545         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3546             // Only do this if the casts both really cause code to be generated.
3547             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3548                               I.getType(), TD) &&
3549             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3550                               I.getType(), TD)) {
3551           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3552                                                          Op1C->getOperand(0),
3553                                                          I.getName());
3554           InsertNewInstBefore(NewOp, I);
3555           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3556         }
3557       }
3558     
3559   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3560   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3561     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3562       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3563           SI0->getOperand(1) == SI1->getOperand(1) &&
3564           (SI0->hasOneUse() || SI1->hasOneUse())) {
3565         Instruction *NewOp =
3566           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3567                                                         SI1->getOperand(0),
3568                                                         SI0->getName()), I);
3569         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3570                                       SI1->getOperand(1));
3571       }
3572   }
3573
3574   return Changed ? &I : 0;
3575 }
3576
3577 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3578 /// in the result.  If it does, and if the specified byte hasn't been filled in
3579 /// yet, fill it in and return false.
3580 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3581   Instruction *I = dyn_cast<Instruction>(V);
3582   if (I == 0) return true;
3583
3584   // If this is an or instruction, it is an inner node of the bswap.
3585   if (I->getOpcode() == Instruction::Or)
3586     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3587            CollectBSwapParts(I->getOperand(1), ByteValues);
3588   
3589   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3590   // If this is a shift by a constant int, and it is "24", then its operand
3591   // defines a byte.  We only handle unsigned types here.
3592   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3593     // Not shifting the entire input by N-1 bytes?
3594     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3595         8*(ByteValues.size()-1))
3596       return true;
3597     
3598     unsigned DestNo;
3599     if (I->getOpcode() == Instruction::Shl) {
3600       // X << 24 defines the top byte with the lowest of the input bytes.
3601       DestNo = ByteValues.size()-1;
3602     } else {
3603       // X >>u 24 defines the low byte with the highest of the input bytes.
3604       DestNo = 0;
3605     }
3606     
3607     // If the destination byte value is already defined, the values are or'd
3608     // together, which isn't a bswap (unless it's an or of the same bits).
3609     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3610       return true;
3611     ByteValues[DestNo] = I->getOperand(0);
3612     return false;
3613   }
3614   
3615   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3616   // don't have this.
3617   Value *Shift = 0, *ShiftLHS = 0;
3618   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3619   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3620       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3621     return true;
3622   Instruction *SI = cast<Instruction>(Shift);
3623
3624   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3625   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3626       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3627     return true;
3628   
3629   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3630   unsigned DestByte;
3631   if (AndAmt->getValue().getActiveBits() > 64)
3632     return true;
3633   uint64_t AndAmtVal = AndAmt->getZExtValue();
3634   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3635     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3636       break;
3637   // Unknown mask for bswap.
3638   if (DestByte == ByteValues.size()) return true;
3639   
3640   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3641   unsigned SrcByte;
3642   if (SI->getOpcode() == Instruction::Shl)
3643     SrcByte = DestByte - ShiftBytes;
3644   else
3645     SrcByte = DestByte + ShiftBytes;
3646   
3647   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3648   if (SrcByte != ByteValues.size()-DestByte-1)
3649     return true;
3650   
3651   // If the destination byte value is already defined, the values are or'd
3652   // together, which isn't a bswap (unless it's an or of the same bits).
3653   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3654     return true;
3655   ByteValues[DestByte] = SI->getOperand(0);
3656   return false;
3657 }
3658
3659 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3660 /// If so, insert the new bswap intrinsic and return it.
3661 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3662   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3663   if (!ITy || ITy->getBitWidth() % 16) 
3664     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3665   
3666   /// ByteValues - For each byte of the result, we keep track of which value
3667   /// defines each byte.
3668   SmallVector<Value*, 8> ByteValues;
3669   ByteValues.resize(ITy->getBitWidth()/8);
3670     
3671   // Try to find all the pieces corresponding to the bswap.
3672   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3673       CollectBSwapParts(I.getOperand(1), ByteValues))
3674     return 0;
3675   
3676   // Check to see if all of the bytes come from the same value.
3677   Value *V = ByteValues[0];
3678   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3679   
3680   // Check to make sure that all of the bytes come from the same value.
3681   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3682     if (ByteValues[i] != V)
3683       return 0;
3684   const Type *Tys[] = { ITy, ITy };
3685   Module *M = I.getParent()->getParent()->getParent();
3686   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 2);
3687   return new CallInst(F, V);
3688 }
3689
3690
3691 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3692   bool Changed = SimplifyCommutative(I);
3693   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3694
3695   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3696     return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
3697
3698   // or X, X = X
3699   if (Op0 == Op1)
3700     return ReplaceInstUsesWith(I, Op0);
3701
3702   // See if we can simplify any instructions used by the instruction whose sole 
3703   // purpose is to compute bits we don't care about.
3704   if (!isa<VectorType>(I.getType())) {
3705     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3706     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3707     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3708                              KnownZero, KnownOne))
3709       return &I;
3710   }
3711   
3712   // or X, -1 == -1
3713   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3714     ConstantInt *C1 = 0; Value *X = 0;
3715     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3716     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3717       Instruction *Or = BinaryOperator::createOr(X, RHS);
3718       InsertNewInstBefore(Or, I);
3719       Or->takeName(Op0);
3720       return BinaryOperator::createAnd(Or, 
3721                ConstantInt::get(RHS->getValue() | C1->getValue()));
3722     }
3723
3724     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3725     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3726       Instruction *Or = BinaryOperator::createOr(X, RHS);
3727       InsertNewInstBefore(Or, I);
3728       Or->takeName(Op0);
3729       return BinaryOperator::createXor(Or,
3730                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3731     }
3732
3733     // Try to fold constant and into select arguments.
3734     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3735       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3736         return R;
3737     if (isa<PHINode>(Op0))
3738       if (Instruction *NV = FoldOpIntoPhi(I))
3739         return NV;
3740   }
3741
3742   Value *A = 0, *B = 0;
3743   ConstantInt *C1 = 0, *C2 = 0;
3744
3745   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3746     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3747       return ReplaceInstUsesWith(I, Op1);
3748   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3749     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3750       return ReplaceInstUsesWith(I, Op0);
3751
3752   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3753   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3754   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3755       match(Op1, m_Or(m_Value(), m_Value())) ||
3756       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3757        match(Op1, m_Shift(m_Value(), m_Value())))) {
3758     if (Instruction *BSwap = MatchBSwap(I))
3759       return BSwap;
3760   }
3761   
3762   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3763   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3764       MaskedValueIsZero(Op1, C1->getValue())) {
3765     Instruction *NOr = BinaryOperator::createOr(A, Op1);
3766     InsertNewInstBefore(NOr, I);
3767     NOr->takeName(Op0);
3768     return BinaryOperator::createXor(NOr, C1);
3769   }
3770
3771   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3772   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3773       MaskedValueIsZero(Op0, C1->getValue())) {
3774     Instruction *NOr = BinaryOperator::createOr(A, Op0);
3775     InsertNewInstBefore(NOr, I);
3776     NOr->takeName(Op0);
3777     return BinaryOperator::createXor(NOr, C1);
3778   }
3779
3780   // (A & C)|(B & D)
3781   Value *C, *D;
3782   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3783       match(Op1, m_And(m_Value(B), m_Value(D)))) {
3784     Value *V1 = 0, *V2 = 0, *V3 = 0;
3785     C1 = dyn_cast<ConstantInt>(C);
3786     C2 = dyn_cast<ConstantInt>(D);
3787     if (C1 && C2) {  // (A & C1)|(B & C2)
3788       // If we have: ((V + N) & C1) | (V & C2)
3789       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3790       // replace with V+N.
3791       if (C1->getValue() == ~C2->getValue()) {
3792         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3793             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3794           // Add commutes, try both ways.
3795           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3796             return ReplaceInstUsesWith(I, A);
3797           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3798             return ReplaceInstUsesWith(I, A);
3799         }
3800         // Or commutes, try both ways.
3801         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3802             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3803           // Add commutes, try both ways.
3804           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3805             return ReplaceInstUsesWith(I, B);
3806           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3807             return ReplaceInstUsesWith(I, B);
3808         }
3809       }
3810       V1 = 0; V2 = 0; V3 = 0;
3811     }
3812     
3813     // Check to see if we have any common things being and'ed.  If so, find the
3814     // terms for V1 & (V2|V3).
3815     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3816       if (A == B)      // (A & C)|(A & D) == A & (C|D)
3817         V1 = A, V2 = C, V3 = D;
3818       else if (A == D) // (A & C)|(B & A) == A & (B|C)
3819         V1 = A, V2 = B, V3 = C;
3820       else if (C == B) // (A & C)|(C & D) == C & (A|D)
3821         V1 = C, V2 = A, V3 = D;
3822       else if (C == D) // (A & C)|(B & C) == C & (A|B)
3823         V1 = C, V2 = A, V3 = B;
3824       
3825       if (V1) {
3826         Value *Or =
3827           InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3828         return BinaryOperator::createAnd(V1, Or);
3829       }
3830       
3831       // (V1 & V3)|(V2 & ~V3) -> ((V1 ^ V2) & V3) ^ V2
3832       if (isOnlyUse(Op0) && isOnlyUse(Op1)) {
3833         // Try all combination of terms to find V3 and ~V3.
3834         if (A->hasOneUse() && match(A, m_Not(m_Value(V3)))) {
3835           if (V3 == B)
3836             V1 = D, V2 = C;
3837           else if (V3 == D)
3838             V1 = B, V2 = C;
3839         }
3840         if (B->hasOneUse() && match(B, m_Not(m_Value(V3)))) {
3841           if (V3 == A)
3842             V1 = C, V2 = D;
3843           else if (V3 == C)
3844             V1 = A, V2 = D;
3845         }
3846         if (C->hasOneUse() && match(C, m_Not(m_Value(V3)))) {
3847           if (V3 == B)
3848             V1 = D, V2 = A;
3849           else if (V3 == D)
3850             V1 = B, V2 = A;
3851         }
3852         if (D->hasOneUse() && match(D, m_Not(m_Value(V3)))) {
3853           if (V3 == A)
3854             V1 = C, V2 = B;
3855           else if (V3 == C)
3856             V1 = A, V2 = B;
3857         }
3858         if (V1) {
3859           A = InsertNewInstBefore(BinaryOperator::createXor(V1, V2, "tmp"), I);
3860           A = InsertNewInstBefore(BinaryOperator::createAnd(A, V3, "tmp"), I);
3861           return BinaryOperator::createXor(A, V2);
3862         }
3863       }
3864     }
3865   }
3866   
3867   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3868   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3869     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3870       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3871           SI0->getOperand(1) == SI1->getOperand(1) &&
3872           (SI0->hasOneUse() || SI1->hasOneUse())) {
3873         Instruction *NewOp =
3874         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3875                                                      SI1->getOperand(0),
3876                                                      SI0->getName()), I);
3877         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3878                                       SI1->getOperand(1));
3879       }
3880   }
3881
3882   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3883     if (A == Op1)   // ~A | A == -1
3884       return ReplaceInstUsesWith(I,
3885                                 ConstantInt::getAllOnesValue(I.getType()));
3886   } else {
3887     A = 0;
3888   }
3889   // Note, A is still live here!
3890   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3891     if (Op0 == B)
3892       return ReplaceInstUsesWith(I,
3893                                 ConstantInt::getAllOnesValue(I.getType()));
3894
3895     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3896     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3897       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3898                                               I.getName()+".demorgan"), I);
3899       return BinaryOperator::createNot(And);
3900     }
3901   }
3902
3903   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3904   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3905     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3906       return R;
3907
3908     Value *LHSVal, *RHSVal;
3909     ConstantInt *LHSCst, *RHSCst;
3910     ICmpInst::Predicate LHSCC, RHSCC;
3911     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3912       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3913         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
3914             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3915             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3916             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3917             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3918             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3919           // Ensure that the larger constant is on the RHS.
3920           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3921             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3922           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3923           ICmpInst *LHS = cast<ICmpInst>(Op0);
3924           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3925             std::swap(LHS, RHS);
3926             std::swap(LHSCst, RHSCst);
3927             std::swap(LHSCC, RHSCC);
3928           }
3929
3930           // At this point, we know we have have two icmp instructions
3931           // comparing a value against two constants and or'ing the result
3932           // together.  Because of the above check, we know that we only have
3933           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3934           // FoldICmpLogical check above), that the two constants are not
3935           // equal.
3936           assert(LHSCst != RHSCst && "Compares not folded above?");
3937
3938           switch (LHSCC) {
3939           default: assert(0 && "Unknown integer condition code!");
3940           case ICmpInst::ICMP_EQ:
3941             switch (RHSCC) {
3942             default: assert(0 && "Unknown integer condition code!");
3943             case ICmpInst::ICMP_EQ:
3944               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3945                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3946                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3947                                                       LHSVal->getName()+".off");
3948                 InsertNewInstBefore(Add, I);
3949                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
3950                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3951               }
3952               break;                         // (X == 13 | X == 15) -> no change
3953             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
3954             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
3955               break;
3956             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
3957             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
3958             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
3959               return ReplaceInstUsesWith(I, RHS);
3960             }
3961             break;
3962           case ICmpInst::ICMP_NE:
3963             switch (RHSCC) {
3964             default: assert(0 && "Unknown integer condition code!");
3965             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
3966             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
3967             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
3968               return ReplaceInstUsesWith(I, LHS);
3969             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
3970             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
3971             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
3972               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3973             }
3974             break;
3975           case ICmpInst::ICMP_ULT:
3976             switch (RHSCC) {
3977             default: assert(0 && "Unknown integer condition code!");
3978             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
3979               break;
3980             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
3981               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
3982                                      false, I);
3983             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
3984               break;
3985             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
3986             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
3987               return ReplaceInstUsesWith(I, RHS);
3988             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
3989               break;
3990             }
3991             break;
3992           case ICmpInst::ICMP_SLT:
3993             switch (RHSCC) {
3994             default: assert(0 && "Unknown integer condition code!");
3995             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
3996               break;
3997             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
3998               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
3999                                      false, I);
4000             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4001               break;
4002             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4003             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4004               return ReplaceInstUsesWith(I, RHS);
4005             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4006               break;
4007             }
4008             break;
4009           case ICmpInst::ICMP_UGT:
4010             switch (RHSCC) {
4011             default: assert(0 && "Unknown integer condition code!");
4012             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4013             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4014               return ReplaceInstUsesWith(I, LHS);
4015             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4016               break;
4017             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4018             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4019               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4020             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4021               break;
4022             }
4023             break;
4024           case ICmpInst::ICMP_SGT:
4025             switch (RHSCC) {
4026             default: assert(0 && "Unknown integer condition code!");
4027             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4028             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4029               return ReplaceInstUsesWith(I, LHS);
4030             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4031               break;
4032             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4033             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4034               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4035             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4036               break;
4037             }
4038             break;
4039           }
4040         }
4041   }
4042     
4043   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4044   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4045     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4046       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4047         const Type *SrcTy = Op0C->getOperand(0)->getType();
4048         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4049             // Only do this if the casts both really cause code to be generated.
4050             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4051                               I.getType(), TD) &&
4052             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4053                               I.getType(), TD)) {
4054           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4055                                                         Op1C->getOperand(0),
4056                                                         I.getName());
4057           InsertNewInstBefore(NewOp, I);
4058           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4059         }
4060       }
4061       
4062
4063   return Changed ? &I : 0;
4064 }
4065
4066 // XorSelf - Implements: X ^ X --> 0
4067 struct XorSelf {
4068   Value *RHS;
4069   XorSelf(Value *rhs) : RHS(rhs) {}
4070   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4071   Instruction *apply(BinaryOperator &Xor) const {
4072     return &Xor;
4073   }
4074 };
4075
4076
4077 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4078   bool Changed = SimplifyCommutative(I);
4079   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4080
4081   if (isa<UndefValue>(Op1))
4082     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4083
4084   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4085   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4086     assert(Result == &I && "AssociativeOpt didn't work?");
4087     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4088   }
4089   
4090   // See if we can simplify any instructions used by the instruction whose sole 
4091   // purpose is to compute bits we don't care about.
4092   if (!isa<VectorType>(I.getType())) {
4093     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4094     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4095     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4096                              KnownZero, KnownOne))
4097       return &I;
4098   }
4099
4100   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4101     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4102     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4103       if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
4104         return new ICmpInst(ICI->getInversePredicate(),
4105                             ICI->getOperand(0), ICI->getOperand(1));
4106
4107     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4108       // ~(c-X) == X-c-1 == X+(-c-1)
4109       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4110         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4111           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4112           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4113                                               ConstantInt::get(I.getType(), 1));
4114           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4115         }
4116
4117       // ~(~X & Y) --> (X | ~Y)
4118       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4119         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4120         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4121           Instruction *NotY =
4122             BinaryOperator::createNot(Op0I->getOperand(1),
4123                                       Op0I->getOperand(1)->getName()+".not");
4124           InsertNewInstBefore(NotY, I);
4125           return BinaryOperator::createOr(Op0NotVal, NotY);
4126         }
4127       }
4128           
4129       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4130         if (Op0I->getOpcode() == Instruction::Add) {
4131           // ~(X-c) --> (-c-1)-X
4132           if (RHS->isAllOnesValue()) {
4133             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4134             return BinaryOperator::createSub(
4135                            ConstantExpr::getSub(NegOp0CI,
4136                                              ConstantInt::get(I.getType(), 1)),
4137                                           Op0I->getOperand(0));
4138           } else if (RHS->getValue().isSignBit()) {
4139             // (X + C) ^ signbit -> (X + C + signbit)
4140             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4141             return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4142
4143           }
4144         } else if (Op0I->getOpcode() == Instruction::Or) {
4145           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4146           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4147             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4148             // Anything in both C1 and C2 is known to be zero, remove it from
4149             // NewRHS.
4150             Constant *CommonBits = And(Op0CI, RHS);
4151             NewRHS = ConstantExpr::getAnd(NewRHS, 
4152                                           ConstantExpr::getNot(CommonBits));
4153             AddToWorkList(Op0I);
4154             I.setOperand(0, Op0I->getOperand(0));
4155             I.setOperand(1, NewRHS);
4156             return &I;
4157           }
4158         }
4159     }
4160
4161     // Try to fold constant and into select arguments.
4162     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4163       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4164         return R;
4165     if (isa<PHINode>(Op0))
4166       if (Instruction *NV = FoldOpIntoPhi(I))
4167         return NV;
4168   }
4169
4170   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4171     if (X == Op1)
4172       return ReplaceInstUsesWith(I,
4173                                 ConstantInt::getAllOnesValue(I.getType()));
4174
4175   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4176     if (X == Op0)
4177       return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
4178
4179   
4180   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4181   if (Op1I) {
4182     Value *A, *B;
4183     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4184       if (A == Op0) {              // B^(B|A) == (A|B)^B
4185         Op1I->swapOperands();
4186         I.swapOperands();
4187         std::swap(Op0, Op1);
4188       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4189         I.swapOperands();     // Simplified below.
4190         std::swap(Op0, Op1);
4191       }
4192     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4193       if (Op0 == A)                                          // A^(A^B) == B
4194         return ReplaceInstUsesWith(I, B);
4195       else if (Op0 == B)                                     // A^(B^A) == B
4196         return ReplaceInstUsesWith(I, A);
4197     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4198       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4199         Op1I->swapOperands();
4200         std::swap(A, B);
4201       }
4202       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4203         I.swapOperands();     // Simplified below.
4204         std::swap(Op0, Op1);
4205       }
4206     }
4207   }
4208   
4209   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4210   if (Op0I) {
4211     Value *A, *B;
4212     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4213       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4214         std::swap(A, B);
4215       if (B == Op1) {                                // (A|B)^B == A & ~B
4216         Instruction *NotB =
4217           InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4218         return BinaryOperator::createAnd(A, NotB);
4219       }
4220     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4221       if (Op1 == A)                                          // (A^B)^A == B
4222         return ReplaceInstUsesWith(I, B);
4223       else if (Op1 == B)                                     // (B^A)^A == B
4224         return ReplaceInstUsesWith(I, A);
4225     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4226       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4227         std::swap(A, B);
4228       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4229           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4230         Instruction *N =
4231           InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4232         return BinaryOperator::createAnd(N, Op1);
4233       }
4234     }
4235   }
4236   
4237   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4238   if (Op0I && Op1I && Op0I->isShift() && 
4239       Op0I->getOpcode() == Op1I->getOpcode() && 
4240       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4241       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4242     Instruction *NewOp =
4243       InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4244                                                     Op1I->getOperand(0),
4245                                                     Op0I->getName()), I);
4246     return BinaryOperator::create(Op1I->getOpcode(), NewOp, 
4247                                   Op1I->getOperand(1));
4248   }
4249     
4250   if (Op0I && Op1I) {
4251     Value *A, *B, *C, *D;
4252     // (A & B)^(A | B) -> A ^ B
4253     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4254         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4255       if ((A == C && B == D) || (A == D && B == C)) 
4256         return BinaryOperator::createXor(A, B);
4257     }
4258     // (A | B)^(A & B) -> A ^ B
4259     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4260         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4261       if ((A == C && B == D) || (A == D && B == C)) 
4262         return BinaryOperator::createXor(A, B);
4263     }
4264     
4265     // (A & B)^(C & D)
4266     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4267         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4268         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4269       // (X & Y)^(X & Y) -> (Y^Z) & X
4270       Value *X = 0, *Y = 0, *Z = 0;
4271       if (A == C)
4272         X = A, Y = B, Z = D;
4273       else if (A == D)
4274         X = A, Y = B, Z = C;
4275       else if (B == C)
4276         X = B, Y = A, Z = D;
4277       else if (B == D)
4278         X = B, Y = A, Z = C;
4279       
4280       if (X) {
4281         Instruction *NewOp =
4282         InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4283         return BinaryOperator::createAnd(NewOp, X);
4284       }
4285     }
4286   }
4287     
4288   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4289   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4290     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4291       return R;
4292
4293   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4294   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4295     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4296       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4297         const Type *SrcTy = Op0C->getOperand(0)->getType();
4298         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4299             // Only do this if the casts both really cause code to be generated.
4300             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4301                               I.getType(), TD) &&
4302             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4303                               I.getType(), TD)) {
4304           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4305                                                          Op1C->getOperand(0),
4306                                                          I.getName());
4307           InsertNewInstBefore(NewOp, I);
4308           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4309         }
4310       }
4311
4312   return Changed ? &I : 0;
4313 }
4314
4315 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4316 /// overflowed for this type.
4317 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4318                             ConstantInt *In2, bool IsSigned = false) {
4319   Result = cast<ConstantInt>(Add(In1, In2));
4320
4321   if (IsSigned)
4322     if (In2->getValue().isNegative())
4323       return Result->getValue().sgt(In1->getValue());
4324     else
4325       return Result->getValue().slt(In1->getValue());
4326   else
4327     return Result->getValue().ult(In1->getValue());
4328 }
4329
4330 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4331 /// code necessary to compute the offset from the base pointer (without adding
4332 /// in the base pointer).  Return the result as a signed integer of intptr size.
4333 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4334   TargetData &TD = IC.getTargetData();
4335   gep_type_iterator GTI = gep_type_begin(GEP);
4336   const Type *IntPtrTy = TD.getIntPtrType();
4337   Value *Result = Constant::getNullValue(IntPtrTy);
4338
4339   // Build a mask for high order bits.
4340   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4341
4342   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4343     Value *Op = GEP->getOperand(i);
4344     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4345     Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4346     if (Constant *OpC = dyn_cast<Constant>(Op)) {
4347       if (!OpC->isNullValue()) {
4348         OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4349         Scale = ConstantExpr::getMul(OpC, Scale);
4350         if (Constant *RC = dyn_cast<Constant>(Result))
4351           Result = ConstantExpr::getAdd(RC, Scale);
4352         else {
4353           // Emit an add instruction.
4354           Result = IC.InsertNewInstBefore(
4355              BinaryOperator::createAdd(Result, Scale,
4356                                        GEP->getName()+".offs"), I);
4357         }
4358       }
4359     } else {
4360       // Convert to correct type.
4361       if (Op->getType() != IntPtrTy) {
4362         if (Constant *OpC = dyn_cast<Constant>(Op))
4363           Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4364         else
4365           Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4366                                                    Op->getName()+".c"), I);
4367       }
4368       if (Size != 1) {
4369         if (Constant *OpC = dyn_cast<Constant>(Op))
4370           Op = ConstantExpr::getMul(OpC, Scale);
4371         else    // We'll let instcombine(mul) convert this to a shl if possible.
4372           Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4373                                                     GEP->getName()+".idx"), I);
4374       }
4375
4376       // Emit an add instruction.
4377       if (isa<Constant>(Op) && isa<Constant>(Result))
4378         Result = ConstantExpr::getAdd(cast<Constant>(Op),
4379                                       cast<Constant>(Result));
4380       else
4381         Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4382                                                     GEP->getName()+".offs"), I);
4383     }
4384   }
4385   return Result;
4386 }
4387
4388 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4389 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4390 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4391                                        ICmpInst::Predicate Cond,
4392                                        Instruction &I) {
4393   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4394
4395   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4396     if (isa<PointerType>(CI->getOperand(0)->getType()))
4397       RHS = CI->getOperand(0);
4398
4399   Value *PtrBase = GEPLHS->getOperand(0);
4400   if (PtrBase == RHS) {
4401     // As an optimization, we don't actually have to compute the actual value of
4402     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4403     // each index is zero or not.
4404     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4405       Instruction *InVal = 0;
4406       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4407       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4408         bool EmitIt = true;
4409         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4410           if (isa<UndefValue>(C))  // undef index -> undef.
4411             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4412           if (C->isNullValue())
4413             EmitIt = false;
4414           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4415             EmitIt = false;  // This is indexing into a zero sized array?
4416           } else if (isa<ConstantInt>(C))
4417             return ReplaceInstUsesWith(I, // No comparison is needed here.
4418                                  ConstantInt::get(Type::Int1Ty, 
4419                                                   Cond == ICmpInst::ICMP_NE));
4420         }
4421
4422         if (EmitIt) {
4423           Instruction *Comp =
4424             new ICmpInst(Cond, GEPLHS->getOperand(i),
4425                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4426           if (InVal == 0)
4427             InVal = Comp;
4428           else {
4429             InVal = InsertNewInstBefore(InVal, I);
4430             InsertNewInstBefore(Comp, I);
4431             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4432               InVal = BinaryOperator::createOr(InVal, Comp);
4433             else                              // True if all are equal
4434               InVal = BinaryOperator::createAnd(InVal, Comp);
4435           }
4436         }
4437       }
4438
4439       if (InVal)
4440         return InVal;
4441       else
4442         // No comparison is needed here, all indexes = 0
4443         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4444                                                 Cond == ICmpInst::ICMP_EQ));
4445     }
4446
4447     // Only lower this if the icmp is the only user of the GEP or if we expect
4448     // the result to fold to a constant!
4449     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4450       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4451       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4452       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4453                           Constant::getNullValue(Offset->getType()));
4454     }
4455   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4456     // If the base pointers are different, but the indices are the same, just
4457     // compare the base pointer.
4458     if (PtrBase != GEPRHS->getOperand(0)) {
4459       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4460       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4461                         GEPRHS->getOperand(0)->getType();
4462       if (IndicesTheSame)
4463         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4464           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4465             IndicesTheSame = false;
4466             break;
4467           }
4468
4469       // If all indices are the same, just compare the base pointers.
4470       if (IndicesTheSame)
4471         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4472                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4473
4474       // Otherwise, the base pointers are different and the indices are
4475       // different, bail out.
4476       return 0;
4477     }
4478
4479     // If one of the GEPs has all zero indices, recurse.
4480     bool AllZeros = true;
4481     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4482       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4483           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4484         AllZeros = false;
4485         break;
4486       }
4487     if (AllZeros)
4488       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4489                           ICmpInst::getSwappedPredicate(Cond), I);
4490
4491     // If the other GEP has all zero indices, recurse.
4492     AllZeros = true;
4493     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4494       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4495           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4496         AllZeros = false;
4497         break;
4498       }
4499     if (AllZeros)
4500       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4501
4502     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4503       // If the GEPs only differ by one index, compare it.
4504       unsigned NumDifferences = 0;  // Keep track of # differences.
4505       unsigned DiffOperand = 0;     // The operand that differs.
4506       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4507         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4508           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4509                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4510             // Irreconcilable differences.
4511             NumDifferences = 2;
4512             break;
4513           } else {
4514             if (NumDifferences++) break;
4515             DiffOperand = i;
4516           }
4517         }
4518
4519       if (NumDifferences == 0)   // SAME GEP?
4520         return ReplaceInstUsesWith(I, // No comparison is needed here.
4521                                    ConstantInt::get(Type::Int1Ty, 
4522                                                     Cond == ICmpInst::ICMP_EQ));
4523       else if (NumDifferences == 1) {
4524         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4525         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4526         // Make sure we do a signed comparison here.
4527         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4528       }
4529     }
4530
4531     // Only lower this if the icmp is the only user of the GEP or if we expect
4532     // the result to fold to a constant!
4533     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4534         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4535       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4536       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4537       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4538       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4539     }
4540   }
4541   return 0;
4542 }
4543
4544 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4545   bool Changed = SimplifyCompare(I);
4546   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4547
4548   // Fold trivial predicates.
4549   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4550     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4551   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4552     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4553   
4554   // Simplify 'fcmp pred X, X'
4555   if (Op0 == Op1) {
4556     switch (I.getPredicate()) {
4557     default: assert(0 && "Unknown predicate!");
4558     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4559     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4560     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4561       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4562     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4563     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4564     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4565       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4566       
4567     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4568     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4569     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4570     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4571       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4572       I.setPredicate(FCmpInst::FCMP_UNO);
4573       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4574       return &I;
4575       
4576     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4577     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4578     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4579     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4580       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4581       I.setPredicate(FCmpInst::FCMP_ORD);
4582       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4583       return &I;
4584     }
4585   }
4586     
4587   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4588     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4589
4590   // Handle fcmp with constant RHS
4591   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4592     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4593       switch (LHSI->getOpcode()) {
4594       case Instruction::PHI:
4595         if (Instruction *NV = FoldOpIntoPhi(I))
4596           return NV;
4597         break;
4598       case Instruction::Select:
4599         // If either operand of the select is a constant, we can fold the
4600         // comparison into the select arms, which will cause one to be
4601         // constant folded and the select turned into a bitwise or.
4602         Value *Op1 = 0, *Op2 = 0;
4603         if (LHSI->hasOneUse()) {
4604           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4605             // Fold the known value into the constant operand.
4606             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4607             // Insert a new FCmp of the other select operand.
4608             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4609                                                       LHSI->getOperand(2), RHSC,
4610                                                       I.getName()), I);
4611           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4612             // Fold the known value into the constant operand.
4613             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4614             // Insert a new FCmp of the other select operand.
4615             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4616                                                       LHSI->getOperand(1), RHSC,
4617                                                       I.getName()), I);
4618           }
4619         }
4620
4621         if (Op1)
4622           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4623         break;
4624       }
4625   }
4626
4627   return Changed ? &I : 0;
4628 }
4629
4630 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4631   bool Changed = SimplifyCompare(I);
4632   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4633   const Type *Ty = Op0->getType();
4634
4635   // icmp X, X
4636   if (Op0 == Op1)
4637     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4638                                                    isTrueWhenEqual(I)));
4639
4640   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4641     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4642
4643   // icmp of GlobalValues can never equal each other as long as they aren't
4644   // external weak linkage type.
4645   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4646     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4647       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4648         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4649                                                        !isTrueWhenEqual(I)));
4650
4651   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4652   // addresses never equal each other!  We already know that Op0 != Op1.
4653   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4654        isa<ConstantPointerNull>(Op0)) &&
4655       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4656        isa<ConstantPointerNull>(Op1)))
4657     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4658                                                    !isTrueWhenEqual(I)));
4659
4660   // icmp's with boolean values can always be turned into bitwise operations
4661   if (Ty == Type::Int1Ty) {
4662     switch (I.getPredicate()) {
4663     default: assert(0 && "Invalid icmp instruction!");
4664     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4665       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4666       InsertNewInstBefore(Xor, I);
4667       return BinaryOperator::createNot(Xor);
4668     }
4669     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4670       return BinaryOperator::createXor(Op0, Op1);
4671
4672     case ICmpInst::ICMP_UGT:
4673     case ICmpInst::ICMP_SGT:
4674       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4675       // FALL THROUGH
4676     case ICmpInst::ICMP_ULT:
4677     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4678       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4679       InsertNewInstBefore(Not, I);
4680       return BinaryOperator::createAnd(Not, Op1);
4681     }
4682     case ICmpInst::ICMP_UGE:
4683     case ICmpInst::ICMP_SGE:
4684       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4685       // FALL THROUGH
4686     case ICmpInst::ICMP_ULE:
4687     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4688       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4689       InsertNewInstBefore(Not, I);
4690       return BinaryOperator::createOr(Not, Op1);
4691     }
4692     }
4693   }
4694
4695   // See if we are doing a comparison between a constant and an instruction that
4696   // can be folded into the comparison.
4697   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4698     switch (I.getPredicate()) {
4699     default: break;
4700     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4701       if (CI->isMinValue(false))
4702         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4703       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4704         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4705       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4706         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4707       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
4708       if (CI->isMinValue(true))
4709         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4710                             ConstantInt::getAllOnesValue(Op0->getType()));
4711           
4712       break;
4713
4714     case ICmpInst::ICMP_SLT:
4715       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4716         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4717       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4718         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4719       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4720         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4721       break;
4722
4723     case ICmpInst::ICMP_UGT:
4724       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4725         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4726       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4727         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4728       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4729         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4730         
4731       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
4732       if (CI->isMaxValue(true))
4733         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4734                             ConstantInt::getNullValue(Op0->getType()));
4735       break;
4736
4737     case ICmpInst::ICMP_SGT:
4738       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4739         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4740       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4741         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4742       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4743         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4744       break;
4745
4746     case ICmpInst::ICMP_ULE:
4747       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4748         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4749       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4750         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4751       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4752         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4753       break;
4754
4755     case ICmpInst::ICMP_SLE:
4756       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4757         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4758       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4759         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4760       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4761         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4762       break;
4763
4764     case ICmpInst::ICMP_UGE:
4765       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4766         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4767       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4768         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4769       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4770         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4771       break;
4772
4773     case ICmpInst::ICMP_SGE:
4774       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4775         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4776       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4777         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4778       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4779         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4780       break;
4781     }
4782
4783     // If we still have a icmp le or icmp ge instruction, turn it into the
4784     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4785     // already been handled above, this requires little checking.
4786     //
4787     switch (I.getPredicate()) {
4788       default: break;
4789       case ICmpInst::ICMP_ULE: 
4790         return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4791       case ICmpInst::ICMP_SLE:
4792         return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4793       case ICmpInst::ICMP_UGE:
4794         return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4795       case ICmpInst::ICMP_SGE:
4796         return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4797     }
4798     
4799     // See if we can fold the comparison based on bits known to be zero or one
4800     // in the input.
4801     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4802     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4803     if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
4804                              KnownZero, KnownOne, 0))
4805       return &I;
4806         
4807     // Given the known and unknown bits, compute a range that the LHS could be
4808     // in.
4809     if ((KnownOne | KnownZero) != 0) {
4810       // Compute the Min, Max and RHS values based on the known bits. For the
4811       // EQ and NE we use unsigned values.
4812       APInt Min(BitWidth, 0), Max(BitWidth, 0);
4813       const APInt& RHSVal = CI->getValue();
4814       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4815         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
4816                                                Max);
4817       } else {
4818         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
4819                                                  Max);
4820       }
4821       switch (I.getPredicate()) {  // LE/GE have been folded already.
4822       default: assert(0 && "Unknown icmp opcode!");
4823       case ICmpInst::ICMP_EQ:
4824         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4825           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4826         break;
4827       case ICmpInst::ICMP_NE:
4828         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4829           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4830         break;
4831       case ICmpInst::ICMP_ULT:
4832         if (Max.ult(RHSVal))
4833           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4834         if (Min.uge(RHSVal))
4835           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4836         break;
4837       case ICmpInst::ICMP_UGT:
4838         if (Min.ugt(RHSVal))
4839           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4840         if (Max.ule(RHSVal))
4841           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4842         break;
4843       case ICmpInst::ICMP_SLT:
4844         if (Max.slt(RHSVal))
4845           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4846         if (Min.sgt(RHSVal))
4847           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4848         break;
4849       case ICmpInst::ICMP_SGT: 
4850         if (Min.sgt(RHSVal))
4851           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4852         if (Max.sle(RHSVal))
4853           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4854         break;
4855       }
4856     }
4857           
4858     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
4859     // instruction, see if that instruction also has constants so that the 
4860     // instruction can be folded into the icmp 
4861     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4862       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
4863         return Res;
4864   }
4865
4866   // Handle icmp with constant (but not simple integer constant) RHS
4867   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4868     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4869       switch (LHSI->getOpcode()) {
4870       case Instruction::GetElementPtr:
4871         if (RHSC->isNullValue()) {
4872           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
4873           bool isAllZeros = true;
4874           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4875             if (!isa<Constant>(LHSI->getOperand(i)) ||
4876                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4877               isAllZeros = false;
4878               break;
4879             }
4880           if (isAllZeros)
4881             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
4882                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
4883         }
4884         break;
4885
4886       case Instruction::PHI:
4887         if (Instruction *NV = FoldOpIntoPhi(I))
4888           return NV;
4889         break;
4890       case Instruction::Select: {
4891         // If either operand of the select is a constant, we can fold the
4892         // comparison into the select arms, which will cause one to be
4893         // constant folded and the select turned into a bitwise or.
4894         Value *Op1 = 0, *Op2 = 0;
4895         if (LHSI->hasOneUse()) {
4896           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4897             // Fold the known value into the constant operand.
4898             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4899             // Insert a new ICmp of the other select operand.
4900             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4901                                                    LHSI->getOperand(2), RHSC,
4902                                                    I.getName()), I);
4903           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4904             // Fold the known value into the constant operand.
4905             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4906             // Insert a new ICmp of the other select operand.
4907             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4908                                                    LHSI->getOperand(1), RHSC,
4909                                                    I.getName()), I);
4910           }
4911         }
4912
4913         if (Op1)
4914           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4915         break;
4916       }
4917       case Instruction::Malloc:
4918         // If we have (malloc != null), and if the malloc has a single use, we
4919         // can assume it is successful and remove the malloc.
4920         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
4921           AddToWorkList(LHSI);
4922           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4923                                                          !isTrueWhenEqual(I)));
4924         }
4925         break;
4926       }
4927   }
4928
4929   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
4930   if (User *GEP = dyn_castGetElementPtr(Op0))
4931     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
4932       return NI;
4933   if (User *GEP = dyn_castGetElementPtr(Op1))
4934     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
4935                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
4936       return NI;
4937
4938   // Test to see if the operands of the icmp are casted versions of other
4939   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
4940   // now.
4941   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
4942     if (isa<PointerType>(Op0->getType()) && 
4943         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
4944       // We keep moving the cast from the left operand over to the right
4945       // operand, where it can often be eliminated completely.
4946       Op0 = CI->getOperand(0);
4947
4948       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
4949       // so eliminate it as well.
4950       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
4951         Op1 = CI2->getOperand(0);
4952
4953       // If Op1 is a constant, we can fold the cast into the constant.
4954       if (Op0->getType() != Op1->getType())
4955         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4956           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
4957         } else {
4958           // Otherwise, cast the RHS right before the icmp
4959           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
4960         }
4961       return new ICmpInst(I.getPredicate(), Op0, Op1);
4962     }
4963   }
4964   
4965   if (isa<CastInst>(Op0)) {
4966     // Handle the special case of: icmp (cast bool to X), <cst>
4967     // This comes up when you have code like
4968     //   int X = A < B;
4969     //   if (X) ...
4970     // For generality, we handle any zero-extension of any operand comparison
4971     // with a constant or another cast from the same type.
4972     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4973       if (Instruction *R = visitICmpInstWithCastAndCast(I))
4974         return R;
4975   }
4976   
4977   if (I.isEquality()) {
4978     Value *A, *B, *C, *D;
4979     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4980       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
4981         Value *OtherVal = A == Op1 ? B : A;
4982         return new ICmpInst(I.getPredicate(), OtherVal,
4983                             Constant::getNullValue(A->getType()));
4984       }
4985
4986       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4987         // A^c1 == C^c2 --> A == C^(c1^c2)
4988         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
4989           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
4990             if (Op1->hasOneUse()) {
4991               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
4992               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
4993               return new ICmpInst(I.getPredicate(), A,
4994                                   InsertNewInstBefore(Xor, I));
4995             }
4996         
4997         // A^B == A^D -> B == D
4998         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
4999         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5000         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5001         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5002       }
5003     }
5004     
5005     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5006         (A == Op0 || B == Op0)) {
5007       // A == (A^B)  ->  B == 0
5008       Value *OtherVal = A == Op0 ? B : A;
5009       return new ICmpInst(I.getPredicate(), OtherVal,
5010                           Constant::getNullValue(A->getType()));
5011     }
5012     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5013       // (A-B) == A  ->  B == 0
5014       return new ICmpInst(I.getPredicate(), B,
5015                           Constant::getNullValue(B->getType()));
5016     }
5017     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5018       // A == (A-B)  ->  B == 0
5019       return new ICmpInst(I.getPredicate(), B,
5020                           Constant::getNullValue(B->getType()));
5021     }
5022     
5023     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5024     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5025         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5026         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5027       Value *X = 0, *Y = 0, *Z = 0;
5028       
5029       if (A == C) {
5030         X = B; Y = D; Z = A;
5031       } else if (A == D) {
5032         X = B; Y = C; Z = A;
5033       } else if (B == C) {
5034         X = A; Y = D; Z = B;
5035       } else if (B == D) {
5036         X = A; Y = C; Z = B;
5037       }
5038       
5039       if (X) {   // Build (X^Y) & Z
5040         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5041         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5042         I.setOperand(0, Op1);
5043         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5044         return &I;
5045       }
5046     }
5047   }
5048   return Changed ? &I : 0;
5049 }
5050
5051 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5052 ///
5053 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5054                                                           Instruction *LHSI,
5055                                                           ConstantInt *RHS) {
5056   const APInt &RHSV = RHS->getValue();
5057   
5058   switch (LHSI->getOpcode()) {
5059   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5060     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5061       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5062       // fold the xor.
5063       if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5064           ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5065         Value *CompareVal = LHSI->getOperand(0);
5066         
5067         // If the sign bit of the XorCST is not set, there is no change to
5068         // the operation, just stop using the Xor.
5069         if (!XorCST->getValue().isNegative()) {
5070           ICI.setOperand(0, CompareVal);
5071           AddToWorkList(LHSI);
5072           return &ICI;
5073         }
5074         
5075         // Was the old condition true if the operand is positive?
5076         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5077         
5078         // If so, the new one isn't.
5079         isTrueIfPositive ^= true;
5080         
5081         if (isTrueIfPositive)
5082           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5083         else
5084           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5085       }
5086     }
5087     break;
5088   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5089     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5090         LHSI->getOperand(0)->hasOneUse()) {
5091       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5092       
5093       // If the LHS is an AND of a truncating cast, we can widen the
5094       // and/compare to be the input width without changing the value
5095       // produced, eliminating a cast.
5096       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5097         // We can do this transformation if either the AND constant does not
5098         // have its sign bit set or if it is an equality comparison. 
5099         // Extending a relational comparison when we're checking the sign
5100         // bit would not work.
5101         if (Cast->hasOneUse() &&
5102             (ICI.isEquality() || AndCST->getValue().isPositive() && 
5103              RHSV.isPositive())) {
5104           uint32_t BitWidth = 
5105             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5106           APInt NewCST = AndCST->getValue();
5107           NewCST.zext(BitWidth);
5108           APInt NewCI = RHSV;
5109           NewCI.zext(BitWidth);
5110           Instruction *NewAnd = 
5111             BinaryOperator::createAnd(Cast->getOperand(0),
5112                                       ConstantInt::get(NewCST),LHSI->getName());
5113           InsertNewInstBefore(NewAnd, ICI);
5114           return new ICmpInst(ICI.getPredicate(), NewAnd,
5115                               ConstantInt::get(NewCI));
5116         }
5117       }
5118       
5119       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5120       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5121       // happens a LOT in code produced by the C front-end, for bitfield
5122       // access.
5123       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5124       if (Shift && !Shift->isShift())
5125         Shift = 0;
5126       
5127       ConstantInt *ShAmt;
5128       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5129       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5130       const Type *AndTy = AndCST->getType();          // Type of the and.
5131       
5132       // We can fold this as long as we can't shift unknown bits
5133       // into the mask.  This can only happen with signed shift
5134       // rights, as they sign-extend.
5135       if (ShAmt) {
5136         bool CanFold = Shift->isLogicalShift();
5137         if (!CanFold) {
5138           // To test for the bad case of the signed shr, see if any
5139           // of the bits shifted in could be tested after the mask.
5140           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5141           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5142           
5143           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5144           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5145                AndCST->getValue()) == 0)
5146             CanFold = true;
5147         }
5148         
5149         if (CanFold) {
5150           Constant *NewCst;
5151           if (Shift->getOpcode() == Instruction::Shl)
5152             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5153           else
5154             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5155           
5156           // Check to see if we are shifting out any of the bits being
5157           // compared.
5158           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5159             // If we shifted bits out, the fold is not going to work out.
5160             // As a special case, check to see if this means that the
5161             // result is always true or false now.
5162             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5163               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5164             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5165               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5166           } else {
5167             ICI.setOperand(1, NewCst);
5168             Constant *NewAndCST;
5169             if (Shift->getOpcode() == Instruction::Shl)
5170               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5171             else
5172               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5173             LHSI->setOperand(1, NewAndCST);
5174             LHSI->setOperand(0, Shift->getOperand(0));
5175             AddToWorkList(Shift); // Shift is dead.
5176             AddUsesToWorkList(ICI);
5177             return &ICI;
5178           }
5179         }
5180       }
5181       
5182       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5183       // preferable because it allows the C<<Y expression to be hoisted out
5184       // of a loop if Y is invariant and X is not.
5185       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5186           ICI.isEquality() && !Shift->isArithmeticShift() &&
5187           isa<Instruction>(Shift->getOperand(0))) {
5188         // Compute C << Y.
5189         Value *NS;
5190         if (Shift->getOpcode() == Instruction::LShr) {
5191           NS = BinaryOperator::createShl(AndCST, 
5192                                          Shift->getOperand(1), "tmp");
5193         } else {
5194           // Insert a logical shift.
5195           NS = BinaryOperator::createLShr(AndCST,
5196                                           Shift->getOperand(1), "tmp");
5197         }
5198         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5199         
5200         // Compute X & (C << Y).
5201         Instruction *NewAnd = 
5202           BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5203         InsertNewInstBefore(NewAnd, ICI);
5204         
5205         ICI.setOperand(0, NewAnd);
5206         return &ICI;
5207       }
5208     }
5209     break;
5210     
5211   case Instruction::Shl:         // (icmp pred (shl X, ShAmt), CI)
5212     if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5213       if (ICI.isEquality()) {
5214         uint32_t TypeBits = RHSV.getBitWidth();
5215         
5216         // Check that the shift amount is in range.  If not, don't perform
5217         // undefined shifts.  When the shift is visited it will be
5218         // simplified.
5219         if (ShAmt->uge(TypeBits))
5220           break;
5221         
5222         // If we are comparing against bits always shifted out, the
5223         // comparison cannot succeed.
5224         Constant *Comp =
5225           ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5226         if (Comp != RHS) {// Comparing against a bit that we know is zero.
5227           bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5228           Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5229           return ReplaceInstUsesWith(ICI, Cst);
5230         }
5231         
5232         if (LHSI->hasOneUse()) {
5233           // Otherwise strength reduce the shift into an and.
5234           uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5235           Constant *Mask =
5236             ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5237           
5238           Instruction *AndI =
5239             BinaryOperator::createAnd(LHSI->getOperand(0),
5240                                       Mask, LHSI->getName()+".mask");
5241           Value *And = InsertNewInstBefore(AndI, ICI);
5242           return new ICmpInst(ICI.getPredicate(), And,
5243                               ConstantInt::get(RHSV.lshr(ShAmtVal)));
5244         }
5245       }
5246     }
5247     break;
5248     
5249   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5250   case Instruction::AShr:
5251     if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5252       if (ICI.isEquality()) {
5253         // Check that the shift amount is in range.  If not, don't perform
5254         // undefined shifts.  When the shift is visited it will be
5255         // simplified.
5256         uint32_t TypeBits = RHSV.getBitWidth();
5257         if (ShAmt->uge(TypeBits))
5258           break;
5259         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5260         
5261         // If we are comparing against bits always shifted out, the
5262         // comparison cannot succeed.
5263         APInt Comp = RHSV << ShAmtVal;
5264         if (LHSI->getOpcode() == Instruction::LShr)
5265           Comp = Comp.lshr(ShAmtVal);
5266         else
5267           Comp = Comp.ashr(ShAmtVal);
5268         
5269         if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5270           bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5271           Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5272           return ReplaceInstUsesWith(ICI, Cst);
5273         }
5274         
5275         if (LHSI->hasOneUse() || RHSV == 0) {
5276           // Otherwise strength reduce the shift into an and.
5277           APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5278           Constant *Mask = ConstantInt::get(Val);
5279           
5280           Instruction *AndI =
5281             BinaryOperator::createAnd(LHSI->getOperand(0),
5282                                       Mask, LHSI->getName()+".mask");
5283           Value *And = InsertNewInstBefore(AndI, ICI);
5284           return new ICmpInst(ICI.getPredicate(), And,
5285                               ConstantExpr::getShl(RHS, ShAmt));
5286         }
5287       }
5288     }
5289     break;
5290     
5291   case Instruction::SDiv:
5292   case Instruction::UDiv:
5293     // Fold: icmp pred ([us]div X, C1), C2 -> range test
5294     // Fold this div into the comparison, producing a range check. 
5295     // Determine, based on the divide type, what the range is being 
5296     // checked.  If there is an overflow on the low or high side, remember 
5297     // it, otherwise compute the range [low, hi) bounding the new value.
5298     // See: InsertRangeTest above for the kinds of replacements possible.
5299     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5300       // FIXME: If the operand types don't match the type of the divide 
5301       // then don't attempt this transform. The code below doesn't have the
5302       // logic to deal with a signed divide and an unsigned compare (and
5303       // vice versa). This is because (x /s C1) <s C2  produces different 
5304       // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5305       // (x /u C1) <u C2.  Simply casting the operands and result won't 
5306       // work. :(  The if statement below tests that condition and bails 
5307       // if it finds it. 
5308       bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5309       if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5310         break;
5311       if (DivRHS->isZero())
5312         break; // Don't hack on div by zero
5313       
5314       // Initialize the variables that will indicate the nature of the
5315       // range check.
5316       bool LoOverflow = false, HiOverflow = false;
5317       ConstantInt *LoBound = 0, *HiBound = 0;
5318       
5319       // Compute Prod = CI * DivRHS. We are essentially solving an equation
5320       // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5321       // C2 (CI). By solving for X we can turn this into a range check 
5322       // instead of computing a divide. 
5323       ConstantInt *Prod = Multiply(RHS, DivRHS);
5324       
5325       // Determine if the product overflows by seeing if the product is
5326       // not equal to the divide. Make sure we do the same kind of divide
5327       // as in the LHS instruction that we're folding. 
5328       bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5329                      ConstantExpr::getUDiv(Prod, DivRHS)) != RHS;
5330       
5331       // Get the ICmp opcode
5332       ICmpInst::Predicate predicate = ICI.getPredicate();
5333       
5334       if (!DivIsSigned) {  // udiv
5335         LoBound = Prod;
5336         LoOverflow = ProdOV;
5337         HiOverflow = ProdOV || 
5338           AddWithOverflow(HiBound, LoBound, DivRHS, false);
5339       } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5340         if (RHSV == 0) {       // (X / pos) op 0
5341                                // Can't overflow.
5342           LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5343           HiBound = DivRHS;
5344         } else if (RHSV.isPositive()) {   // (X / pos) op pos
5345           LoBound = Prod;
5346           LoOverflow = ProdOV;
5347           HiOverflow = ProdOV || 
5348             AddWithOverflow(HiBound, Prod, DivRHS, true);
5349         } else {                       // (X / pos) op neg
5350           Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5351           LoOverflow = AddWithOverflow(LoBound, Prod,
5352                                        cast<ConstantInt>(DivRHSH), true);
5353           HiBound = AddOne(Prod);
5354           HiOverflow = ProdOV;
5355         }
5356       } else {                         // Divisor is < 0.
5357         if (RHSV == 0) {       // (X / neg) op 0
5358           LoBound = AddOne(DivRHS);
5359           HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5360           if (HiBound == DivRHS)
5361             LoBound = 0;               // - INTMIN = INTMIN
5362         } else if (RHSV.isPositive()) {   // (X / neg) op pos
5363           HiOverflow = LoOverflow = ProdOV;
5364           if (!LoOverflow)
5365             LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
5366                                          true);
5367           HiBound = AddOne(Prod);
5368         } else {                       // (X / neg) op neg
5369           LoBound = Prod;
5370           LoOverflow = HiOverflow = ProdOV;
5371           HiBound = Subtract(Prod, DivRHS);
5372         }
5373         
5374         // Dividing by a negate swaps the condition.
5375         predicate = ICmpInst::getSwappedPredicate(predicate);
5376       }
5377       
5378       if (LoBound) {
5379         Value *X = LHSI->getOperand(0);
5380         switch (predicate) {
5381           default: assert(0 && "Unhandled icmp opcode!");
5382           case ICmpInst::ICMP_EQ:
5383             if (LoOverflow && HiOverflow)
5384               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5385             else if (HiOverflow)
5386               return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SGE : 
5387                                   ICmpInst::ICMP_UGE, X, LoBound);
5388             else if (LoOverflow)
5389               return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5390                                   ICmpInst::ICMP_ULT, X, HiBound);
5391             else
5392               return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
5393                                      true, ICI);
5394           case ICmpInst::ICMP_NE:
5395             if (LoOverflow && HiOverflow)
5396               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5397             else if (HiOverflow)
5398               return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SLT : 
5399                                   ICmpInst::ICMP_ULT, X, LoBound);
5400             else if (LoOverflow)
5401               return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5402                                   ICmpInst::ICMP_UGE, X, HiBound);
5403             else
5404               return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
5405                                      false, ICI);
5406           case ICmpInst::ICMP_ULT:
5407           case ICmpInst::ICMP_SLT:
5408             if (LoOverflow)
5409               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5410             return new ICmpInst(predicate, X, LoBound);
5411           case ICmpInst::ICMP_UGT:
5412           case ICmpInst::ICMP_SGT:
5413             if (HiOverflow)
5414               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5415             if (predicate == ICmpInst::ICMP_UGT)
5416               return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5417             else
5418               return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5419         }
5420       }
5421     }
5422     break;
5423   }
5424   
5425   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5426   if (ICI.isEquality()) {
5427     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5428     
5429     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
5430     // the second operand is a constant, simplify a bit.
5431     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5432       switch (BO->getOpcode()) {
5433       case Instruction::SRem:
5434         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5435         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5436           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5437           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5438             Instruction *NewRem =
5439               BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5440                                          BO->getName());
5441             InsertNewInstBefore(NewRem, ICI);
5442             return new ICmpInst(ICI.getPredicate(), NewRem, 
5443                                 Constant::getNullValue(BO->getType()));
5444           }
5445         }
5446         break;
5447       case Instruction::Add:
5448         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5449         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5450           if (BO->hasOneUse())
5451             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5452                                 Subtract(RHS, BOp1C));
5453         } else if (RHSV == 0) {
5454           // Replace ((add A, B) != 0) with (A != -B) if A or B is
5455           // efficiently invertible, or if the add has just this one use.
5456           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5457           
5458           if (Value *NegVal = dyn_castNegVal(BOp1))
5459             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5460           else if (Value *NegVal = dyn_castNegVal(BOp0))
5461             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5462           else if (BO->hasOneUse()) {
5463             Instruction *Neg = BinaryOperator::createNeg(BOp1);
5464             InsertNewInstBefore(Neg, ICI);
5465             Neg->takeName(BO);
5466             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5467           }
5468         }
5469         break;
5470       case Instruction::Xor:
5471         // For the xor case, we can xor two constants together, eliminating
5472         // the explicit xor.
5473         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5474           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
5475                               ConstantExpr::getXor(RHS, BOC));
5476         
5477         // FALLTHROUGH
5478       case Instruction::Sub:
5479         // Replace (([sub|xor] A, B) != 0) with (A != B)
5480         if (RHSV == 0)
5481           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5482                               BO->getOperand(1));
5483         break;
5484         
5485       case Instruction::Or:
5486         // If bits are being or'd in that are not present in the constant we
5487         // are comparing against, then the comparison could never succeed!
5488         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5489           Constant *NotCI = ConstantExpr::getNot(RHS);
5490           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5491             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
5492                                                              isICMP_NE));
5493         }
5494         break;
5495         
5496       case Instruction::And:
5497         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5498           // If bits are being compared against that are and'd out, then the
5499           // comparison can never succeed!
5500           if ((RHSV & ~BOC->getValue()) != 0)
5501             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5502                                                              isICMP_NE));
5503           
5504           // If we have ((X & C) == C), turn it into ((X & C) != 0).
5505           if (RHS == BOC && RHSV.isPowerOf2())
5506             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5507                                 ICmpInst::ICMP_NE, LHSI,
5508                                 Constant::getNullValue(RHS->getType()));
5509           
5510           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5511           if (isSignBit(BOC)) {
5512             Value *X = BO->getOperand(0);
5513             Constant *Zero = Constant::getNullValue(X->getType());
5514             ICmpInst::Predicate pred = isICMP_NE ? 
5515               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5516             return new ICmpInst(pred, X, Zero);
5517           }
5518           
5519           // ((X & ~7) == 0) --> X < 8
5520           if (RHSV == 0 && isHighOnes(BOC)) {
5521             Value *X = BO->getOperand(0);
5522             Constant *NegX = ConstantExpr::getNeg(BOC);
5523             ICmpInst::Predicate pred = isICMP_NE ? 
5524               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5525             return new ICmpInst(pred, X, NegX);
5526           }
5527         }
5528       default: break;
5529       }
5530     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5531       // Handle icmp {eq|ne} <intrinsic>, intcst.
5532       if (II->getIntrinsicID() == Intrinsic::bswap) {
5533         AddToWorkList(II);
5534         ICI.setOperand(0, II->getOperand(1));
5535         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5536         return &ICI;
5537       }
5538     }
5539   } else {  // Not a ICMP_EQ/ICMP_NE
5540             // If the LHS is a cast from an integral value of the same size, 
5541             // then since we know the RHS is a constant, try to simlify.
5542     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5543       Value *CastOp = Cast->getOperand(0);
5544       const Type *SrcTy = CastOp->getType();
5545       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5546       if (SrcTy->isInteger() && 
5547           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5548         // If this is an unsigned comparison, try to make the comparison use
5549         // smaller constant values.
5550         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5551           // X u< 128 => X s> -1
5552           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5553                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5554         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5555                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5556           // X u> 127 => X s< 0
5557           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5558                               Constant::getNullValue(SrcTy));
5559         }
5560       }
5561     }
5562   }
5563   return 0;
5564 }
5565
5566 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5567 /// We only handle extending casts so far.
5568 ///
5569 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5570   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5571   Value *LHSCIOp        = LHSCI->getOperand(0);
5572   const Type *SrcTy     = LHSCIOp->getType();
5573   const Type *DestTy    = LHSCI->getType();
5574   Value *RHSCIOp;
5575
5576   // We only handle extension cast instructions, so far. Enforce this.
5577   if (LHSCI->getOpcode() != Instruction::ZExt &&
5578       LHSCI->getOpcode() != Instruction::SExt)
5579     return 0;
5580
5581   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5582   bool isSignedCmp = ICI.isSignedPredicate();
5583
5584   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5585     // Not an extension from the same type?
5586     RHSCIOp = CI->getOperand(0);
5587     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5588       return 0;
5589     
5590     // If the signedness of the two compares doesn't agree (i.e. one is a sext
5591     // and the other is a zext), then we can't handle this.
5592     if (CI->getOpcode() != LHSCI->getOpcode())
5593       return 0;
5594
5595     // Likewise, if the signedness of the [sz]exts and the compare don't match, 
5596     // then we can't handle this.
5597     if (isSignedExt != isSignedCmp && !ICI.isEquality())
5598       return 0;
5599     
5600     // Okay, just insert a compare of the reduced operands now!
5601     return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5602   }
5603
5604   // If we aren't dealing with a constant on the RHS, exit early
5605   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5606   if (!CI)
5607     return 0;
5608
5609   // Compute the constant that would happen if we truncated to SrcTy then
5610   // reextended to DestTy.
5611   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5612   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5613
5614   // If the re-extended constant didn't change...
5615   if (Res2 == CI) {
5616     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5617     // For example, we might have:
5618     //    %A = sext short %X to uint
5619     //    %B = icmp ugt uint %A, 1330
5620     // It is incorrect to transform this into 
5621     //    %B = icmp ugt short %X, 1330 
5622     // because %A may have negative value. 
5623     //
5624     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5625     // OR operation is EQ/NE.
5626     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5627       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5628     else
5629       return 0;
5630   }
5631
5632   // The re-extended constant changed so the constant cannot be represented 
5633   // in the shorter type. Consequently, we cannot emit a simple comparison.
5634
5635   // First, handle some easy cases. We know the result cannot be equal at this
5636   // point so handle the ICI.isEquality() cases
5637   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5638     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5639   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5640     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5641
5642   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5643   // should have been folded away previously and not enter in here.
5644   Value *Result;
5645   if (isSignedCmp) {
5646     // We're performing a signed comparison.
5647     if (cast<ConstantInt>(CI)->getValue().isNegative())
5648       Result = ConstantInt::getFalse();          // X < (small) --> false
5649     else
5650       Result = ConstantInt::getTrue();           // X < (large) --> true
5651   } else {
5652     // We're performing an unsigned comparison.
5653     if (isSignedExt) {
5654       // We're performing an unsigned comp with a sign extended value.
5655       // This is true if the input is >= 0. [aka >s -1]
5656       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5657       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5658                                    NegOne, ICI.getName()), ICI);
5659     } else {
5660       // Unsigned extend & unsigned compare -> always true.
5661       Result = ConstantInt::getTrue();
5662     }
5663   }
5664
5665   // Finally, return the value computed.
5666   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5667       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5668     return ReplaceInstUsesWith(ICI, Result);
5669   } else {
5670     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5671             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5672            "ICmp should be folded!");
5673     if (Constant *CI = dyn_cast<Constant>(Result))
5674       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5675     else
5676       return BinaryOperator::createNot(Result);
5677   }
5678 }
5679
5680 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5681   return commonShiftTransforms(I);
5682 }
5683
5684 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5685   return commonShiftTransforms(I);
5686 }
5687
5688 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5689   return commonShiftTransforms(I);
5690 }
5691
5692 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5693   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
5694   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5695
5696   // shl X, 0 == X and shr X, 0 == X
5697   // shl 0, X == 0 and shr 0, X == 0
5698   if (Op1 == Constant::getNullValue(Op1->getType()) ||
5699       Op0 == Constant::getNullValue(Op0->getType()))
5700     return ReplaceInstUsesWith(I, Op0);
5701   
5702   if (isa<UndefValue>(Op0)) {            
5703     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5704       return ReplaceInstUsesWith(I, Op0);
5705     else                                    // undef << X -> 0, undef >>u X -> 0
5706       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5707   }
5708   if (isa<UndefValue>(Op1)) {
5709     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5710       return ReplaceInstUsesWith(I, Op0);          
5711     else                                     // X << undef, X >>u undef -> 0
5712       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5713   }
5714
5715   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5716   if (I.getOpcode() == Instruction::AShr)
5717     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5718       if (CSI->isAllOnesValue())
5719         return ReplaceInstUsesWith(I, CSI);
5720
5721   // Try to fold constant and into select arguments.
5722   if (isa<Constant>(Op0))
5723     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5724       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5725         return R;
5726
5727   // See if we can turn a signed shr into an unsigned shr.
5728   if (I.isArithmeticShift()) {
5729     if (MaskedValueIsZero(Op0, 
5730           APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
5731       return BinaryOperator::createLShr(Op0, Op1, I.getName());
5732     }
5733   }
5734
5735   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5736     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5737       return Res;
5738   return 0;
5739 }
5740
5741 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5742                                                BinaryOperator &I) {
5743   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5744
5745   // See if we can simplify any instructions used by the instruction whose sole 
5746   // purpose is to compute bits we don't care about.
5747   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5748   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5749   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
5750                            KnownZero, KnownOne))
5751     return &I;
5752   
5753   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5754   // of a signed value.
5755   //
5756   if (Op1->uge(TypeBits)) {
5757     if (I.getOpcode() != Instruction::AShr)
5758       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5759     else {
5760       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
5761       return &I;
5762     }
5763   }
5764   
5765   // ((X*C1) << C2) == (X * (C1 << C2))
5766   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5767     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5768       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5769         return BinaryOperator::createMul(BO->getOperand(0),
5770                                          ConstantExpr::getShl(BOOp, Op1));
5771   
5772   // Try to fold constant and into select arguments.
5773   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5774     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5775       return R;
5776   if (isa<PHINode>(Op0))
5777     if (Instruction *NV = FoldOpIntoPhi(I))
5778       return NV;
5779   
5780   if (Op0->hasOneUse()) {
5781     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5782       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5783       Value *V1, *V2;
5784       ConstantInt *CC;
5785       switch (Op0BO->getOpcode()) {
5786         default: break;
5787         case Instruction::Add:
5788         case Instruction::And:
5789         case Instruction::Or:
5790         case Instruction::Xor: {
5791           // These operators commute.
5792           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5793           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5794               match(Op0BO->getOperand(1),
5795                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5796             Instruction *YS = BinaryOperator::createShl(
5797                                             Op0BO->getOperand(0), Op1,
5798                                             Op0BO->getName());
5799             InsertNewInstBefore(YS, I); // (Y << C)
5800             Instruction *X = 
5801               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5802                                      Op0BO->getOperand(1)->getName());
5803             InsertNewInstBefore(X, I);  // (X + (Y << C))
5804             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
5805             return BinaryOperator::createAnd(X, ConstantInt::get(
5806                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
5807           }
5808           
5809           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5810           Value *Op0BOOp1 = Op0BO->getOperand(1);
5811           if (isLeftShift && Op0BOOp1->hasOneUse() &&
5812               match(Op0BOOp1, 
5813                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
5814               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5815               V2 == Op1) {
5816             Instruction *YS = BinaryOperator::createShl(
5817                                                      Op0BO->getOperand(0), Op1,
5818                                                      Op0BO->getName());
5819             InsertNewInstBefore(YS, I); // (Y << C)
5820             Instruction *XM =
5821               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5822                                         V1->getName()+".mask");
5823             InsertNewInstBefore(XM, I); // X & (CC << C)
5824             
5825             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5826           }
5827         }
5828           
5829         // FALL THROUGH.
5830         case Instruction::Sub: {
5831           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5832           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5833               match(Op0BO->getOperand(0),
5834                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5835             Instruction *YS = BinaryOperator::createShl(
5836                                                      Op0BO->getOperand(1), Op1,
5837                                                      Op0BO->getName());
5838             InsertNewInstBefore(YS, I); // (Y << C)
5839             Instruction *X =
5840               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5841                                      Op0BO->getOperand(0)->getName());
5842             InsertNewInstBefore(X, I);  // (X + (Y << C))
5843             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
5844             return BinaryOperator::createAnd(X, ConstantInt::get(
5845                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
5846           }
5847           
5848           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5849           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5850               match(Op0BO->getOperand(0),
5851                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5852                           m_ConstantInt(CC))) && V2 == Op1 &&
5853               cast<BinaryOperator>(Op0BO->getOperand(0))
5854                   ->getOperand(0)->hasOneUse()) {
5855             Instruction *YS = BinaryOperator::createShl(
5856                                                      Op0BO->getOperand(1), Op1,
5857                                                      Op0BO->getName());
5858             InsertNewInstBefore(YS, I); // (Y << C)
5859             Instruction *XM =
5860               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5861                                         V1->getName()+".mask");
5862             InsertNewInstBefore(XM, I); // X & (CC << C)
5863             
5864             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5865           }
5866           
5867           break;
5868         }
5869       }
5870       
5871       
5872       // If the operand is an bitwise operator with a constant RHS, and the
5873       // shift is the only use, we can pull it out of the shift.
5874       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5875         bool isValid = true;     // Valid only for And, Or, Xor
5876         bool highBitSet = false; // Transform if high bit of constant set?
5877         
5878         switch (Op0BO->getOpcode()) {
5879           default: isValid = false; break;   // Do not perform transform!
5880           case Instruction::Add:
5881             isValid = isLeftShift;
5882             break;
5883           case Instruction::Or:
5884           case Instruction::Xor:
5885             highBitSet = false;
5886             break;
5887           case Instruction::And:
5888             highBitSet = true;
5889             break;
5890         }
5891         
5892         // If this is a signed shift right, and the high bit is modified
5893         // by the logical operation, do not perform the transformation.
5894         // The highBitSet boolean indicates the value of the high bit of
5895         // the constant which would cause it to be modified for this
5896         // operation.
5897         //
5898         if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
5899           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
5900         }
5901         
5902         if (isValid) {
5903           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5904           
5905           Instruction *NewShift =
5906             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
5907           InsertNewInstBefore(NewShift, I);
5908           NewShift->takeName(Op0BO);
5909           
5910           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5911                                         NewRHS);
5912         }
5913       }
5914     }
5915   }
5916   
5917   // Find out if this is a shift of a shift by a constant.
5918   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5919   if (ShiftOp && !ShiftOp->isShift())
5920     ShiftOp = 0;
5921   
5922   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5923     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5924     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
5925     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
5926     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5927     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
5928     Value *X = ShiftOp->getOperand(0);
5929     
5930     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5931     if (AmtSum > TypeBits)
5932       AmtSum = TypeBits;
5933     
5934     const IntegerType *Ty = cast<IntegerType>(I.getType());
5935     
5936     // Check for (X << c1) << c2  and  (X >> c1) >> c2
5937     if (I.getOpcode() == ShiftOp->getOpcode()) {
5938       return BinaryOperator::create(I.getOpcode(), X,
5939                                     ConstantInt::get(Ty, AmtSum));
5940     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5941                I.getOpcode() == Instruction::AShr) {
5942       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
5943       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5944     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5945                I.getOpcode() == Instruction::LShr) {
5946       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5947       Instruction *Shift =
5948         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5949       InsertNewInstBefore(Shift, I);
5950
5951       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
5952       return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
5953     }
5954     
5955     // Okay, if we get here, one shift must be left, and the other shift must be
5956     // right.  See if the amounts are equal.
5957     if (ShiftAmt1 == ShiftAmt2) {
5958       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5959       if (I.getOpcode() == Instruction::Shl) {
5960         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
5961         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
5962       }
5963       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5964       if (I.getOpcode() == Instruction::LShr) {
5965         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
5966         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
5967       }
5968       // We can simplify ((X << C) >>s C) into a trunc + sext.
5969       // NOTE: we could do this for any C, but that would make 'unusual' integer
5970       // types.  For now, just stick to ones well-supported by the code
5971       // generators.
5972       const Type *SExtType = 0;
5973       switch (Ty->getBitWidth() - ShiftAmt1) {
5974       case 1  :
5975       case 8  :
5976       case 16 :
5977       case 32 :
5978       case 64 :
5979       case 128:
5980         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
5981         break;
5982       default: break;
5983       }
5984       if (SExtType) {
5985         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5986         InsertNewInstBefore(NewTrunc, I);
5987         return new SExtInst(NewTrunc, Ty);
5988       }
5989       // Otherwise, we can't handle it yet.
5990     } else if (ShiftAmt1 < ShiftAmt2) {
5991       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
5992       
5993       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
5994       if (I.getOpcode() == Instruction::Shl) {
5995         assert(ShiftOp->getOpcode() == Instruction::LShr ||
5996                ShiftOp->getOpcode() == Instruction::AShr);
5997         Instruction *Shift =
5998           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5999         InsertNewInstBefore(Shift, I);
6000         
6001         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6002         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6003       }
6004       
6005       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6006       if (I.getOpcode() == Instruction::LShr) {
6007         assert(ShiftOp->getOpcode() == Instruction::Shl);
6008         Instruction *Shift =
6009           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6010         InsertNewInstBefore(Shift, I);
6011         
6012         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6013         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6014       }
6015       
6016       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6017     } else {
6018       assert(ShiftAmt2 < ShiftAmt1);
6019       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6020
6021       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6022       if (I.getOpcode() == Instruction::Shl) {
6023         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6024                ShiftOp->getOpcode() == Instruction::AShr);
6025         Instruction *Shift =
6026           BinaryOperator::create(ShiftOp->getOpcode(), X,
6027                                  ConstantInt::get(Ty, ShiftDiff));
6028         InsertNewInstBefore(Shift, I);
6029         
6030         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6031         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6032       }
6033       
6034       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6035       if (I.getOpcode() == Instruction::LShr) {
6036         assert(ShiftOp->getOpcode() == Instruction::Shl);
6037         Instruction *Shift =
6038           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6039         InsertNewInstBefore(Shift, I);
6040         
6041         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6042         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6043       }
6044       
6045       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6046     }
6047   }
6048   return 0;
6049 }
6050
6051
6052 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6053 /// expression.  If so, decompose it, returning some value X, such that Val is
6054 /// X*Scale+Offset.
6055 ///
6056 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6057                                         int &Offset) {
6058   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6059   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6060     Offset = CI->getZExtValue();
6061     Scale  = 1;
6062     return ConstantInt::get(Type::Int32Ty, 0);
6063   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6064     if (I->getNumOperands() == 2) {
6065       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6066         if (I->getOpcode() == Instruction::Shl) {
6067           // This is a value scaled by '1 << the shift amt'.
6068           Scale = 1U << CUI->getZExtValue();
6069           Offset = 0;
6070           return I->getOperand(0);
6071         } else if (I->getOpcode() == Instruction::Mul) {
6072           // This value is scaled by 'CUI'.
6073           Scale = CUI->getZExtValue();
6074           Offset = 0;
6075           return I->getOperand(0);
6076         } else if (I->getOpcode() == Instruction::Add) {
6077           // We have X+C.  Check to see if we really have (X*C2)+C1, 
6078           // where C1 is divisible by C2.
6079           unsigned SubScale;
6080           Value *SubVal = 
6081             DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6082           Offset += CUI->getZExtValue();
6083           if (SubScale > 1 && (Offset % SubScale == 0)) {
6084             Scale = SubScale;
6085             return SubVal;
6086           }
6087         }
6088       }
6089     }
6090   }
6091
6092   // Otherwise, we can't look past this.
6093   Scale = 1;
6094   Offset = 0;
6095   return Val;
6096 }
6097
6098
6099 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6100 /// try to eliminate the cast by moving the type information into the alloc.
6101 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6102                                                    AllocationInst &AI) {
6103   const PointerType *PTy = cast<PointerType>(CI.getType());
6104   
6105   // Remove any uses of AI that are dead.
6106   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6107   
6108   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6109     Instruction *User = cast<Instruction>(*UI++);
6110     if (isInstructionTriviallyDead(User)) {
6111       while (UI != E && *UI == User)
6112         ++UI; // If this instruction uses AI more than once, don't break UI.
6113       
6114       ++NumDeadInst;
6115       DOUT << "IC: DCE: " << *User;
6116       EraseInstFromFunction(*User);
6117     }
6118   }
6119   
6120   // Get the type really allocated and the type casted to.
6121   const Type *AllocElTy = AI.getAllocatedType();
6122   const Type *CastElTy = PTy->getElementType();
6123   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6124
6125   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6126   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6127   if (CastElTyAlign < AllocElTyAlign) return 0;
6128
6129   // If the allocation has multiple uses, only promote it if we are strictly
6130   // increasing the alignment of the resultant allocation.  If we keep it the
6131   // same, we open the door to infinite loops of various kinds.
6132   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6133
6134   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6135   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
6136   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6137
6138   // See if we can satisfy the modulus by pulling a scale out of the array
6139   // size argument.
6140   unsigned ArraySizeScale;
6141   int ArrayOffset;
6142   Value *NumElements = // See if the array size is a decomposable linear expr.
6143     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6144  
6145   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6146   // do the xform.
6147   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6148       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6149
6150   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6151   Value *Amt = 0;
6152   if (Scale == 1) {
6153     Amt = NumElements;
6154   } else {
6155     // If the allocation size is constant, form a constant mul expression
6156     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6157     if (isa<ConstantInt>(NumElements))
6158       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6159     // otherwise multiply the amount and the number of elements
6160     else if (Scale != 1) {
6161       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6162       Amt = InsertNewInstBefore(Tmp, AI);
6163     }
6164   }
6165   
6166   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6167     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6168     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6169     Amt = InsertNewInstBefore(Tmp, AI);
6170   }
6171   
6172   AllocationInst *New;
6173   if (isa<MallocInst>(AI))
6174     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6175   else
6176     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6177   InsertNewInstBefore(New, AI);
6178   New->takeName(&AI);
6179   
6180   // If the allocation has multiple uses, insert a cast and change all things
6181   // that used it to use the new cast.  This will also hack on CI, but it will
6182   // die soon.
6183   if (!AI.hasOneUse()) {
6184     AddUsesToWorkList(AI);
6185     // New is the allocation instruction, pointer typed. AI is the original
6186     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6187     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6188     InsertNewInstBefore(NewCast, AI);
6189     AI.replaceAllUsesWith(NewCast);
6190   }
6191   return ReplaceInstUsesWith(CI, New);
6192 }
6193
6194 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6195 /// and return it as type Ty without inserting any new casts and without
6196 /// changing the computed value.  This is used by code that tries to decide
6197 /// whether promoting or shrinking integer operations to wider or smaller types
6198 /// will allow us to eliminate a truncate or extend.
6199 ///
6200 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6201 /// extension operation if Ty is larger.
6202 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6203                                        int &NumCastsRemoved) {
6204   // We can always evaluate constants in another type.
6205   if (isa<ConstantInt>(V))
6206     return true;
6207   
6208   Instruction *I = dyn_cast<Instruction>(V);
6209   if (!I) return false;
6210   
6211   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6212   
6213   switch (I->getOpcode()) {
6214   case Instruction::Add:
6215   case Instruction::Sub:
6216   case Instruction::And:
6217   case Instruction::Or:
6218   case Instruction::Xor:
6219     if (!I->hasOneUse()) return false;
6220     // These operators can all arbitrarily be extended or truncated.
6221     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6222            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
6223
6224   case Instruction::Shl:
6225     if (!I->hasOneUse()) return false;
6226     // If we are truncating the result of this SHL, and if it's a shift of a
6227     // constant amount, we can always perform a SHL in a smaller type.
6228     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6229       uint32_t BitWidth = Ty->getBitWidth();
6230       if (BitWidth < OrigTy->getBitWidth() && 
6231           CI->getLimitedValue(BitWidth) < BitWidth)
6232         return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6233     }
6234     break;
6235   case Instruction::LShr:
6236     if (!I->hasOneUse()) return false;
6237     // If this is a truncate of a logical shr, we can truncate it to a smaller
6238     // lshr iff we know that the bits we would otherwise be shifting in are
6239     // already zeros.
6240     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6241       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6242       uint32_t BitWidth = Ty->getBitWidth();
6243       if (BitWidth < OrigBitWidth &&
6244           MaskedValueIsZero(I->getOperand(0),
6245             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6246           CI->getLimitedValue(BitWidth) < BitWidth) {
6247         return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6248       }
6249     }
6250     break;
6251   case Instruction::Trunc:
6252   case Instruction::ZExt:
6253   case Instruction::SExt:
6254     // If this is a cast from the destination type, we can trivially eliminate
6255     // it, and this will remove a cast overall.
6256     if (I->getOperand(0)->getType() == Ty) {
6257       // If the first operand is itself a cast, and is eliminable, do not count
6258       // this as an eliminable cast.  We would prefer to eliminate those two
6259       // casts first.
6260       if (isa<CastInst>(I->getOperand(0)))
6261         return true;
6262       
6263       ++NumCastsRemoved;
6264       return true;
6265     }
6266     break;
6267   default:
6268     // TODO: Can handle more cases here.
6269     break;
6270   }
6271   
6272   return false;
6273 }
6274
6275 /// EvaluateInDifferentType - Given an expression that 
6276 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6277 /// evaluate the expression.
6278 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6279                                              bool isSigned) {
6280   if (Constant *C = dyn_cast<Constant>(V))
6281     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6282
6283   // Otherwise, it must be an instruction.
6284   Instruction *I = cast<Instruction>(V);
6285   Instruction *Res = 0;
6286   switch (I->getOpcode()) {
6287   case Instruction::Add:
6288   case Instruction::Sub:
6289   case Instruction::And:
6290   case Instruction::Or:
6291   case Instruction::Xor:
6292   case Instruction::AShr:
6293   case Instruction::LShr:
6294   case Instruction::Shl: {
6295     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6296     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6297     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6298                                  LHS, RHS, I->getName());
6299     break;
6300   }    
6301   case Instruction::Trunc:
6302   case Instruction::ZExt:
6303   case Instruction::SExt:
6304   case Instruction::BitCast:
6305     // If the source type of the cast is the type we're trying for then we can
6306     // just return the source. There's no need to insert it because its not new.
6307     if (I->getOperand(0)->getType() == Ty)
6308       return I->getOperand(0);
6309     
6310     // Some other kind of cast, which shouldn't happen, so just ..
6311     // FALL THROUGH
6312   default: 
6313     // TODO: Can handle more cases here.
6314     assert(0 && "Unreachable!");
6315     break;
6316   }
6317   
6318   return InsertNewInstBefore(Res, *I);
6319 }
6320
6321 /// @brief Implement the transforms common to all CastInst visitors.
6322 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6323   Value *Src = CI.getOperand(0);
6324
6325   // Casting undef to anything results in undef so might as just replace it and
6326   // get rid of the cast.
6327   if (isa<UndefValue>(Src))   // cast undef -> undef
6328     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6329
6330   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6331   // eliminate it now.
6332   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6333     if (Instruction::CastOps opc = 
6334         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6335       // The first cast (CSrc) is eliminable so we need to fix up or replace
6336       // the second cast (CI). CSrc will then have a good chance of being dead.
6337       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6338     }
6339   }
6340
6341   // If we are casting a select then fold the cast into the select
6342   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6343     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6344       return NV;
6345
6346   // If we are casting a PHI then fold the cast into the PHI
6347   if (isa<PHINode>(Src))
6348     if (Instruction *NV = FoldOpIntoPhi(CI))
6349       return NV;
6350   
6351   return 0;
6352 }
6353
6354 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6355 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6356   Value *Src = CI.getOperand(0);
6357   
6358   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6359     // If casting the result of a getelementptr instruction with no offset, turn
6360     // this into a cast of the original pointer!
6361     if (GEP->hasAllZeroIndices()) {
6362       // Changing the cast operand is usually not a good idea but it is safe
6363       // here because the pointer operand is being replaced with another 
6364       // pointer operand so the opcode doesn't need to change.
6365       AddToWorkList(GEP);
6366       CI.setOperand(0, GEP->getOperand(0));
6367       return &CI;
6368     }
6369     
6370     // If the GEP has a single use, and the base pointer is a bitcast, and the
6371     // GEP computes a constant offset, see if we can convert these three
6372     // instructions into fewer.  This typically happens with unions and other
6373     // non-type-safe code.
6374     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6375       if (GEP->hasAllConstantIndices()) {
6376         // We are guaranteed to get a constant from EmitGEPOffset.
6377         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6378         int64_t Offset = OffsetV->getSExtValue();
6379         
6380         // Get the base pointer input of the bitcast, and the type it points to.
6381         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6382         const Type *GEPIdxTy =
6383           cast<PointerType>(OrigBase->getType())->getElementType();
6384         if (GEPIdxTy->isSized()) {
6385           SmallVector<Value*, 8> NewIndices;
6386           
6387           // Start with the index over the outer type.
6388           const Type *IntPtrTy = TD->getIntPtrType();
6389           int64_t TySize = TD->getTypeSize(GEPIdxTy);
6390           int64_t FirstIdx = Offset/TySize;
6391           Offset %= TySize;
6392           
6393           // Handle silly modulus not returning values values [0..TySize).
6394           if (Offset < 0) {
6395             assert(FirstIdx == 0);
6396             FirstIdx = -1;
6397             Offset += TySize;
6398             assert(Offset >= 0);
6399           }
6400           
6401           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6402           assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
6403
6404           // Index into the types.  If we fail, set OrigBase to null.
6405           while (Offset) {
6406             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6407               const StructLayout *SL = TD->getStructLayout(STy);
6408               unsigned Elt = SL->getElementContainingOffset(Offset);
6409               NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6410               
6411               Offset -= SL->getElementOffset(Elt);
6412               GEPIdxTy = STy->getElementType(Elt);
6413             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6414               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
6415               uint64_t EltSize = TD->getTypeSize(STy->getElementType());
6416               NewIndices.push_back(ConstantInt::get(IntPtrTy, Offset/EltSize));
6417               Offset %= EltSize;
6418               GEPIdxTy = STy->getElementType();
6419             } else {
6420               // Otherwise, we can't index into this, bail out.
6421               Offset = 0;
6422               OrigBase = 0;
6423             }
6424           }
6425           if (OrigBase) {
6426             // If we were able to index down into an element, create the GEP
6427             // and bitcast the result.  This eliminates one bitcast, potentially
6428             // two.
6429             Instruction *NGEP = new GetElementPtrInst(OrigBase, &NewIndices[0],
6430                                                       NewIndices.size(), "");
6431             InsertNewInstBefore(NGEP, CI);
6432             NGEP->takeName(GEP);
6433             
6434             cerr << "\nZAP: " << *GEP->getOperand(0);
6435             cerr << "ZAP: " << *GEP;
6436             cerr << "ZAP: " << CI << "\n";
6437
6438             cerr << "NEW: " << *NGEP << "\n";
6439
6440             if (isa<BitCastInst>(CI))
6441               return new BitCastInst(NGEP, CI.getType());
6442             assert(isa<PtrToIntInst>(CI));
6443             return new PtrToIntInst(NGEP, CI.getType());
6444           }
6445         }
6446       }      
6447     }
6448   }
6449     
6450   return commonCastTransforms(CI);
6451 }
6452
6453
6454
6455 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6456 /// integer types. This function implements the common transforms for all those
6457 /// cases.
6458 /// @brief Implement the transforms common to CastInst with integer operands
6459 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6460   if (Instruction *Result = commonCastTransforms(CI))
6461     return Result;
6462
6463   Value *Src = CI.getOperand(0);
6464   const Type *SrcTy = Src->getType();
6465   const Type *DestTy = CI.getType();
6466   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6467   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6468
6469   // See if we can simplify any instructions used by the LHS whose sole 
6470   // purpose is to compute bits we don't care about.
6471   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6472   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6473                            KnownZero, KnownOne))
6474     return &CI;
6475
6476   // If the source isn't an instruction or has more than one use then we
6477   // can't do anything more. 
6478   Instruction *SrcI = dyn_cast<Instruction>(Src);
6479   if (!SrcI || !Src->hasOneUse())
6480     return 0;
6481
6482   // Attempt to propagate the cast into the instruction for int->int casts.
6483   int NumCastsRemoved = 0;
6484   if (!isa<BitCastInst>(CI) &&
6485       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6486                                  NumCastsRemoved)) {
6487     // If this cast is a truncate, evaluting in a different type always
6488     // eliminates the cast, so it is always a win.  If this is a noop-cast
6489     // this just removes a noop cast which isn't pointful, but simplifies
6490     // the code.  If this is a zero-extension, we need to do an AND to
6491     // maintain the clear top-part of the computation, so we require that
6492     // the input have eliminated at least one cast.  If this is a sign
6493     // extension, we insert two new casts (to do the extension) so we
6494     // require that two casts have been eliminated.
6495     bool DoXForm;
6496     switch (CI.getOpcode()) {
6497     default:
6498       // All the others use floating point so we shouldn't actually 
6499       // get here because of the check above.
6500       assert(0 && "Unknown cast type");
6501     case Instruction::Trunc:
6502       DoXForm = true;
6503       break;
6504     case Instruction::ZExt:
6505       DoXForm = NumCastsRemoved >= 1;
6506       break;
6507     case Instruction::SExt:
6508       DoXForm = NumCastsRemoved >= 2;
6509       break;
6510     case Instruction::BitCast:
6511       DoXForm = false;
6512       break;
6513     }
6514     
6515     if (DoXForm) {
6516       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6517                                            CI.getOpcode() == Instruction::SExt);
6518       assert(Res->getType() == DestTy);
6519       switch (CI.getOpcode()) {
6520       default: assert(0 && "Unknown cast type!");
6521       case Instruction::Trunc:
6522       case Instruction::BitCast:
6523         // Just replace this cast with the result.
6524         return ReplaceInstUsesWith(CI, Res);
6525       case Instruction::ZExt: {
6526         // We need to emit an AND to clear the high bits.
6527         assert(SrcBitSize < DestBitSize && "Not a zext?");
6528         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6529                                                             SrcBitSize));
6530         return BinaryOperator::createAnd(Res, C);
6531       }
6532       case Instruction::SExt:
6533         // We need to emit a cast to truncate, then a cast to sext.
6534         return CastInst::create(Instruction::SExt,
6535             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6536                              CI), DestTy);
6537       }
6538     }
6539   }
6540   
6541   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6542   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6543
6544   switch (SrcI->getOpcode()) {
6545   case Instruction::Add:
6546   case Instruction::Mul:
6547   case Instruction::And:
6548   case Instruction::Or:
6549   case Instruction::Xor:
6550     // If we are discarding information, rewrite.
6551     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6552       // Don't insert two casts if they cannot be eliminated.  We allow 
6553       // two casts to be inserted if the sizes are the same.  This could 
6554       // only be converting signedness, which is a noop.
6555       if (DestBitSize == SrcBitSize || 
6556           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6557           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6558         Instruction::CastOps opcode = CI.getOpcode();
6559         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6560         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6561         return BinaryOperator::create(
6562             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6563       }
6564     }
6565
6566     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6567     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6568         SrcI->getOpcode() == Instruction::Xor &&
6569         Op1 == ConstantInt::getTrue() &&
6570         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6571       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6572       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6573     }
6574     break;
6575   case Instruction::SDiv:
6576   case Instruction::UDiv:
6577   case Instruction::SRem:
6578   case Instruction::URem:
6579     // If we are just changing the sign, rewrite.
6580     if (DestBitSize == SrcBitSize) {
6581       // Don't insert two casts if they cannot be eliminated.  We allow 
6582       // two casts to be inserted if the sizes are the same.  This could 
6583       // only be converting signedness, which is a noop.
6584       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6585           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6586         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6587                                               Op0, DestTy, SrcI);
6588         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6589                                               Op1, DestTy, SrcI);
6590         return BinaryOperator::create(
6591           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6592       }
6593     }
6594     break;
6595
6596   case Instruction::Shl:
6597     // Allow changing the sign of the source operand.  Do not allow 
6598     // changing the size of the shift, UNLESS the shift amount is a 
6599     // constant.  We must not change variable sized shifts to a smaller 
6600     // size, because it is undefined to shift more bits out than exist 
6601     // in the value.
6602     if (DestBitSize == SrcBitSize ||
6603         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6604       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6605           Instruction::BitCast : Instruction::Trunc);
6606       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6607       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6608       return BinaryOperator::createShl(Op0c, Op1c);
6609     }
6610     break;
6611   case Instruction::AShr:
6612     // If this is a signed shr, and if all bits shifted in are about to be
6613     // truncated off, turn it into an unsigned shr to allow greater
6614     // simplifications.
6615     if (DestBitSize < SrcBitSize &&
6616         isa<ConstantInt>(Op1)) {
6617       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
6618       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6619         // Insert the new logical shift right.
6620         return BinaryOperator::createLShr(Op0, Op1);
6621       }
6622     }
6623     break;
6624   }
6625   return 0;
6626 }
6627
6628 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
6629   if (Instruction *Result = commonIntCastTransforms(CI))
6630     return Result;
6631   
6632   Value *Src = CI.getOperand(0);
6633   const Type *Ty = CI.getType();
6634   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6635   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
6636   
6637   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6638     switch (SrcI->getOpcode()) {
6639     default: break;
6640     case Instruction::LShr:
6641       // We can shrink lshr to something smaller if we know the bits shifted in
6642       // are already zeros.
6643       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6644         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
6645         
6646         // Get a mask for the bits shifting in.
6647         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
6648         Value* SrcIOp0 = SrcI->getOperand(0);
6649         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6650           if (ShAmt >= DestBitWidth)        // All zeros.
6651             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6652
6653           // Okay, we can shrink this.  Truncate the input, then return a new
6654           // shift.
6655           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6656           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6657                                        Ty, CI);
6658           return BinaryOperator::createLShr(V1, V2);
6659         }
6660       } else {     // This is a variable shr.
6661         
6662         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6663         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6664         // loop-invariant and CSE'd.
6665         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6666           Value *One = ConstantInt::get(SrcI->getType(), 1);
6667
6668           Value *V = InsertNewInstBefore(
6669               BinaryOperator::createShl(One, SrcI->getOperand(1),
6670                                      "tmp"), CI);
6671           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6672                                                             SrcI->getOperand(0),
6673                                                             "tmp"), CI);
6674           Value *Zero = Constant::getNullValue(V->getType());
6675           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6676         }
6677       }
6678       break;
6679     }
6680   }
6681   
6682   return 0;
6683 }
6684
6685 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
6686   // If one of the common conversion will work ..
6687   if (Instruction *Result = commonIntCastTransforms(CI))
6688     return Result;
6689
6690   Value *Src = CI.getOperand(0);
6691
6692   // If this is a cast of a cast
6693   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6694     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6695     // types and if the sizes are just right we can convert this into a logical
6696     // 'and' which will be much cheaper than the pair of casts.
6697     if (isa<TruncInst>(CSrc)) {
6698       // Get the sizes of the types involved
6699       Value *A = CSrc->getOperand(0);
6700       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6701       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6702       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
6703       // If we're actually extending zero bits and the trunc is a no-op
6704       if (MidSize < DstSize && SrcSize == DstSize) {
6705         // Replace both of the casts with an And of the type mask.
6706         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
6707         Constant *AndConst = ConstantInt::get(AndValue);
6708         Instruction *And = 
6709           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6710         // Unfortunately, if the type changed, we need to cast it back.
6711         if (And->getType() != CI.getType()) {
6712           And->setName(CSrc->getName()+".mask");
6713           InsertNewInstBefore(And, CI);
6714           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6715         }
6716         return And;
6717       }
6718     }
6719   }
6720
6721   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6722     // If we are just checking for a icmp eq of a single bit and zext'ing it
6723     // to an integer, then shift the bit to the appropriate place and then
6724     // cast to integer to avoid the comparison.
6725     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
6726       const APInt &Op1CV = Op1C->getValue();
6727       
6728       // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
6729       // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
6730       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6731           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6732         Value *In = ICI->getOperand(0);
6733         Value *Sh = ConstantInt::get(In->getType(),
6734                                     In->getType()->getPrimitiveSizeInBits()-1);
6735         In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
6736                                                         In->getName()+".lobit"),
6737                                  CI);
6738         if (In->getType() != CI.getType())
6739           In = CastInst::createIntegerCast(In, CI.getType(),
6740                                            false/*ZExt*/, "tmp", &CI);
6741
6742         if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
6743           Constant *One = ConstantInt::get(In->getType(), 1);
6744           In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
6745                                                           In->getName()+".not"),
6746                                    CI);
6747         }
6748
6749         return ReplaceInstUsesWith(CI, In);
6750       }
6751       
6752       
6753       
6754       // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
6755       // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
6756       // zext (X == 1) to i32 --> X        iff X has only the low bit set.
6757       // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
6758       // zext (X != 0) to i32 --> X        iff X has only the low bit set.
6759       // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
6760       // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
6761       // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
6762       if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
6763           // This only works for EQ and NE
6764           ICI->isEquality()) {
6765         // If Op1C some other power of two, convert:
6766         uint32_t BitWidth = Op1C->getType()->getBitWidth();
6767         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6768         APInt TypeMask(APInt::getAllOnesValue(BitWidth));
6769         ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
6770         
6771         APInt KnownZeroMask(~KnownZero);
6772         if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
6773           bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
6774           if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
6775             // (X&4) == 2 --> false
6776             // (X&4) != 2 --> true
6777             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6778             Res = ConstantExpr::getZExt(Res, CI.getType());
6779             return ReplaceInstUsesWith(CI, Res);
6780           }
6781           
6782           uint32_t ShiftAmt = KnownZeroMask.logBase2();
6783           Value *In = ICI->getOperand(0);
6784           if (ShiftAmt) {
6785             // Perform a logical shr by shiftamt.
6786             // Insert the shift to put the result in the low bit.
6787             In = InsertNewInstBefore(
6788                    BinaryOperator::createLShr(In,
6789                                      ConstantInt::get(In->getType(), ShiftAmt),
6790                                               In->getName()+".lobit"), CI);
6791           }
6792           
6793           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6794             Constant *One = ConstantInt::get(In->getType(), 1);
6795             In = BinaryOperator::createXor(In, One, "tmp");
6796             InsertNewInstBefore(cast<Instruction>(In), CI);
6797           }
6798           
6799           if (CI.getType() == In->getType())
6800             return ReplaceInstUsesWith(CI, In);
6801           else
6802             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6803         }
6804       }
6805     }
6806   }    
6807   return 0;
6808 }
6809
6810 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
6811   if (Instruction *I = commonIntCastTransforms(CI))
6812     return I;
6813   
6814   Value *Src = CI.getOperand(0);
6815   
6816   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
6817   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
6818   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6819     // If we are just checking for a icmp eq of a single bit and zext'ing it
6820     // to an integer, then shift the bit to the appropriate place and then
6821     // cast to integer to avoid the comparison.
6822     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
6823       const APInt &Op1CV = Op1C->getValue();
6824       
6825       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
6826       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
6827       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6828           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6829         Value *In = ICI->getOperand(0);
6830         Value *Sh = ConstantInt::get(In->getType(),
6831                                      In->getType()->getPrimitiveSizeInBits()-1);
6832         In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
6833                                                         In->getName()+".lobit"),
6834                                  CI);
6835         if (In->getType() != CI.getType())
6836           In = CastInst::createIntegerCast(In, CI.getType(),
6837                                            true/*SExt*/, "tmp", &CI);
6838         
6839         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
6840           In = InsertNewInstBefore(BinaryOperator::createNot(In,
6841                                      In->getName()+".not"), CI);
6842         
6843         return ReplaceInstUsesWith(CI, In);
6844       }
6845     }
6846   }
6847       
6848   return 0;
6849 }
6850
6851 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6852   return commonCastTransforms(CI);
6853 }
6854
6855 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6856   return commonCastTransforms(CI);
6857 }
6858
6859 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6860   return commonCastTransforms(CI);
6861 }
6862
6863 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6864   return commonCastTransforms(CI);
6865 }
6866
6867 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6868   return commonCastTransforms(CI);
6869 }
6870
6871 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6872   return commonCastTransforms(CI);
6873 }
6874
6875 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6876   return commonPointerCastTransforms(CI);
6877 }
6878
6879 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6880   return commonCastTransforms(CI);
6881 }
6882
6883 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
6884   // If the operands are integer typed then apply the integer transforms,
6885   // otherwise just apply the common ones.
6886   Value *Src = CI.getOperand(0);
6887   const Type *SrcTy = Src->getType();
6888   const Type *DestTy = CI.getType();
6889
6890   if (SrcTy->isInteger() && DestTy->isInteger()) {
6891     if (Instruction *Result = commonIntCastTransforms(CI))
6892       return Result;
6893   } else if (isa<PointerType>(SrcTy)) {
6894     if (Instruction *I = commonPointerCastTransforms(CI))
6895       return I;
6896   } else {
6897     if (Instruction *Result = commonCastTransforms(CI))
6898       return Result;
6899   }
6900
6901
6902   // Get rid of casts from one type to the same type. These are useless and can
6903   // be replaced by the operand.
6904   if (DestTy == Src->getType())
6905     return ReplaceInstUsesWith(CI, Src);
6906
6907   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6908     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
6909     const Type *DstElTy = DstPTy->getElementType();
6910     const Type *SrcElTy = SrcPTy->getElementType();
6911     
6912     // If we are casting a malloc or alloca to a pointer to a type of the same
6913     // size, rewrite the allocation instruction to allocate the "right" type.
6914     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
6915       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6916         return V;
6917     
6918     // If the source and destination are pointers, and this cast is equivalent to
6919     // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
6920     // This can enhance SROA and other transforms that want type-safe pointers.
6921     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6922     unsigned NumZeros = 0;
6923     while (SrcElTy != DstElTy && 
6924            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6925            SrcElTy->getNumContainedTypes() /* not "{}" */) {
6926       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6927       ++NumZeros;
6928     }
6929
6930     // If we found a path from the src to dest, create the getelementptr now.
6931     if (SrcElTy == DstElTy) {
6932       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6933       return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
6934     }
6935   }
6936
6937   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6938     if (SVI->hasOneUse()) {
6939       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
6940       // a bitconvert to a vector with the same # elts.
6941       if (isa<VectorType>(DestTy) && 
6942           cast<VectorType>(DestTy)->getNumElements() == 
6943                 SVI->getType()->getNumElements()) {
6944         CastInst *Tmp;
6945         // If either of the operands is a cast from CI.getType(), then
6946         // evaluating the shuffle in the casted destination's type will allow
6947         // us to eliminate at least one cast.
6948         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
6949              Tmp->getOperand(0)->getType() == DestTy) ||
6950             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
6951              Tmp->getOperand(0)->getType() == DestTy)) {
6952           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6953                                                SVI->getOperand(0), DestTy, &CI);
6954           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6955                                                SVI->getOperand(1), DestTy, &CI);
6956           // Return a new shuffle vector.  Use the same element ID's, as we
6957           // know the vector types match #elts.
6958           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6959         }
6960       }
6961     }
6962   }
6963   return 0;
6964 }
6965
6966 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6967 ///   %C = or %A, %B
6968 ///   %D = select %cond, %C, %A
6969 /// into:
6970 ///   %C = select %cond, %B, 0
6971 ///   %D = or %A, %C
6972 ///
6973 /// Assuming that the specified instruction is an operand to the select, return
6974 /// a bitmask indicating which operands of this instruction are foldable if they
6975 /// equal the other incoming value of the select.
6976 ///
6977 static unsigned GetSelectFoldableOperands(Instruction *I) {
6978   switch (I->getOpcode()) {
6979   case Instruction::Add:
6980   case Instruction::Mul:
6981   case Instruction::And:
6982   case Instruction::Or:
6983   case Instruction::Xor:
6984     return 3;              // Can fold through either operand.
6985   case Instruction::Sub:   // Can only fold on the amount subtracted.
6986   case Instruction::Shl:   // Can only fold on the shift amount.
6987   case Instruction::LShr:
6988   case Instruction::AShr:
6989     return 1;
6990   default:
6991     return 0;              // Cannot fold
6992   }
6993 }
6994
6995 /// GetSelectFoldableConstant - For the same transformation as the previous
6996 /// function, return the identity constant that goes into the select.
6997 static Constant *GetSelectFoldableConstant(Instruction *I) {
6998   switch (I->getOpcode()) {
6999   default: assert(0 && "This cannot happen!"); abort();
7000   case Instruction::Add:
7001   case Instruction::Sub:
7002   case Instruction::Or:
7003   case Instruction::Xor:
7004   case Instruction::Shl:
7005   case Instruction::LShr:
7006   case Instruction::AShr:
7007     return Constant::getNullValue(I->getType());
7008   case Instruction::And:
7009     return ConstantInt::getAllOnesValue(I->getType());
7010   case Instruction::Mul:
7011     return ConstantInt::get(I->getType(), 1);
7012   }
7013 }
7014
7015 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7016 /// have the same opcode and only one use each.  Try to simplify this.
7017 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7018                                           Instruction *FI) {
7019   if (TI->getNumOperands() == 1) {
7020     // If this is a non-volatile load or a cast from the same type,
7021     // merge.
7022     if (TI->isCast()) {
7023       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7024         return 0;
7025     } else {
7026       return 0;  // unknown unary op.
7027     }
7028
7029     // Fold this by inserting a select from the input values.
7030     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7031                                        FI->getOperand(0), SI.getName()+".v");
7032     InsertNewInstBefore(NewSI, SI);
7033     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7034                             TI->getType());
7035   }
7036
7037   // Only handle binary operators here.
7038   if (!isa<BinaryOperator>(TI))
7039     return 0;
7040
7041   // Figure out if the operations have any operands in common.
7042   Value *MatchOp, *OtherOpT, *OtherOpF;
7043   bool MatchIsOpZero;
7044   if (TI->getOperand(0) == FI->getOperand(0)) {
7045     MatchOp  = TI->getOperand(0);
7046     OtherOpT = TI->getOperand(1);
7047     OtherOpF = FI->getOperand(1);
7048     MatchIsOpZero = true;
7049   } else if (TI->getOperand(1) == FI->getOperand(1)) {
7050     MatchOp  = TI->getOperand(1);
7051     OtherOpT = TI->getOperand(0);
7052     OtherOpF = FI->getOperand(0);
7053     MatchIsOpZero = false;
7054   } else if (!TI->isCommutative()) {
7055     return 0;
7056   } else if (TI->getOperand(0) == FI->getOperand(1)) {
7057     MatchOp  = TI->getOperand(0);
7058     OtherOpT = TI->getOperand(1);
7059     OtherOpF = FI->getOperand(0);
7060     MatchIsOpZero = true;
7061   } else if (TI->getOperand(1) == FI->getOperand(0)) {
7062     MatchOp  = TI->getOperand(1);
7063     OtherOpT = TI->getOperand(0);
7064     OtherOpF = FI->getOperand(1);
7065     MatchIsOpZero = true;
7066   } else {
7067     return 0;
7068   }
7069
7070   // If we reach here, they do have operations in common.
7071   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7072                                      OtherOpF, SI.getName()+".v");
7073   InsertNewInstBefore(NewSI, SI);
7074
7075   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7076     if (MatchIsOpZero)
7077       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7078     else
7079       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7080   }
7081   assert(0 && "Shouldn't get here");
7082   return 0;
7083 }
7084
7085 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7086   Value *CondVal = SI.getCondition();
7087   Value *TrueVal = SI.getTrueValue();
7088   Value *FalseVal = SI.getFalseValue();
7089
7090   // select true, X, Y  -> X
7091   // select false, X, Y -> Y
7092   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7093     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7094
7095   // select C, X, X -> X
7096   if (TrueVal == FalseVal)
7097     return ReplaceInstUsesWith(SI, TrueVal);
7098
7099   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
7100     return ReplaceInstUsesWith(SI, FalseVal);
7101   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
7102     return ReplaceInstUsesWith(SI, TrueVal);
7103   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
7104     if (isa<Constant>(TrueVal))
7105       return ReplaceInstUsesWith(SI, TrueVal);
7106     else
7107       return ReplaceInstUsesWith(SI, FalseVal);
7108   }
7109
7110   if (SI.getType() == Type::Int1Ty) {
7111     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7112       if (C->getZExtValue()) {
7113         // Change: A = select B, true, C --> A = or B, C
7114         return BinaryOperator::createOr(CondVal, FalseVal);
7115       } else {
7116         // Change: A = select B, false, C --> A = and !B, C
7117         Value *NotCond =
7118           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7119                                              "not."+CondVal->getName()), SI);
7120         return BinaryOperator::createAnd(NotCond, FalseVal);
7121       }
7122     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7123       if (C->getZExtValue() == false) {
7124         // Change: A = select B, C, false --> A = and B, C
7125         return BinaryOperator::createAnd(CondVal, TrueVal);
7126       } else {
7127         // Change: A = select B, C, true --> A = or !B, C
7128         Value *NotCond =
7129           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7130                                              "not."+CondVal->getName()), SI);
7131         return BinaryOperator::createOr(NotCond, TrueVal);
7132       }
7133     }
7134   }
7135
7136   // Selecting between two integer constants?
7137   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7138     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7139       // select C, 1, 0 -> zext C to int
7140       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7141         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7142       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7143         // select C, 0, 1 -> zext !C to int
7144         Value *NotCond =
7145           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7146                                                "not."+CondVal->getName()), SI);
7147         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7148       }
7149       
7150       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7151
7152       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7153
7154         // (x <s 0) ? -1 : 0 -> ashr x, 31
7155         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7156           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7157             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7158               // The comparison constant and the result are not neccessarily the
7159               // same width. Make an all-ones value by inserting a AShr.
7160               Value *X = IC->getOperand(0);
7161               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7162               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7163               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7164                                                         ShAmt, "ones");
7165               InsertNewInstBefore(SRA, SI);
7166               
7167               // Finally, convert to the type of the select RHS.  We figure out
7168               // if this requires a SExt, Trunc or BitCast based on the sizes.
7169               Instruction::CastOps opc = Instruction::BitCast;
7170               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7171               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
7172               if (SRASize < SISize)
7173                 opc = Instruction::SExt;
7174               else if (SRASize > SISize)
7175                 opc = Instruction::Trunc;
7176               return CastInst::create(opc, SRA, SI.getType());
7177             }
7178           }
7179
7180
7181         // If one of the constants is zero (we know they can't both be) and we
7182         // have an icmp instruction with zero, and we have an 'and' with the
7183         // non-constant value, eliminate this whole mess.  This corresponds to
7184         // cases like this: ((X & 27) ? 27 : 0)
7185         if (TrueValC->isZero() || FalseValC->isZero())
7186           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7187               cast<Constant>(IC->getOperand(1))->isNullValue())
7188             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7189               if (ICA->getOpcode() == Instruction::And &&
7190                   isa<ConstantInt>(ICA->getOperand(1)) &&
7191                   (ICA->getOperand(1) == TrueValC ||
7192                    ICA->getOperand(1) == FalseValC) &&
7193                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7194                 // Okay, now we know that everything is set up, we just don't
7195                 // know whether we have a icmp_ne or icmp_eq and whether the 
7196                 // true or false val is the zero.
7197                 bool ShouldNotVal = !TrueValC->isZero();
7198                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7199                 Value *V = ICA;
7200                 if (ShouldNotVal)
7201                   V = InsertNewInstBefore(BinaryOperator::create(
7202                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
7203                 return ReplaceInstUsesWith(SI, V);
7204               }
7205       }
7206     }
7207
7208   // See if we are selecting two values based on a comparison of the two values.
7209   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7210     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7211       // Transform (X == Y) ? X : Y  -> Y
7212       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
7213         return ReplaceInstUsesWith(SI, FalseVal);
7214       // Transform (X != Y) ? X : Y  -> X
7215       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7216         return ReplaceInstUsesWith(SI, TrueVal);
7217       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7218
7219     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7220       // Transform (X == Y) ? Y : X  -> X
7221       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
7222         return ReplaceInstUsesWith(SI, FalseVal);
7223       // Transform (X != Y) ? Y : X  -> Y
7224       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7225         return ReplaceInstUsesWith(SI, TrueVal);
7226       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7227     }
7228   }
7229
7230   // See if we are selecting two values based on a comparison of the two values.
7231   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7232     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7233       // Transform (X == Y) ? X : Y  -> Y
7234       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7235         return ReplaceInstUsesWith(SI, FalseVal);
7236       // Transform (X != Y) ? X : Y  -> X
7237       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7238         return ReplaceInstUsesWith(SI, TrueVal);
7239       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7240
7241     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7242       // Transform (X == Y) ? Y : X  -> X
7243       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7244         return ReplaceInstUsesWith(SI, FalseVal);
7245       // Transform (X != Y) ? Y : X  -> Y
7246       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7247         return ReplaceInstUsesWith(SI, TrueVal);
7248       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7249     }
7250   }
7251
7252   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7253     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7254       if (TI->hasOneUse() && FI->hasOneUse()) {
7255         Instruction *AddOp = 0, *SubOp = 0;
7256
7257         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7258         if (TI->getOpcode() == FI->getOpcode())
7259           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7260             return IV;
7261
7262         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
7263         // even legal for FP.
7264         if (TI->getOpcode() == Instruction::Sub &&
7265             FI->getOpcode() == Instruction::Add) {
7266           AddOp = FI; SubOp = TI;
7267         } else if (FI->getOpcode() == Instruction::Sub &&
7268                    TI->getOpcode() == Instruction::Add) {
7269           AddOp = TI; SubOp = FI;
7270         }
7271
7272         if (AddOp) {
7273           Value *OtherAddOp = 0;
7274           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7275             OtherAddOp = AddOp->getOperand(1);
7276           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7277             OtherAddOp = AddOp->getOperand(0);
7278           }
7279
7280           if (OtherAddOp) {
7281             // So at this point we know we have (Y -> OtherAddOp):
7282             //        select C, (add X, Y), (sub X, Z)
7283             Value *NegVal;  // Compute -Z
7284             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7285               NegVal = ConstantExpr::getNeg(C);
7286             } else {
7287               NegVal = InsertNewInstBefore(
7288                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7289             }
7290
7291             Value *NewTrueOp = OtherAddOp;
7292             Value *NewFalseOp = NegVal;
7293             if (AddOp != TI)
7294               std::swap(NewTrueOp, NewFalseOp);
7295             Instruction *NewSel =
7296               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7297
7298             NewSel = InsertNewInstBefore(NewSel, SI);
7299             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7300           }
7301         }
7302       }
7303
7304   // See if we can fold the select into one of our operands.
7305   if (SI.getType()->isInteger()) {
7306     // See the comment above GetSelectFoldableOperands for a description of the
7307     // transformation we are doing here.
7308     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7309       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7310           !isa<Constant>(FalseVal))
7311         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7312           unsigned OpToFold = 0;
7313           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7314             OpToFold = 1;
7315           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7316             OpToFold = 2;
7317           }
7318
7319           if (OpToFold) {
7320             Constant *C = GetSelectFoldableConstant(TVI);
7321             Instruction *NewSel =
7322               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7323             InsertNewInstBefore(NewSel, SI);
7324             NewSel->takeName(TVI);
7325             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7326               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7327             else {
7328               assert(0 && "Unknown instruction!!");
7329             }
7330           }
7331         }
7332
7333     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7334       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7335           !isa<Constant>(TrueVal))
7336         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7337           unsigned OpToFold = 0;
7338           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7339             OpToFold = 1;
7340           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7341             OpToFold = 2;
7342           }
7343
7344           if (OpToFold) {
7345             Constant *C = GetSelectFoldableConstant(FVI);
7346             Instruction *NewSel =
7347               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7348             InsertNewInstBefore(NewSel, SI);
7349             NewSel->takeName(FVI);
7350             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7351               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7352             else
7353               assert(0 && "Unknown instruction!!");
7354           }
7355         }
7356   }
7357
7358   if (BinaryOperator::isNot(CondVal)) {
7359     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7360     SI.setOperand(1, FalseVal);
7361     SI.setOperand(2, TrueVal);
7362     return &SI;
7363   }
7364
7365   return 0;
7366 }
7367
7368 /// GetKnownAlignment - If the specified pointer has an alignment that we can
7369 /// determine, return it, otherwise return 0.
7370 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7371   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7372     unsigned Align = GV->getAlignment();
7373     if (Align == 0 && TD) 
7374       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
7375     return Align;
7376   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7377     unsigned Align = AI->getAlignment();
7378     if (Align == 0 && TD) {
7379       if (isa<AllocaInst>(AI))
7380         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7381       else if (isa<MallocInst>(AI)) {
7382         // Malloc returns maximally aligned memory.
7383         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7384         Align =
7385           std::max(Align,
7386                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7387         Align =
7388           std::max(Align,
7389                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7390       }
7391     }
7392     return Align;
7393   } else if (isa<BitCastInst>(V) ||
7394              (isa<ConstantExpr>(V) && 
7395               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
7396     User *CI = cast<User>(V);
7397     if (isa<PointerType>(CI->getOperand(0)->getType()))
7398       return GetKnownAlignment(CI->getOperand(0), TD);
7399     return 0;
7400   } else if (User *GEPI = dyn_castGetElementPtr(V)) {
7401     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7402     if (BaseAlignment == 0) return 0;
7403     
7404     // If all indexes are zero, it is just the alignment of the base pointer.
7405     bool AllZeroOperands = true;
7406     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7407       if (!isa<Constant>(GEPI->getOperand(i)) ||
7408           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7409         AllZeroOperands = false;
7410         break;
7411       }
7412     if (AllZeroOperands)
7413       return BaseAlignment;
7414     
7415     // Otherwise, if the base alignment is >= the alignment we expect for the
7416     // base pointer type, then we know that the resultant pointer is aligned at
7417     // least as much as its type requires.
7418     if (!TD) return 0;
7419
7420     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7421     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
7422     if (TD->getABITypeAlignment(PtrTy->getElementType())
7423         <= BaseAlignment) {
7424       const Type *GEPTy = GEPI->getType();
7425       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
7426       return TD->getABITypeAlignment(GEPPtrTy->getElementType());
7427     }
7428     return 0;
7429   }
7430   return 0;
7431 }
7432
7433
7434 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
7435 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
7436 /// the heavy lifting.
7437 ///
7438 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
7439   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7440   if (!II) return visitCallSite(&CI);
7441   
7442   // Intrinsics cannot occur in an invoke, so handle them here instead of in
7443   // visitCallSite.
7444   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
7445     bool Changed = false;
7446
7447     // memmove/cpy/set of zero bytes is a noop.
7448     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7449       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7450
7451       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
7452         if (CI->getZExtValue() == 1) {
7453           // Replace the instruction with just byte operations.  We would
7454           // transform other cases to loads/stores, but we don't know if
7455           // alignment is sufficient.
7456         }
7457     }
7458
7459     // If we have a memmove and the source operation is a constant global,
7460     // then the source and dest pointers can't alias, so we can change this
7461     // into a call to memcpy.
7462     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
7463       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7464         if (GVSrc->isConstant()) {
7465           Module *M = CI.getParent()->getParent()->getParent();
7466           const char *Name;
7467           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
7468               Type::Int32Ty)
7469             Name = "llvm.memcpy.i32";
7470           else
7471             Name = "llvm.memcpy.i64";
7472           Constant *MemCpy = M->getOrInsertFunction(Name,
7473                                      CI.getCalledFunction()->getFunctionType());
7474           CI.setOperand(0, MemCpy);
7475           Changed = true;
7476         }
7477     }
7478
7479     // If we can determine a pointer alignment that is bigger than currently
7480     // set, update the alignment.
7481     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7482       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7483       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7484       unsigned Align = std::min(Alignment1, Alignment2);
7485       if (MI->getAlignment()->getZExtValue() < Align) {
7486         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7487         Changed = true;
7488       }
7489     } else if (isa<MemSetInst>(MI)) {
7490       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
7491       if (MI->getAlignment()->getZExtValue() < Alignment) {
7492         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7493         Changed = true;
7494       }
7495     }
7496           
7497     if (Changed) return II;
7498   } else {
7499     switch (II->getIntrinsicID()) {
7500     default: break;
7501     case Intrinsic::ppc_altivec_lvx:
7502     case Intrinsic::ppc_altivec_lvxl:
7503     case Intrinsic::x86_sse_loadu_ps:
7504     case Intrinsic::x86_sse2_loadu_pd:
7505     case Intrinsic::x86_sse2_loadu_dq:
7506       // Turn PPC lvx     -> load if the pointer is known aligned.
7507       // Turn X86 loadups -> load if the pointer is known aligned.
7508       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7509         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7510                                       PointerType::get(II->getType()), CI);
7511         return new LoadInst(Ptr);
7512       }
7513       break;
7514     case Intrinsic::ppc_altivec_stvx:
7515     case Intrinsic::ppc_altivec_stvxl:
7516       // Turn stvx -> store if the pointer is known aligned.
7517       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7518         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7519         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7520                                       OpPtrTy, CI);
7521         return new StoreInst(II->getOperand(1), Ptr);
7522       }
7523       break;
7524     case Intrinsic::x86_sse_storeu_ps:
7525     case Intrinsic::x86_sse2_storeu_pd:
7526     case Intrinsic::x86_sse2_storeu_dq:
7527     case Intrinsic::x86_sse2_storel_dq:
7528       // Turn X86 storeu -> store if the pointer is known aligned.
7529       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7530         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7531         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7532                                       OpPtrTy, CI);
7533         return new StoreInst(II->getOperand(2), Ptr);
7534       }
7535       break;
7536       
7537     case Intrinsic::x86_sse_cvttss2si: {
7538       // These intrinsics only demands the 0th element of its input vector.  If
7539       // we can simplify the input based on that, do so now.
7540       uint64_t UndefElts;
7541       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7542                                                 UndefElts)) {
7543         II->setOperand(1, V);
7544         return II;
7545       }
7546       break;
7547     }
7548       
7549     case Intrinsic::ppc_altivec_vperm:
7550       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7551       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
7552         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7553         
7554         // Check that all of the elements are integer constants or undefs.
7555         bool AllEltsOk = true;
7556         for (unsigned i = 0; i != 16; ++i) {
7557           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7558               !isa<UndefValue>(Mask->getOperand(i))) {
7559             AllEltsOk = false;
7560             break;
7561           }
7562         }
7563         
7564         if (AllEltsOk) {
7565           // Cast the input vectors to byte vectors.
7566           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7567                                         II->getOperand(1), Mask->getType(), CI);
7568           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7569                                         II->getOperand(2), Mask->getType(), CI);
7570           Value *Result = UndefValue::get(Op0->getType());
7571           
7572           // Only extract each element once.
7573           Value *ExtractedElts[32];
7574           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7575           
7576           for (unsigned i = 0; i != 16; ++i) {
7577             if (isa<UndefValue>(Mask->getOperand(i)))
7578               continue;
7579             unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7580             Idx &= 31;  // Match the hardware behavior.
7581             
7582             if (ExtractedElts[Idx] == 0) {
7583               Instruction *Elt = 
7584                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7585               InsertNewInstBefore(Elt, CI);
7586               ExtractedElts[Idx] = Elt;
7587             }
7588           
7589             // Insert this value into the result vector.
7590             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7591             InsertNewInstBefore(cast<Instruction>(Result), CI);
7592           }
7593           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7594         }
7595       }
7596       break;
7597
7598     case Intrinsic::stackrestore: {
7599       // If the save is right next to the restore, remove the restore.  This can
7600       // happen when variable allocas are DCE'd.
7601       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7602         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7603           BasicBlock::iterator BI = SS;
7604           if (&*++BI == II)
7605             return EraseInstFromFunction(CI);
7606         }
7607       }
7608       
7609       // If the stack restore is in a return/unwind block and if there are no
7610       // allocas or calls between the restore and the return, nuke the restore.
7611       TerminatorInst *TI = II->getParent()->getTerminator();
7612       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7613         BasicBlock::iterator BI = II;
7614         bool CannotRemove = false;
7615         for (++BI; &*BI != TI; ++BI) {
7616           if (isa<AllocaInst>(BI) ||
7617               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7618             CannotRemove = true;
7619             break;
7620           }
7621         }
7622         if (!CannotRemove)
7623           return EraseInstFromFunction(CI);
7624       }
7625       break;
7626     }
7627     }
7628   }
7629
7630   return visitCallSite(II);
7631 }
7632
7633 // InvokeInst simplification
7634 //
7635 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7636   return visitCallSite(&II);
7637 }
7638
7639 // visitCallSite - Improvements for call and invoke instructions.
7640 //
7641 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7642   bool Changed = false;
7643
7644   // If the callee is a constexpr cast of a function, attempt to move the cast
7645   // to the arguments of the call/invoke.
7646   if (transformConstExprCastCall(CS)) return 0;
7647
7648   Value *Callee = CS.getCalledValue();
7649
7650   if (Function *CalleeF = dyn_cast<Function>(Callee))
7651     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7652       Instruction *OldCall = CS.getInstruction();
7653       // If the call and callee calling conventions don't match, this call must
7654       // be unreachable, as the call is undefined.
7655       new StoreInst(ConstantInt::getTrue(),
7656                     UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
7657       if (!OldCall->use_empty())
7658         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7659       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7660         return EraseInstFromFunction(*OldCall);
7661       return 0;
7662     }
7663
7664   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7665     // This instruction is not reachable, just remove it.  We insert a store to
7666     // undef so that we know that this code is not reachable, despite the fact
7667     // that we can't modify the CFG here.
7668     new StoreInst(ConstantInt::getTrue(),
7669                   UndefValue::get(PointerType::get(Type::Int1Ty)),
7670                   CS.getInstruction());
7671
7672     if (!CS.getInstruction()->use_empty())
7673       CS.getInstruction()->
7674         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7675
7676     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7677       // Don't break the CFG, insert a dummy cond branch.
7678       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7679                      ConstantInt::getTrue(), II);
7680     }
7681     return EraseInstFromFunction(*CS.getInstruction());
7682   }
7683
7684   const PointerType *PTy = cast<PointerType>(Callee->getType());
7685   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7686   if (FTy->isVarArg()) {
7687     // See if we can optimize any arguments passed through the varargs area of
7688     // the call.
7689     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7690            E = CS.arg_end(); I != E; ++I)
7691       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7692         // If this cast does not effect the value passed through the varargs
7693         // area, we can eliminate the use of the cast.
7694         Value *Op = CI->getOperand(0);
7695         if (CI->isLosslessCast()) {
7696           *I = Op;
7697           Changed = true;
7698         }
7699       }
7700   }
7701
7702   return Changed ? CS.getInstruction() : 0;
7703 }
7704
7705 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7706 // attempt to move the cast to the arguments of the call/invoke.
7707 //
7708 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7709   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7710   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7711   if (CE->getOpcode() != Instruction::BitCast || 
7712       !isa<Function>(CE->getOperand(0)))
7713     return false;
7714   Function *Callee = cast<Function>(CE->getOperand(0));
7715   Instruction *Caller = CS.getInstruction();
7716
7717   // Okay, this is a cast from a function to a different type.  Unless doing so
7718   // would cause a type conversion of one of our arguments, change this call to
7719   // be a direct call with arguments casted to the appropriate types.
7720   //
7721   const FunctionType *FT = Callee->getFunctionType();
7722   const Type *OldRetTy = Caller->getType();
7723
7724   // Check to see if we are changing the return type...
7725   if (OldRetTy != FT->getReturnType()) {
7726     if (Callee->isDeclaration() && !Caller->use_empty() && 
7727         // Conversion is ok if changing from pointer to int of same size.
7728         !(isa<PointerType>(FT->getReturnType()) &&
7729           TD->getIntPtrType() == OldRetTy))
7730       return false;   // Cannot transform this return value.
7731
7732     // If the callsite is an invoke instruction, and the return value is used by
7733     // a PHI node in a successor, we cannot change the return type of the call
7734     // because there is no place to put the cast instruction (without breaking
7735     // the critical edge).  Bail out in this case.
7736     if (!Caller->use_empty())
7737       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7738         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7739              UI != E; ++UI)
7740           if (PHINode *PN = dyn_cast<PHINode>(*UI))
7741             if (PN->getParent() == II->getNormalDest() ||
7742                 PN->getParent() == II->getUnwindDest())
7743               return false;
7744   }
7745
7746   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7747   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7748
7749   CallSite::arg_iterator AI = CS.arg_begin();
7750   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7751     const Type *ParamTy = FT->getParamType(i);
7752     const Type *ActTy = (*AI)->getType();
7753     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7754     //Some conversions are safe even if we do not have a body.
7755     //Either we can cast directly, or we can upconvert the argument
7756     bool isConvertible = ActTy == ParamTy ||
7757       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
7758       (ParamTy->isInteger() && ActTy->isInteger() &&
7759        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7760       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7761        && c->getValue().isStrictlyPositive());
7762     if (Callee->isDeclaration() && !isConvertible) return false;
7763
7764     // Most other conversions can be done if we have a body, even if these
7765     // lose information, e.g. int->short.
7766     // Some conversions cannot be done at all, e.g. float to pointer.
7767     // Logic here parallels CastInst::getCastOpcode (the design there
7768     // requires legality checks like this be done before calling it).
7769     if (ParamTy->isInteger()) {
7770       if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7771         if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7772           return false;
7773       }
7774       if (!ActTy->isInteger() && !ActTy->isFloatingPoint() &&
7775           !isa<PointerType>(ActTy))
7776         return false;
7777     } else if (ParamTy->isFloatingPoint()) {
7778       if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7779         if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7780           return false;
7781       }
7782       if (!ActTy->isInteger() && !ActTy->isFloatingPoint())
7783         return false;
7784     } else if (const VectorType *VParamTy = dyn_cast<VectorType>(ParamTy)) {
7785       if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7786         if (VActTy->getBitWidth() != VParamTy->getBitWidth())
7787           return false;
7788       }
7789       if (VParamTy->getBitWidth() != ActTy->getPrimitiveSizeInBits())      
7790         return false;
7791     } else if (isa<PointerType>(ParamTy)) {
7792       if (!ActTy->isInteger() && !isa<PointerType>(ActTy))
7793         return false;
7794     } else {
7795       return false;
7796     }
7797   }
7798
7799   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7800       Callee->isDeclaration())
7801     return false;   // Do not delete arguments unless we have a function body...
7802
7803   // Okay, we decided that this is a safe thing to do: go ahead and start
7804   // inserting cast instructions as necessary...
7805   std::vector<Value*> Args;
7806   Args.reserve(NumActualArgs);
7807
7808   AI = CS.arg_begin();
7809   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7810     const Type *ParamTy = FT->getParamType(i);
7811     if ((*AI)->getType() == ParamTy) {
7812       Args.push_back(*AI);
7813     } else {
7814       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7815           false, ParamTy, false);
7816       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7817       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7818     }
7819   }
7820
7821   // If the function takes more arguments than the call was taking, add them
7822   // now...
7823   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7824     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7825
7826   // If we are removing arguments to the function, emit an obnoxious warning...
7827   if (FT->getNumParams() < NumActualArgs)
7828     if (!FT->isVarArg()) {
7829       cerr << "WARNING: While resolving call to function '"
7830            << Callee->getName() << "' arguments were dropped!\n";
7831     } else {
7832       // Add all of the arguments in their promoted form to the arg list...
7833       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7834         const Type *PTy = getPromotedType((*AI)->getType());
7835         if (PTy != (*AI)->getType()) {
7836           // Must promote to pass through va_arg area!
7837           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
7838                                                                 PTy, false);
7839           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7840           InsertNewInstBefore(Cast, *Caller);
7841           Args.push_back(Cast);
7842         } else {
7843           Args.push_back(*AI);
7844         }
7845       }
7846     }
7847
7848   if (FT->getReturnType() == Type::VoidTy)
7849     Caller->setName("");   // Void type should not have a name.
7850
7851   Instruction *NC;
7852   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7853     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7854                         &Args[0], Args.size(), Caller->getName(), Caller);
7855     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7856   } else {
7857     NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
7858     if (cast<CallInst>(Caller)->isTailCall())
7859       cast<CallInst>(NC)->setTailCall();
7860    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7861   }
7862
7863   // Insert a cast of the return type as necessary.
7864   Value *NV = NC;
7865   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7866     if (NV->getType() != Type::VoidTy) {
7867       const Type *CallerTy = Caller->getType();
7868       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
7869                                                             CallerTy, false);
7870       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7871
7872       // If this is an invoke instruction, we should insert it after the first
7873       // non-phi, instruction in the normal successor block.
7874       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7875         BasicBlock::iterator I = II->getNormalDest()->begin();
7876         while (isa<PHINode>(I)) ++I;
7877         InsertNewInstBefore(NC, *I);
7878       } else {
7879         // Otherwise, it's a call, just insert cast right after the call instr
7880         InsertNewInstBefore(NC, *Caller);
7881       }
7882       AddUsersToWorkList(*Caller);
7883     } else {
7884       NV = UndefValue::get(Caller->getType());
7885     }
7886   }
7887
7888   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7889     Caller->replaceAllUsesWith(NV);
7890   Caller->eraseFromParent();
7891   RemoveFromWorkList(Caller);
7892   return true;
7893 }
7894
7895 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7896 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7897 /// and a single binop.
7898 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7899   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7900   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7901          isa<CmpInst>(FirstInst));
7902   unsigned Opc = FirstInst->getOpcode();
7903   Value *LHSVal = FirstInst->getOperand(0);
7904   Value *RHSVal = FirstInst->getOperand(1);
7905     
7906   const Type *LHSType = LHSVal->getType();
7907   const Type *RHSType = RHSVal->getType();
7908   
7909   // Scan to see if all operands are the same opcode, all have one use, and all
7910   // kill their operands (i.e. the operands have one use).
7911   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7912     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7913     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7914         // Verify type of the LHS matches so we don't fold cmp's of different
7915         // types or GEP's with different index types.
7916         I->getOperand(0)->getType() != LHSType ||
7917         I->getOperand(1)->getType() != RHSType)
7918       return 0;
7919
7920     // If they are CmpInst instructions, check their predicates
7921     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7922       if (cast<CmpInst>(I)->getPredicate() !=
7923           cast<CmpInst>(FirstInst)->getPredicate())
7924         return 0;
7925     
7926     // Keep track of which operand needs a phi node.
7927     if (I->getOperand(0) != LHSVal) LHSVal = 0;
7928     if (I->getOperand(1) != RHSVal) RHSVal = 0;
7929   }
7930   
7931   // Otherwise, this is safe to transform, determine if it is profitable.
7932
7933   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7934   // Indexes are often folded into load/store instructions, so we don't want to
7935   // hide them behind a phi.
7936   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7937     return 0;
7938   
7939   Value *InLHS = FirstInst->getOperand(0);
7940   Value *InRHS = FirstInst->getOperand(1);
7941   PHINode *NewLHS = 0, *NewRHS = 0;
7942   if (LHSVal == 0) {
7943     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7944     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7945     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7946     InsertNewInstBefore(NewLHS, PN);
7947     LHSVal = NewLHS;
7948   }
7949   
7950   if (RHSVal == 0) {
7951     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7952     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7953     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7954     InsertNewInstBefore(NewRHS, PN);
7955     RHSVal = NewRHS;
7956   }
7957   
7958   // Add all operands to the new PHIs.
7959   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7960     if (NewLHS) {
7961       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7962       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7963     }
7964     if (NewRHS) {
7965       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7966       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7967     }
7968   }
7969     
7970   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7971     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7972   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7973     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
7974                            RHSVal);
7975   else {
7976     assert(isa<GetElementPtrInst>(FirstInst));
7977     return new GetElementPtrInst(LHSVal, RHSVal);
7978   }
7979 }
7980
7981 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7982 /// of the block that defines it.  This means that it must be obvious the value
7983 /// of the load is not changed from the point of the load to the end of the
7984 /// block it is in.
7985 ///
7986 /// Finally, it is safe, but not profitable, to sink a load targetting a
7987 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
7988 /// to a register.
7989 static bool isSafeToSinkLoad(LoadInst *L) {
7990   BasicBlock::iterator BBI = L, E = L->getParent()->end();
7991   
7992   for (++BBI; BBI != E; ++BBI)
7993     if (BBI->mayWriteToMemory())
7994       return false;
7995   
7996   // Check for non-address taken alloca.  If not address-taken already, it isn't
7997   // profitable to do this xform.
7998   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7999     bool isAddressTaken = false;
8000     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8001          UI != E; ++UI) {
8002       if (isa<LoadInst>(UI)) continue;
8003       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8004         // If storing TO the alloca, then the address isn't taken.
8005         if (SI->getOperand(1) == AI) continue;
8006       }
8007       isAddressTaken = true;
8008       break;
8009     }
8010     
8011     if (!isAddressTaken)
8012       return false;
8013   }
8014   
8015   return true;
8016 }
8017
8018
8019 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8020 // operator and they all are only used by the PHI, PHI together their
8021 // inputs, and do the operation once, to the result of the PHI.
8022 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8023   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8024
8025   // Scan the instruction, looking for input operations that can be folded away.
8026   // If all input operands to the phi are the same instruction (e.g. a cast from
8027   // the same type or "+42") we can pull the operation through the PHI, reducing
8028   // code size and simplifying code.
8029   Constant *ConstantOp = 0;
8030   const Type *CastSrcTy = 0;
8031   bool isVolatile = false;
8032   if (isa<CastInst>(FirstInst)) {
8033     CastSrcTy = FirstInst->getOperand(0)->getType();
8034   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8035     // Can fold binop, compare or shift here if the RHS is a constant, 
8036     // otherwise call FoldPHIArgBinOpIntoPHI.
8037     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8038     if (ConstantOp == 0)
8039       return FoldPHIArgBinOpIntoPHI(PN);
8040   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8041     isVolatile = LI->isVolatile();
8042     // We can't sink the load if the loaded value could be modified between the
8043     // load and the PHI.
8044     if (LI->getParent() != PN.getIncomingBlock(0) ||
8045         !isSafeToSinkLoad(LI))
8046       return 0;
8047   } else if (isa<GetElementPtrInst>(FirstInst)) {
8048     if (FirstInst->getNumOperands() == 2)
8049       return FoldPHIArgBinOpIntoPHI(PN);
8050     // Can't handle general GEPs yet.
8051     return 0;
8052   } else {
8053     return 0;  // Cannot fold this operation.
8054   }
8055
8056   // Check to see if all arguments are the same operation.
8057   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8058     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8059     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8060     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8061       return 0;
8062     if (CastSrcTy) {
8063       if (I->getOperand(0)->getType() != CastSrcTy)
8064         return 0;  // Cast operation must match.
8065     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8066       // We can't sink the load if the loaded value could be modified between 
8067       // the load and the PHI.
8068       if (LI->isVolatile() != isVolatile ||
8069           LI->getParent() != PN.getIncomingBlock(i) ||
8070           !isSafeToSinkLoad(LI))
8071         return 0;
8072     } else if (I->getOperand(1) != ConstantOp) {
8073       return 0;
8074     }
8075   }
8076
8077   // Okay, they are all the same operation.  Create a new PHI node of the
8078   // correct type, and PHI together all of the LHS's of the instructions.
8079   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8080                                PN.getName()+".in");
8081   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8082
8083   Value *InVal = FirstInst->getOperand(0);
8084   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8085
8086   // Add all operands to the new PHI.
8087   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8088     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8089     if (NewInVal != InVal)
8090       InVal = 0;
8091     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8092   }
8093
8094   Value *PhiVal;
8095   if (InVal) {
8096     // The new PHI unions all of the same values together.  This is really
8097     // common, so we handle it intelligently here for compile-time speed.
8098     PhiVal = InVal;
8099     delete NewPN;
8100   } else {
8101     InsertNewInstBefore(NewPN, PN);
8102     PhiVal = NewPN;
8103   }
8104
8105   // Insert and return the new operation.
8106   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8107     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8108   else if (isa<LoadInst>(FirstInst))
8109     return new LoadInst(PhiVal, "", isVolatile);
8110   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8111     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8112   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8113     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
8114                            PhiVal, ConstantOp);
8115   else
8116     assert(0 && "Unknown operation");
8117   return 0;
8118 }
8119
8120 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8121 /// that is dead.
8122 static bool DeadPHICycle(PHINode *PN,
8123                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
8124   if (PN->use_empty()) return true;
8125   if (!PN->hasOneUse()) return false;
8126
8127   // Remember this node, and if we find the cycle, return.
8128   if (!PotentiallyDeadPHIs.insert(PN))
8129     return true;
8130
8131   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8132     return DeadPHICycle(PU, PotentiallyDeadPHIs);
8133
8134   return false;
8135 }
8136
8137 // PHINode simplification
8138 //
8139 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8140   // If LCSSA is around, don't mess with Phi nodes
8141   if (MustPreserveLCSSA) return 0;
8142   
8143   if (Value *V = PN.hasConstantValue())
8144     return ReplaceInstUsesWith(PN, V);
8145
8146   // If all PHI operands are the same operation, pull them through the PHI,
8147   // reducing code size.
8148   if (isa<Instruction>(PN.getIncomingValue(0)) &&
8149       PN.getIncomingValue(0)->hasOneUse())
8150     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8151       return Result;
8152
8153   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
8154   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8155   // PHI)... break the cycle.
8156   if (PN.hasOneUse()) {
8157     Instruction *PHIUser = cast<Instruction>(PN.use_back());
8158     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
8159       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
8160       PotentiallyDeadPHIs.insert(&PN);
8161       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8162         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8163     }
8164    
8165     // If this phi has a single use, and if that use just computes a value for
8166     // the next iteration of a loop, delete the phi.  This occurs with unused
8167     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
8168     // common case here is good because the only other things that catch this
8169     // are induction variable analysis (sometimes) and ADCE, which is only run
8170     // late.
8171     if (PHIUser->hasOneUse() &&
8172         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8173         PHIUser->use_back() == &PN) {
8174       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8175     }
8176   }
8177
8178   return 0;
8179 }
8180
8181 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8182                                    Instruction *InsertPoint,
8183                                    InstCombiner *IC) {
8184   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8185   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
8186   // We must cast correctly to the pointer type. Ensure that we
8187   // sign extend the integer value if it is smaller as this is
8188   // used for address computation.
8189   Instruction::CastOps opcode = 
8190      (VTySize < PtrSize ? Instruction::SExt :
8191       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8192   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
8193 }
8194
8195
8196 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
8197   Value *PtrOp = GEP.getOperand(0);
8198   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
8199   // If so, eliminate the noop.
8200   if (GEP.getNumOperands() == 1)
8201     return ReplaceInstUsesWith(GEP, PtrOp);
8202
8203   if (isa<UndefValue>(GEP.getOperand(0)))
8204     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8205
8206   bool HasZeroPointerIndex = false;
8207   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8208     HasZeroPointerIndex = C->isNullValue();
8209
8210   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
8211     return ReplaceInstUsesWith(GEP, PtrOp);
8212
8213   // Eliminate unneeded casts for indices.
8214   bool MadeChange = false;
8215   
8216   gep_type_iterator GTI = gep_type_begin(GEP);
8217   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
8218     if (isa<SequentialType>(*GTI)) {
8219       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
8220         if (CI->getOpcode() == Instruction::ZExt ||
8221             CI->getOpcode() == Instruction::SExt) {
8222           const Type *SrcTy = CI->getOperand(0)->getType();
8223           // We can eliminate a cast from i32 to i64 iff the target 
8224           // is a 32-bit pointer target.
8225           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8226             MadeChange = true;
8227             GEP.setOperand(i, CI->getOperand(0));
8228           }
8229         }
8230       }
8231       // If we are using a wider index than needed for this platform, shrink it
8232       // to what we need.  If the incoming value needs a cast instruction,
8233       // insert it.  This explicit cast can make subsequent optimizations more
8234       // obvious.
8235       Value *Op = GEP.getOperand(i);
8236       if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
8237         if (Constant *C = dyn_cast<Constant>(Op)) {
8238           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
8239           MadeChange = true;
8240         } else {
8241           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8242                                 GEP);
8243           GEP.setOperand(i, Op);
8244           MadeChange = true;
8245         }
8246     }
8247   }
8248   if (MadeChange) return &GEP;
8249
8250   // If this GEP instruction doesn't move the pointer, and if the input operand
8251   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
8252   // real input to the dest type.
8253   if (GEP.hasAllZeroIndices() && isa<BitCastInst>(GEP.getOperand(0)))
8254     return new BitCastInst(cast<BitCastInst>(GEP.getOperand(0))->getOperand(0),
8255                            GEP.getType());
8256     
8257   // Combine Indices - If the source pointer to this getelementptr instruction
8258   // is a getelementptr instruction, combine the indices of the two
8259   // getelementptr instructions into a single instruction.
8260   //
8261   SmallVector<Value*, 8> SrcGEPOperands;
8262   if (User *Src = dyn_castGetElementPtr(PtrOp))
8263     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
8264
8265   if (!SrcGEPOperands.empty()) {
8266     // Note that if our source is a gep chain itself that we wait for that
8267     // chain to be resolved before we perform this transformation.  This
8268     // avoids us creating a TON of code in some cases.
8269     //
8270     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8271         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8272       return 0;   // Wait until our source is folded to completion.
8273
8274     SmallVector<Value*, 8> Indices;
8275
8276     // Find out whether the last index in the source GEP is a sequential idx.
8277     bool EndsWithSequential = false;
8278     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8279            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
8280       EndsWithSequential = !isa<StructType>(*I);
8281
8282     // Can we combine the two pointer arithmetics offsets?
8283     if (EndsWithSequential) {
8284       // Replace: gep (gep %P, long B), long A, ...
8285       // With:    T = long A+B; gep %P, T, ...
8286       //
8287       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
8288       if (SO1 == Constant::getNullValue(SO1->getType())) {
8289         Sum = GO1;
8290       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8291         Sum = SO1;
8292       } else {
8293         // If they aren't the same type, convert both to an integer of the
8294         // target's pointer size.
8295         if (SO1->getType() != GO1->getType()) {
8296           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
8297             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
8298           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
8299             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
8300           } else {
8301             unsigned PS = TD->getPointerSize();
8302             if (TD->getTypeSize(SO1->getType()) == PS) {
8303               // Convert GO1 to SO1's type.
8304               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
8305
8306             } else if (TD->getTypeSize(GO1->getType()) == PS) {
8307               // Convert SO1 to GO1's type.
8308               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
8309             } else {
8310               const Type *PT = TD->getIntPtrType();
8311               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8312               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
8313             }
8314           }
8315         }
8316         if (isa<Constant>(SO1) && isa<Constant>(GO1))
8317           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8318         else {
8319           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8320           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
8321         }
8322       }
8323
8324       // Recycle the GEP we already have if possible.
8325       if (SrcGEPOperands.size() == 2) {
8326         GEP.setOperand(0, SrcGEPOperands[0]);
8327         GEP.setOperand(1, Sum);
8328         return &GEP;
8329       } else {
8330         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8331                        SrcGEPOperands.end()-1);
8332         Indices.push_back(Sum);
8333         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8334       }
8335     } else if (isa<Constant>(*GEP.idx_begin()) &&
8336                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
8337                SrcGEPOperands.size() != 1) {
8338       // Otherwise we can do the fold if the first index of the GEP is a zero
8339       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8340                      SrcGEPOperands.end());
8341       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8342     }
8343
8344     if (!Indices.empty())
8345       return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8346                                    Indices.size(), GEP.getName());
8347
8348   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
8349     // GEP of global variable.  If all of the indices for this GEP are
8350     // constants, we can promote this to a constexpr instead of an instruction.
8351
8352     // Scan for nonconstants...
8353     SmallVector<Constant*, 8> Indices;
8354     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8355     for (; I != E && isa<Constant>(*I); ++I)
8356       Indices.push_back(cast<Constant>(*I));
8357
8358     if (I == E) {  // If they are all constants...
8359       Constant *CE = ConstantExpr::getGetElementPtr(GV,
8360                                                     &Indices[0],Indices.size());
8361
8362       // Replace all uses of the GEP with the new constexpr...
8363       return ReplaceInstUsesWith(GEP, CE);
8364     }
8365   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
8366     if (!isa<PointerType>(X->getType())) {
8367       // Not interesting.  Source pointer must be a cast from pointer.
8368     } else if (HasZeroPointerIndex) {
8369       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8370       // into     : GEP [10 x ubyte]* X, long 0, ...
8371       //
8372       // This occurs when the program declares an array extern like "int X[];"
8373       //
8374       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8375       const PointerType *XTy = cast<PointerType>(X->getType());
8376       if (const ArrayType *XATy =
8377           dyn_cast<ArrayType>(XTy->getElementType()))
8378         if (const ArrayType *CATy =
8379             dyn_cast<ArrayType>(CPTy->getElementType()))
8380           if (CATy->getElementType() == XATy->getElementType()) {
8381             // At this point, we know that the cast source type is a pointer
8382             // to an array of the same type as the destination pointer
8383             // array.  Because the array type is never stepped over (there
8384             // is a leading zero) we can fold the cast into this GEP.
8385             GEP.setOperand(0, X);
8386             return &GEP;
8387           }
8388     } else if (GEP.getNumOperands() == 2) {
8389       // Transform things like:
8390       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8391       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
8392       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8393       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8394       if (isa<ArrayType>(SrcElTy) &&
8395           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8396           TD->getTypeSize(ResElTy)) {
8397         Value *V = InsertNewInstBefore(
8398                new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
8399                                      GEP.getOperand(1), GEP.getName()), GEP);
8400         // V and GEP are both pointer types --> BitCast
8401         return new BitCastInst(V, GEP.getType());
8402       }
8403       
8404       // Transform things like:
8405       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8406       //   (where tmp = 8*tmp2) into:
8407       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8408       
8409       if (isa<ArrayType>(SrcElTy) &&
8410           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
8411         uint64_t ArrayEltSize =
8412             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8413         
8414         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
8415         // allow either a mul, shift, or constant here.
8416         Value *NewIdx = 0;
8417         ConstantInt *Scale = 0;
8418         if (ArrayEltSize == 1) {
8419           NewIdx = GEP.getOperand(1);
8420           Scale = ConstantInt::get(NewIdx->getType(), 1);
8421         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
8422           NewIdx = ConstantInt::get(CI->getType(), 1);
8423           Scale = CI;
8424         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8425           if (Inst->getOpcode() == Instruction::Shl &&
8426               isa<ConstantInt>(Inst->getOperand(1))) {
8427             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
8428             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
8429             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
8430             NewIdx = Inst->getOperand(0);
8431           } else if (Inst->getOpcode() == Instruction::Mul &&
8432                      isa<ConstantInt>(Inst->getOperand(1))) {
8433             Scale = cast<ConstantInt>(Inst->getOperand(1));
8434             NewIdx = Inst->getOperand(0);
8435           }
8436         }
8437
8438         // If the index will be to exactly the right offset with the scale taken
8439         // out, perform the transformation.
8440         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
8441           if (isa<ConstantInt>(Scale))
8442             Scale = ConstantInt::get(Scale->getType(),
8443                                       Scale->getZExtValue() / ArrayEltSize);
8444           if (Scale->getZExtValue() != 1) {
8445             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8446                                                        true /*SExt*/);
8447             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8448             NewIdx = InsertNewInstBefore(Sc, GEP);
8449           }
8450
8451           // Insert the new GEP instruction.
8452           Instruction *NewGEP =
8453             new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
8454                                   NewIdx, GEP.getName());
8455           NewGEP = InsertNewInstBefore(NewGEP, GEP);
8456           // The NewGEP must be pointer typed, so must the old one -> BitCast
8457           return new BitCastInst(NewGEP, GEP.getType());
8458         }
8459       }
8460     }
8461   }
8462
8463   return 0;
8464 }
8465
8466 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8467   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8468   if (AI.isArrayAllocation())    // Check C != 1
8469     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8470       const Type *NewTy = 
8471         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
8472       AllocationInst *New = 0;
8473
8474       // Create and insert the replacement instruction...
8475       if (isa<MallocInst>(AI))
8476         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
8477       else {
8478         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
8479         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
8480       }
8481
8482       InsertNewInstBefore(New, AI);
8483
8484       // Scan to the end of the allocation instructions, to skip over a block of
8485       // allocas if possible...
8486       //
8487       BasicBlock::iterator It = New;
8488       while (isa<AllocationInst>(*It)) ++It;
8489
8490       // Now that I is pointing to the first non-allocation-inst in the block,
8491       // insert our getelementptr instruction...
8492       //
8493       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
8494       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8495                                        New->getName()+".sub", It);
8496
8497       // Now make everything use the getelementptr instead of the original
8498       // allocation.
8499       return ReplaceInstUsesWith(AI, V);
8500     } else if (isa<UndefValue>(AI.getArraySize())) {
8501       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8502     }
8503
8504   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8505   // Note that we only do this for alloca's, because malloc should allocate and
8506   // return a unique pointer, even for a zero byte allocation.
8507   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
8508       TD->getTypeSize(AI.getAllocatedType()) == 0)
8509     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8510
8511   return 0;
8512 }
8513
8514 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8515   Value *Op = FI.getOperand(0);
8516
8517   // free undef -> unreachable.
8518   if (isa<UndefValue>(Op)) {
8519     // Insert a new store to null because we cannot modify the CFG here.
8520     new StoreInst(ConstantInt::getTrue(),
8521                   UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
8522     return EraseInstFromFunction(FI);
8523   }
8524   
8525   // If we have 'free null' delete the instruction.  This can happen in stl code
8526   // when lots of inlining happens.
8527   if (isa<ConstantPointerNull>(Op))
8528     return EraseInstFromFunction(FI);
8529   
8530   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8531   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
8532     FI.setOperand(0, CI->getOperand(0));
8533     return &FI;
8534   }
8535   
8536   // Change free (gep X, 0,0,0,0) into free(X)
8537   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
8538     if (GEPI->hasAllZeroIndices()) {
8539       AddToWorkList(GEPI);
8540       FI.setOperand(0, GEPI->getOperand(0));
8541       return &FI;
8542     }
8543   }
8544   
8545   // Change free(malloc) into nothing, if the malloc has a single use.
8546   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
8547     if (MI->hasOneUse()) {
8548       EraseInstFromFunction(FI);
8549       return EraseInstFromFunction(*MI);
8550     }
8551
8552   return 0;
8553 }
8554
8555
8556 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
8557 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8558   User *CI = cast<User>(LI.getOperand(0));
8559   Value *CastOp = CI->getOperand(0);
8560
8561   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8562   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8563     const Type *SrcPTy = SrcTy->getElementType();
8564
8565     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
8566          isa<VectorType>(DestPTy)) {
8567       // If the source is an array, the code below will not succeed.  Check to
8568       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8569       // constants.
8570       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8571         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8572           if (ASrcTy->getNumElements() != 0) {
8573             Value *Idxs[2];
8574             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8575             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8576             SrcTy = cast<PointerType>(CastOp->getType());
8577             SrcPTy = SrcTy->getElementType();
8578           }
8579
8580       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
8581             isa<VectorType>(SrcPTy)) &&
8582           // Do not allow turning this into a load of an integer, which is then
8583           // casted to a pointer, this pessimizes pointer analysis a lot.
8584           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8585           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8586                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8587
8588         // Okay, we are casting from one integer or pointer type to another of
8589         // the same size.  Instead of casting the pointer before the load, cast
8590         // the result of the loaded value.
8591         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8592                                                              CI->getName(),
8593                                                          LI.isVolatile()),LI);
8594         // Now cast the result of the load.
8595         return new BitCastInst(NewLoad, LI.getType());
8596       }
8597     }
8598   }
8599   return 0;
8600 }
8601
8602 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8603 /// from this value cannot trap.  If it is not obviously safe to load from the
8604 /// specified pointer, we do a quick local scan of the basic block containing
8605 /// ScanFrom, to determine if the address is already accessed.
8606 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8607   // If it is an alloca or global variable, it is always safe to load from.
8608   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8609
8610   // Otherwise, be a little bit agressive by scanning the local block where we
8611   // want to check to see if the pointer is already being loaded or stored
8612   // from/to.  If so, the previous load or store would have already trapped,
8613   // so there is no harm doing an extra load (also, CSE will later eliminate
8614   // the load entirely).
8615   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8616
8617   while (BBI != E) {
8618     --BBI;
8619
8620     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8621       if (LI->getOperand(0) == V) return true;
8622     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8623       if (SI->getOperand(1) == V) return true;
8624
8625   }
8626   return false;
8627 }
8628
8629 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8630   Value *Op = LI.getOperand(0);
8631
8632   // load (cast X) --> cast (load X) iff safe
8633   if (isa<CastInst>(Op))
8634     if (Instruction *Res = InstCombineLoadCast(*this, LI))
8635       return Res;
8636
8637   // None of the following transforms are legal for volatile loads.
8638   if (LI.isVolatile()) return 0;
8639   
8640   if (&LI.getParent()->front() != &LI) {
8641     BasicBlock::iterator BBI = &LI; --BBI;
8642     // If the instruction immediately before this is a store to the same
8643     // address, do a simple form of store->load forwarding.
8644     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8645       if (SI->getOperand(1) == LI.getOperand(0))
8646         return ReplaceInstUsesWith(LI, SI->getOperand(0));
8647     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8648       if (LIB->getOperand(0) == LI.getOperand(0))
8649         return ReplaceInstUsesWith(LI, LIB);
8650   }
8651
8652   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8653     if (isa<ConstantPointerNull>(GEPI->getOperand(0))) {
8654       // Insert a new store to null instruction before the load to indicate
8655       // that this code is not reachable.  We do this instead of inserting
8656       // an unreachable instruction directly because we cannot modify the
8657       // CFG.
8658       new StoreInst(UndefValue::get(LI.getType()),
8659                     Constant::getNullValue(Op->getType()), &LI);
8660       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8661     }
8662
8663   if (Constant *C = dyn_cast<Constant>(Op)) {
8664     // load null/undef -> undef
8665     if ((C->isNullValue() || isa<UndefValue>(C))) {
8666       // Insert a new store to null instruction before the load to indicate that
8667       // this code is not reachable.  We do this instead of inserting an
8668       // unreachable instruction directly because we cannot modify the CFG.
8669       new StoreInst(UndefValue::get(LI.getType()),
8670                     Constant::getNullValue(Op->getType()), &LI);
8671       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8672     }
8673
8674     // Instcombine load (constant global) into the value loaded.
8675     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8676       if (GV->isConstant() && !GV->isDeclaration())
8677         return ReplaceInstUsesWith(LI, GV->getInitializer());
8678
8679     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8680     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8681       if (CE->getOpcode() == Instruction::GetElementPtr) {
8682         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8683           if (GV->isConstant() && !GV->isDeclaration())
8684             if (Constant *V = 
8685                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8686               return ReplaceInstUsesWith(LI, V);
8687         if (CE->getOperand(0)->isNullValue()) {
8688           // Insert a new store to null instruction before the load to indicate
8689           // that this code is not reachable.  We do this instead of inserting
8690           // an unreachable instruction directly because we cannot modify the
8691           // CFG.
8692           new StoreInst(UndefValue::get(LI.getType()),
8693                         Constant::getNullValue(Op->getType()), &LI);
8694           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8695         }
8696
8697       } else if (CE->isCast()) {
8698         if (Instruction *Res = InstCombineLoadCast(*this, LI))
8699           return Res;
8700       }
8701   }
8702
8703   if (Op->hasOneUse()) {
8704     // Change select and PHI nodes to select values instead of addresses: this
8705     // helps alias analysis out a lot, allows many others simplifications, and
8706     // exposes redundancy in the code.
8707     //
8708     // Note that we cannot do the transformation unless we know that the
8709     // introduced loads cannot trap!  Something like this is valid as long as
8710     // the condition is always false: load (select bool %C, int* null, int* %G),
8711     // but it would not be valid if we transformed it to load from null
8712     // unconditionally.
8713     //
8714     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8715       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
8716       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8717           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8718         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8719                                      SI->getOperand(1)->getName()+".val"), LI);
8720         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8721                                      SI->getOperand(2)->getName()+".val"), LI);
8722         return new SelectInst(SI->getCondition(), V1, V2);
8723       }
8724
8725       // load (select (cond, null, P)) -> load P
8726       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8727         if (C->isNullValue()) {
8728           LI.setOperand(0, SI->getOperand(2));
8729           return &LI;
8730         }
8731
8732       // load (select (cond, P, null)) -> load P
8733       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8734         if (C->isNullValue()) {
8735           LI.setOperand(0, SI->getOperand(1));
8736           return &LI;
8737         }
8738     }
8739   }
8740   return 0;
8741 }
8742
8743 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
8744 /// when possible.
8745 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8746   User *CI = cast<User>(SI.getOperand(1));
8747   Value *CastOp = CI->getOperand(0);
8748
8749   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8750   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8751     const Type *SrcPTy = SrcTy->getElementType();
8752
8753     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8754       // If the source is an array, the code below will not succeed.  Check to
8755       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8756       // constants.
8757       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8758         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8759           if (ASrcTy->getNumElements() != 0) {
8760             Value* Idxs[2];
8761             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8762             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8763             SrcTy = cast<PointerType>(CastOp->getType());
8764             SrcPTy = SrcTy->getElementType();
8765           }
8766
8767       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8768           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8769                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8770
8771         // Okay, we are casting from one integer or pointer type to another of
8772         // the same size.  Instead of casting the pointer before 
8773         // the store, cast the value to be stored.
8774         Value *NewCast;
8775         Value *SIOp0 = SI.getOperand(0);
8776         Instruction::CastOps opcode = Instruction::BitCast;
8777         const Type* CastSrcTy = SIOp0->getType();
8778         const Type* CastDstTy = SrcPTy;
8779         if (isa<PointerType>(CastDstTy)) {
8780           if (CastSrcTy->isInteger())
8781             opcode = Instruction::IntToPtr;
8782         } else if (isa<IntegerType>(CastDstTy)) {
8783           if (isa<PointerType>(SIOp0->getType()))
8784             opcode = Instruction::PtrToInt;
8785         }
8786         if (Constant *C = dyn_cast<Constant>(SIOp0))
8787           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
8788         else
8789           NewCast = IC.InsertNewInstBefore(
8790             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
8791             SI);
8792         return new StoreInst(NewCast, CastOp);
8793       }
8794     }
8795   }
8796   return 0;
8797 }
8798
8799 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8800   Value *Val = SI.getOperand(0);
8801   Value *Ptr = SI.getOperand(1);
8802
8803   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
8804     EraseInstFromFunction(SI);
8805     ++NumCombined;
8806     return 0;
8807   }
8808   
8809   // If the RHS is an alloca with a single use, zapify the store, making the
8810   // alloca dead.
8811   if (Ptr->hasOneUse()) {
8812     if (isa<AllocaInst>(Ptr)) {
8813       EraseInstFromFunction(SI);
8814       ++NumCombined;
8815       return 0;
8816     }
8817     
8818     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8819       if (isa<AllocaInst>(GEP->getOperand(0)) &&
8820           GEP->getOperand(0)->hasOneUse()) {
8821         EraseInstFromFunction(SI);
8822         ++NumCombined;
8823         return 0;
8824       }
8825   }
8826
8827   // Do really simple DSE, to catch cases where there are several consequtive
8828   // stores to the same location, separated by a few arithmetic operations. This
8829   // situation often occurs with bitfield accesses.
8830   BasicBlock::iterator BBI = &SI;
8831   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8832        --ScanInsts) {
8833     --BBI;
8834     
8835     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8836       // Prev store isn't volatile, and stores to the same location?
8837       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8838         ++NumDeadStore;
8839         ++BBI;
8840         EraseInstFromFunction(*PrevSI);
8841         continue;
8842       }
8843       break;
8844     }
8845     
8846     // If this is a load, we have to stop.  However, if the loaded value is from
8847     // the pointer we're loading and is producing the pointer we're storing,
8848     // then *this* store is dead (X = load P; store X -> P).
8849     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8850       if (LI == Val && LI->getOperand(0) == Ptr) {
8851         EraseInstFromFunction(SI);
8852         ++NumCombined;
8853         return 0;
8854       }
8855       // Otherwise, this is a load from some other location.  Stores before it
8856       // may not be dead.
8857       break;
8858     }
8859     
8860     // Don't skip over loads or things that can modify memory.
8861     if (BBI->mayWriteToMemory())
8862       break;
8863   }
8864   
8865   
8866   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
8867
8868   // store X, null    -> turns into 'unreachable' in SimplifyCFG
8869   if (isa<ConstantPointerNull>(Ptr)) {
8870     if (!isa<UndefValue>(Val)) {
8871       SI.setOperand(0, UndefValue::get(Val->getType()));
8872       if (Instruction *U = dyn_cast<Instruction>(Val))
8873         AddToWorkList(U);  // Dropped a use.
8874       ++NumCombined;
8875     }
8876     return 0;  // Do not modify these!
8877   }
8878
8879   // store undef, Ptr -> noop
8880   if (isa<UndefValue>(Val)) {
8881     EraseInstFromFunction(SI);
8882     ++NumCombined;
8883     return 0;
8884   }
8885
8886   // If the pointer destination is a cast, see if we can fold the cast into the
8887   // source instead.
8888   if (isa<CastInst>(Ptr))
8889     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8890       return Res;
8891   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8892     if (CE->isCast())
8893       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8894         return Res;
8895
8896   
8897   // If this store is the last instruction in the basic block, and if the block
8898   // ends with an unconditional branch, try to move it to the successor block.
8899   BBI = &SI; ++BBI;
8900   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8901     if (BI->isUnconditional())
8902       if (SimplifyStoreAtEndOfBlock(SI))
8903         return 0;  // xform done!
8904   
8905   return 0;
8906 }
8907
8908 /// SimplifyStoreAtEndOfBlock - Turn things like:
8909 ///   if () { *P = v1; } else { *P = v2 }
8910 /// into a phi node with a store in the successor.
8911 ///
8912 /// Simplify things like:
8913 ///   *P = v1; if () { *P = v2; }
8914 /// into a phi node with a store in the successor.
8915 ///
8916 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
8917   BasicBlock *StoreBB = SI.getParent();
8918   
8919   // Check to see if the successor block has exactly two incoming edges.  If
8920   // so, see if the other predecessor contains a store to the same location.
8921   // if so, insert a PHI node (if needed) and move the stores down.
8922   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
8923   
8924   // Determine whether Dest has exactly two predecessors and, if so, compute
8925   // the other predecessor.
8926   pred_iterator PI = pred_begin(DestBB);
8927   BasicBlock *OtherBB = 0;
8928   if (*PI != StoreBB)
8929     OtherBB = *PI;
8930   ++PI;
8931   if (PI == pred_end(DestBB))
8932     return false;
8933   
8934   if (*PI != StoreBB) {
8935     if (OtherBB)
8936       return false;
8937     OtherBB = *PI;
8938   }
8939   if (++PI != pred_end(DestBB))
8940     return false;
8941   
8942   
8943   // Verify that the other block ends in a branch and is not otherwise empty.
8944   BasicBlock::iterator BBI = OtherBB->getTerminator();
8945   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
8946   if (!OtherBr || BBI == OtherBB->begin())
8947     return false;
8948   
8949   // If the other block ends in an unconditional branch, check for the 'if then
8950   // else' case.  there is an instruction before the branch.
8951   StoreInst *OtherStore = 0;
8952   if (OtherBr->isUnconditional()) {
8953     // If this isn't a store, or isn't a store to the same location, bail out.
8954     --BBI;
8955     OtherStore = dyn_cast<StoreInst>(BBI);
8956     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
8957       return false;
8958   } else {
8959     // Otherwise, the other block ended with a conditional branch.  If one of the
8960     // destinations is StoreBB, then we have the if/then case.
8961     if (OtherBr->getSuccessor(0) != StoreBB && 
8962         OtherBr->getSuccessor(1) != StoreBB)
8963       return false;
8964     
8965     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
8966     // if/then triangle.  See if there is a store to the same ptr as SI that lives
8967     // in OtherBB.
8968     for (;; --BBI) {
8969       // Check to see if we find the matching store.
8970       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
8971         if (OtherStore->getOperand(1) != SI.getOperand(1))
8972           return false;
8973         break;
8974       }
8975       // If we find something that may be using the stored value, or if we run out
8976       // of instructions, we can't do the xform.
8977       if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
8978           BBI == OtherBB->begin())
8979         return false;
8980     }
8981     
8982     // In order to eliminate the store in OtherBr, we have to
8983     // make sure nothing reads the stored value in StoreBB.
8984     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
8985       // FIXME: This should really be AA driven.
8986       if (isa<LoadInst>(I) || I->mayWriteToMemory())
8987         return false;
8988     }
8989   }
8990   
8991   // Insert a PHI node now if we need it.
8992   Value *MergedVal = OtherStore->getOperand(0);
8993   if (MergedVal != SI.getOperand(0)) {
8994     PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8995     PN->reserveOperandSpace(2);
8996     PN->addIncoming(SI.getOperand(0), SI.getParent());
8997     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
8998     MergedVal = InsertNewInstBefore(PN, DestBB->front());
8999   }
9000   
9001   // Advance to a place where it is safe to insert the new store and
9002   // insert it.
9003   BBI = DestBB->begin();
9004   while (isa<PHINode>(BBI)) ++BBI;
9005   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9006                                     OtherStore->isVolatile()), *BBI);
9007   
9008   // Nuke the old stores.
9009   EraseInstFromFunction(SI);
9010   EraseInstFromFunction(*OtherStore);
9011   ++NumCombined;
9012   return true;
9013 }
9014
9015
9016 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9017   // Change br (not X), label True, label False to: br X, label False, True
9018   Value *X = 0;
9019   BasicBlock *TrueDest;
9020   BasicBlock *FalseDest;
9021   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9022       !isa<Constant>(X)) {
9023     // Swap Destinations and condition...
9024     BI.setCondition(X);
9025     BI.setSuccessor(0, FalseDest);
9026     BI.setSuccessor(1, TrueDest);
9027     return &BI;
9028   }
9029
9030   // Cannonicalize fcmp_one -> fcmp_oeq
9031   FCmpInst::Predicate FPred; Value *Y;
9032   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
9033                              TrueDest, FalseDest)))
9034     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9035          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9036       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
9037       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
9038       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9039       NewSCC->takeName(I);
9040       // Swap Destinations and condition...
9041       BI.setCondition(NewSCC);
9042       BI.setSuccessor(0, FalseDest);
9043       BI.setSuccessor(1, TrueDest);
9044       RemoveFromWorkList(I);
9045       I->eraseFromParent();
9046       AddToWorkList(NewSCC);
9047       return &BI;
9048     }
9049
9050   // Cannonicalize icmp_ne -> icmp_eq
9051   ICmpInst::Predicate IPred;
9052   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9053                       TrueDest, FalseDest)))
9054     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
9055          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9056          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9057       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
9058       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
9059       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9060       NewSCC->takeName(I);
9061       // Swap Destinations and condition...
9062       BI.setCondition(NewSCC);
9063       BI.setSuccessor(0, FalseDest);
9064       BI.setSuccessor(1, TrueDest);
9065       RemoveFromWorkList(I);
9066       I->eraseFromParent();;
9067       AddToWorkList(NewSCC);
9068       return &BI;
9069     }
9070
9071   return 0;
9072 }
9073
9074 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9075   Value *Cond = SI.getCondition();
9076   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9077     if (I->getOpcode() == Instruction::Add)
9078       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9079         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9080         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
9081           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
9082                                                 AddRHS));
9083         SI.setOperand(0, I->getOperand(0));
9084         AddToWorkList(I);
9085         return &SI;
9086       }
9087   }
9088   return 0;
9089 }
9090
9091 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9092 /// is to leave as a vector operation.
9093 static bool CheapToScalarize(Value *V, bool isConstant) {
9094   if (isa<ConstantAggregateZero>(V)) 
9095     return true;
9096   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
9097     if (isConstant) return true;
9098     // If all elts are the same, we can extract.
9099     Constant *Op0 = C->getOperand(0);
9100     for (unsigned i = 1; i < C->getNumOperands(); ++i)
9101       if (C->getOperand(i) != Op0)
9102         return false;
9103     return true;
9104   }
9105   Instruction *I = dyn_cast<Instruction>(V);
9106   if (!I) return false;
9107   
9108   // Insert element gets simplified to the inserted element or is deleted if
9109   // this is constant idx extract element and its a constant idx insertelt.
9110   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9111       isa<ConstantInt>(I->getOperand(2)))
9112     return true;
9113   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9114     return true;
9115   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9116     if (BO->hasOneUse() &&
9117         (CheapToScalarize(BO->getOperand(0), isConstant) ||
9118          CheapToScalarize(BO->getOperand(1), isConstant)))
9119       return true;
9120   if (CmpInst *CI = dyn_cast<CmpInst>(I))
9121     if (CI->hasOneUse() &&
9122         (CheapToScalarize(CI->getOperand(0), isConstant) ||
9123          CheapToScalarize(CI->getOperand(1), isConstant)))
9124       return true;
9125   
9126   return false;
9127 }
9128
9129 /// Read and decode a shufflevector mask.
9130 ///
9131 /// It turns undef elements into values that are larger than the number of
9132 /// elements in the input.
9133 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9134   unsigned NElts = SVI->getType()->getNumElements();
9135   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9136     return std::vector<unsigned>(NElts, 0);
9137   if (isa<UndefValue>(SVI->getOperand(2)))
9138     return std::vector<unsigned>(NElts, 2*NElts);
9139
9140   std::vector<unsigned> Result;
9141   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
9142   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9143     if (isa<UndefValue>(CP->getOperand(i)))
9144       Result.push_back(NElts*2);  // undef -> 8
9145     else
9146       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
9147   return Result;
9148 }
9149
9150 /// FindScalarElement - Given a vector and an element number, see if the scalar
9151 /// value is already around as a register, for example if it were inserted then
9152 /// extracted from the vector.
9153 static Value *FindScalarElement(Value *V, unsigned EltNo) {
9154   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9155   const VectorType *PTy = cast<VectorType>(V->getType());
9156   unsigned Width = PTy->getNumElements();
9157   if (EltNo >= Width)  // Out of range access.
9158     return UndefValue::get(PTy->getElementType());
9159   
9160   if (isa<UndefValue>(V))
9161     return UndefValue::get(PTy->getElementType());
9162   else if (isa<ConstantAggregateZero>(V))
9163     return Constant::getNullValue(PTy->getElementType());
9164   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
9165     return CP->getOperand(EltNo);
9166   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9167     // If this is an insert to a variable element, we don't know what it is.
9168     if (!isa<ConstantInt>(III->getOperand(2))) 
9169       return 0;
9170     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
9171     
9172     // If this is an insert to the element we are looking for, return the
9173     // inserted value.
9174     if (EltNo == IIElt) 
9175       return III->getOperand(1);
9176     
9177     // Otherwise, the insertelement doesn't modify the value, recurse on its
9178     // vector input.
9179     return FindScalarElement(III->getOperand(0), EltNo);
9180   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
9181     unsigned InEl = getShuffleMask(SVI)[EltNo];
9182     if (InEl < Width)
9183       return FindScalarElement(SVI->getOperand(0), InEl);
9184     else if (InEl < Width*2)
9185       return FindScalarElement(SVI->getOperand(1), InEl - Width);
9186     else
9187       return UndefValue::get(PTy->getElementType());
9188   }
9189   
9190   // Otherwise, we don't know.
9191   return 0;
9192 }
9193
9194 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
9195
9196   // If packed val is undef, replace extract with scalar undef.
9197   if (isa<UndefValue>(EI.getOperand(0)))
9198     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9199
9200   // If packed val is constant 0, replace extract with scalar 0.
9201   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9202     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9203   
9204   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
9205     // If packed val is constant with uniform operands, replace EI
9206     // with that operand
9207     Constant *op0 = C->getOperand(0);
9208     for (unsigned i = 1; i < C->getNumOperands(); ++i)
9209       if (C->getOperand(i) != op0) {
9210         op0 = 0; 
9211         break;
9212       }
9213     if (op0)
9214       return ReplaceInstUsesWith(EI, op0);
9215   }
9216   
9217   // If extracting a specified index from the vector, see if we can recursively
9218   // find a previously computed scalar that was inserted into the vector.
9219   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9220     unsigned IndexVal = IdxC->getZExtValue();
9221     unsigned VectorWidth = 
9222       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
9223       
9224     // If this is extracting an invalid index, turn this into undef, to avoid
9225     // crashing the code below.
9226     if (IndexVal >= VectorWidth)
9227       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9228     
9229     // This instruction only demands the single element from the input vector.
9230     // If the input vector has a single use, simplify it based on this use
9231     // property.
9232     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
9233       uint64_t UndefElts;
9234       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
9235                                                 1 << IndexVal,
9236                                                 UndefElts)) {
9237         EI.setOperand(0, V);
9238         return &EI;
9239       }
9240     }
9241     
9242     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
9243       return ReplaceInstUsesWith(EI, Elt);
9244     
9245     // If the this extractelement is directly using a bitcast from a vector of
9246     // the same number of elements, see if we can find the source element from
9247     // it.  In this case, we will end up needing to bitcast the scalars.
9248     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
9249       if (const VectorType *VT = 
9250               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
9251         if (VT->getNumElements() == VectorWidth)
9252           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
9253             return new BitCastInst(Elt, EI.getType());
9254     }
9255   }
9256   
9257   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
9258     if (I->hasOneUse()) {
9259       // Push extractelement into predecessor operation if legal and
9260       // profitable to do so
9261       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
9262         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9263         if (CheapToScalarize(BO, isConstantElt)) {
9264           ExtractElementInst *newEI0 = 
9265             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9266                                    EI.getName()+".lhs");
9267           ExtractElementInst *newEI1 =
9268             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9269                                    EI.getName()+".rhs");
9270           InsertNewInstBefore(newEI0, EI);
9271           InsertNewInstBefore(newEI1, EI);
9272           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9273         }
9274       } else if (isa<LoadInst>(I)) {
9275         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
9276                                       PointerType::get(EI.getType()), EI);
9277         GetElementPtrInst *GEP = 
9278           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
9279         InsertNewInstBefore(GEP, EI);
9280         return new LoadInst(GEP);
9281       }
9282     }
9283     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9284       // Extracting the inserted element?
9285       if (IE->getOperand(2) == EI.getOperand(1))
9286         return ReplaceInstUsesWith(EI, IE->getOperand(1));
9287       // If the inserted and extracted elements are constants, they must not
9288       // be the same value, extract from the pre-inserted value instead.
9289       if (isa<Constant>(IE->getOperand(2)) &&
9290           isa<Constant>(EI.getOperand(1))) {
9291         AddUsesToWorkList(EI);
9292         EI.setOperand(0, IE->getOperand(0));
9293         return &EI;
9294       }
9295     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9296       // If this is extracting an element from a shufflevector, figure out where
9297       // it came from and extract from the appropriate input element instead.
9298       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9299         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
9300         Value *Src;
9301         if (SrcIdx < SVI->getType()->getNumElements())
9302           Src = SVI->getOperand(0);
9303         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9304           SrcIdx -= SVI->getType()->getNumElements();
9305           Src = SVI->getOperand(1);
9306         } else {
9307           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9308         }
9309         return new ExtractElementInst(Src, SrcIdx);
9310       }
9311     }
9312   }
9313   return 0;
9314 }
9315
9316 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9317 /// elements from either LHS or RHS, return the shuffle mask and true. 
9318 /// Otherwise, return false.
9319 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9320                                          std::vector<Constant*> &Mask) {
9321   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9322          "Invalid CollectSingleShuffleElements");
9323   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9324
9325   if (isa<UndefValue>(V)) {
9326     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9327     return true;
9328   } else if (V == LHS) {
9329     for (unsigned i = 0; i != NumElts; ++i)
9330       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9331     return true;
9332   } else if (V == RHS) {
9333     for (unsigned i = 0; i != NumElts; ++i)
9334       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
9335     return true;
9336   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9337     // If this is an insert of an extract from some other vector, include it.
9338     Value *VecOp    = IEI->getOperand(0);
9339     Value *ScalarOp = IEI->getOperand(1);
9340     Value *IdxOp    = IEI->getOperand(2);
9341     
9342     if (!isa<ConstantInt>(IdxOp))
9343       return false;
9344     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9345     
9346     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
9347       // Okay, we can handle this if the vector we are insertinting into is
9348       // transitively ok.
9349       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9350         // If so, update the mask to reflect the inserted undef.
9351         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
9352         return true;
9353       }      
9354     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9355       if (isa<ConstantInt>(EI->getOperand(1)) &&
9356           EI->getOperand(0)->getType() == V->getType()) {
9357         unsigned ExtractedIdx =
9358           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9359         
9360         // This must be extracting from either LHS or RHS.
9361         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9362           // Okay, we can handle this if the vector we are insertinting into is
9363           // transitively ok.
9364           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9365             // If so, update the mask to reflect the inserted value.
9366             if (EI->getOperand(0) == LHS) {
9367               Mask[InsertedIdx & (NumElts-1)] = 
9368                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9369             } else {
9370               assert(EI->getOperand(0) == RHS);
9371               Mask[InsertedIdx & (NumElts-1)] = 
9372                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
9373               
9374             }
9375             return true;
9376           }
9377         }
9378       }
9379     }
9380   }
9381   // TODO: Handle shufflevector here!
9382   
9383   return false;
9384 }
9385
9386 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9387 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
9388 /// that computes V and the LHS value of the shuffle.
9389 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
9390                                      Value *&RHS) {
9391   assert(isa<VectorType>(V->getType()) && 
9392          (RHS == 0 || V->getType() == RHS->getType()) &&
9393          "Invalid shuffle!");
9394   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9395
9396   if (isa<UndefValue>(V)) {
9397     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9398     return V;
9399   } else if (isa<ConstantAggregateZero>(V)) {
9400     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
9401     return V;
9402   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9403     // If this is an insert of an extract from some other vector, include it.
9404     Value *VecOp    = IEI->getOperand(0);
9405     Value *ScalarOp = IEI->getOperand(1);
9406     Value *IdxOp    = IEI->getOperand(2);
9407     
9408     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9409       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9410           EI->getOperand(0)->getType() == V->getType()) {
9411         unsigned ExtractedIdx =
9412           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9413         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9414         
9415         // Either the extracted from or inserted into vector must be RHSVec,
9416         // otherwise we'd end up with a shuffle of three inputs.
9417         if (EI->getOperand(0) == RHS || RHS == 0) {
9418           RHS = EI->getOperand(0);
9419           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
9420           Mask[InsertedIdx & (NumElts-1)] = 
9421             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
9422           return V;
9423         }
9424         
9425         if (VecOp == RHS) {
9426           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
9427           // Everything but the extracted element is replaced with the RHS.
9428           for (unsigned i = 0; i != NumElts; ++i) {
9429             if (i != InsertedIdx)
9430               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
9431           }
9432           return V;
9433         }
9434         
9435         // If this insertelement is a chain that comes from exactly these two
9436         // vectors, return the vector and the effective shuffle.
9437         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9438           return EI->getOperand(0);
9439         
9440       }
9441     }
9442   }
9443   // TODO: Handle shufflevector here!
9444   
9445   // Otherwise, can't do anything fancy.  Return an identity vector.
9446   for (unsigned i = 0; i != NumElts; ++i)
9447     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9448   return V;
9449 }
9450
9451 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9452   Value *VecOp    = IE.getOperand(0);
9453   Value *ScalarOp = IE.getOperand(1);
9454   Value *IdxOp    = IE.getOperand(2);
9455   
9456   // Inserting an undef or into an undefined place, remove this.
9457   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
9458     ReplaceInstUsesWith(IE, VecOp);
9459   
9460   // If the inserted element was extracted from some other vector, and if the 
9461   // indexes are constant, try to turn this into a shufflevector operation.
9462   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9463     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9464         EI->getOperand(0)->getType() == IE.getType()) {
9465       unsigned NumVectorElts = IE.getType()->getNumElements();
9466       unsigned ExtractedIdx =
9467         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9468       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9469       
9470       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9471         return ReplaceInstUsesWith(IE, VecOp);
9472       
9473       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
9474         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9475       
9476       // If we are extracting a value from a vector, then inserting it right
9477       // back into the same place, just use the input vector.
9478       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9479         return ReplaceInstUsesWith(IE, VecOp);      
9480       
9481       // We could theoretically do this for ANY input.  However, doing so could
9482       // turn chains of insertelement instructions into a chain of shufflevector
9483       // instructions, and right now we do not merge shufflevectors.  As such,
9484       // only do this in a situation where it is clear that there is benefit.
9485       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9486         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
9487         // the values of VecOp, except then one read from EIOp0.
9488         // Build a new shuffle mask.
9489         std::vector<Constant*> Mask;
9490         if (isa<UndefValue>(VecOp))
9491           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
9492         else {
9493           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
9494           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
9495                                                        NumVectorElts));
9496         } 
9497         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9498         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
9499                                      ConstantVector::get(Mask));
9500       }
9501       
9502       // If this insertelement isn't used by some other insertelement, turn it
9503       // (and any insertelements it points to), into one big shuffle.
9504       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9505         std::vector<Constant*> Mask;
9506         Value *RHS = 0;
9507         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9508         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9509         // We now have a shuffle of LHS, RHS, Mask.
9510         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
9511       }
9512     }
9513   }
9514
9515   return 0;
9516 }
9517
9518
9519 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9520   Value *LHS = SVI.getOperand(0);
9521   Value *RHS = SVI.getOperand(1);
9522   std::vector<unsigned> Mask = getShuffleMask(&SVI);
9523
9524   bool MadeChange = false;
9525   
9526   // Undefined shuffle mask -> undefined value.
9527   if (isa<UndefValue>(SVI.getOperand(2)))
9528     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9529   
9530   // If we have shuffle(x, undef, mask) and any elements of mask refer to
9531   // the undef, change them to undefs.
9532   if (isa<UndefValue>(SVI.getOperand(1))) {
9533     // Scan to see if there are any references to the RHS.  If so, replace them
9534     // with undef element refs and set MadeChange to true.
9535     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9536       if (Mask[i] >= e && Mask[i] != 2*e) {
9537         Mask[i] = 2*e;
9538         MadeChange = true;
9539       }
9540     }
9541     
9542     if (MadeChange) {
9543       // Remap any references to RHS to use LHS.
9544       std::vector<Constant*> Elts;
9545       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9546         if (Mask[i] == 2*e)
9547           Elts.push_back(UndefValue::get(Type::Int32Ty));
9548         else
9549           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9550       }
9551       SVI.setOperand(2, ConstantVector::get(Elts));
9552     }
9553   }
9554   
9555   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
9556   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9557   if (LHS == RHS || isa<UndefValue>(LHS)) {
9558     if (isa<UndefValue>(LHS) && LHS == RHS) {
9559       // shuffle(undef,undef,mask) -> undef.
9560       return ReplaceInstUsesWith(SVI, LHS);
9561     }
9562     
9563     // Remap any references to RHS to use LHS.
9564     std::vector<Constant*> Elts;
9565     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9566       if (Mask[i] >= 2*e)
9567         Elts.push_back(UndefValue::get(Type::Int32Ty));
9568       else {
9569         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9570             (Mask[i] <  e && isa<UndefValue>(LHS)))
9571           Mask[i] = 2*e;     // Turn into undef.
9572         else
9573           Mask[i] &= (e-1);  // Force to LHS.
9574         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9575       }
9576     }
9577     SVI.setOperand(0, SVI.getOperand(1));
9578     SVI.setOperand(1, UndefValue::get(RHS->getType()));
9579     SVI.setOperand(2, ConstantVector::get(Elts));
9580     LHS = SVI.getOperand(0);
9581     RHS = SVI.getOperand(1);
9582     MadeChange = true;
9583   }
9584   
9585   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
9586   bool isLHSID = true, isRHSID = true;
9587     
9588   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9589     if (Mask[i] >= e*2) continue;  // Ignore undef values.
9590     // Is this an identity shuffle of the LHS value?
9591     isLHSID &= (Mask[i] == i);
9592       
9593     // Is this an identity shuffle of the RHS value?
9594     isRHSID &= (Mask[i]-e == i);
9595   }
9596
9597   // Eliminate identity shuffles.
9598   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9599   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
9600   
9601   // If the LHS is a shufflevector itself, see if we can combine it with this
9602   // one without producing an unusual shuffle.  Here we are really conservative:
9603   // we are absolutely afraid of producing a shuffle mask not in the input
9604   // program, because the code gen may not be smart enough to turn a merged
9605   // shuffle into two specific shuffles: it may produce worse code.  As such,
9606   // we only merge two shuffles if the result is one of the two input shuffle
9607   // masks.  In this case, merging the shuffles just removes one instruction,
9608   // which we know is safe.  This is good for things like turning:
9609   // (splat(splat)) -> splat.
9610   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9611     if (isa<UndefValue>(RHS)) {
9612       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9613
9614       std::vector<unsigned> NewMask;
9615       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9616         if (Mask[i] >= 2*e)
9617           NewMask.push_back(2*e);
9618         else
9619           NewMask.push_back(LHSMask[Mask[i]]);
9620       
9621       // If the result mask is equal to the src shuffle or this shuffle mask, do
9622       // the replacement.
9623       if (NewMask == LHSMask || NewMask == Mask) {
9624         std::vector<Constant*> Elts;
9625         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9626           if (NewMask[i] >= e*2) {
9627             Elts.push_back(UndefValue::get(Type::Int32Ty));
9628           } else {
9629             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
9630           }
9631         }
9632         return new ShuffleVectorInst(LHSSVI->getOperand(0),
9633                                      LHSSVI->getOperand(1),
9634                                      ConstantVector::get(Elts));
9635       }
9636     }
9637   }
9638
9639   return MadeChange ? &SVI : 0;
9640 }
9641
9642
9643
9644
9645 /// TryToSinkInstruction - Try to move the specified instruction from its
9646 /// current block into the beginning of DestBlock, which can only happen if it's
9647 /// safe to move the instruction past all of the instructions between it and the
9648 /// end of its block.
9649 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9650   assert(I->hasOneUse() && "Invariants didn't hold!");
9651
9652   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9653   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
9654
9655   // Do not sink alloca instructions out of the entry block.
9656   if (isa<AllocaInst>(I) && I->getParent() ==
9657         &DestBlock->getParent()->getEntryBlock())
9658     return false;
9659
9660   // We can only sink load instructions if there is nothing between the load and
9661   // the end of block that could change the value.
9662   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9663     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9664          Scan != E; ++Scan)
9665       if (Scan->mayWriteToMemory())
9666         return false;
9667   }
9668
9669   BasicBlock::iterator InsertPos = DestBlock->begin();
9670   while (isa<PHINode>(InsertPos)) ++InsertPos;
9671
9672   I->moveBefore(InsertPos);
9673   ++NumSunkInst;
9674   return true;
9675 }
9676
9677
9678 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9679 /// all reachable code to the worklist.
9680 ///
9681 /// This has a couple of tricks to make the code faster and more powerful.  In
9682 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9683 /// them to the worklist (this significantly speeds up instcombine on code where
9684 /// many instructions are dead or constant).  Additionally, if we find a branch
9685 /// whose condition is a known constant, we only visit the reachable successors.
9686 ///
9687 static void AddReachableCodeToWorklist(BasicBlock *BB, 
9688                                        SmallPtrSet<BasicBlock*, 64> &Visited,
9689                                        InstCombiner &IC,
9690                                        const TargetData *TD) {
9691   std::vector<BasicBlock*> Worklist;
9692   Worklist.push_back(BB);
9693
9694   while (!Worklist.empty()) {
9695     BB = Worklist.back();
9696     Worklist.pop_back();
9697     
9698     // We have now visited this block!  If we've already been here, ignore it.
9699     if (!Visited.insert(BB)) continue;
9700     
9701     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9702       Instruction *Inst = BBI++;
9703       
9704       // DCE instruction if trivially dead.
9705       if (isInstructionTriviallyDead(Inst)) {
9706         ++NumDeadInst;
9707         DOUT << "IC: DCE: " << *Inst;
9708         Inst->eraseFromParent();
9709         continue;
9710       }
9711       
9712       // ConstantProp instruction if trivially constant.
9713       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9714         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9715         Inst->replaceAllUsesWith(C);
9716         ++NumConstProp;
9717         Inst->eraseFromParent();
9718         continue;
9719       }
9720       
9721       IC.AddToWorkList(Inst);
9722     }
9723
9724     // Recursively visit successors.  If this is a branch or switch on a
9725     // constant, only visit the reachable successor.
9726     TerminatorInst *TI = BB->getTerminator();
9727     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9728       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9729         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9730         Worklist.push_back(BI->getSuccessor(!CondVal));
9731         continue;
9732       }
9733     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9734       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9735         // See if this is an explicit destination.
9736         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9737           if (SI->getCaseValue(i) == Cond) {
9738             Worklist.push_back(SI->getSuccessor(i));
9739             continue;
9740           }
9741         
9742         // Otherwise it is the default destination.
9743         Worklist.push_back(SI->getSuccessor(0));
9744         continue;
9745       }
9746     }
9747     
9748     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9749       Worklist.push_back(TI->getSuccessor(i));
9750   }
9751 }
9752
9753 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
9754   bool Changed = false;
9755   TD = &getAnalysis<TargetData>();
9756   
9757   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9758              << F.getNameStr() << "\n");
9759
9760   {
9761     // Do a depth-first traversal of the function, populate the worklist with
9762     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
9763     // track of which blocks we visit.
9764     SmallPtrSet<BasicBlock*, 64> Visited;
9765     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
9766
9767     // Do a quick scan over the function.  If we find any blocks that are
9768     // unreachable, remove any instructions inside of them.  This prevents
9769     // the instcombine code from having to deal with some bad special cases.
9770     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9771       if (!Visited.count(BB)) {
9772         Instruction *Term = BB->getTerminator();
9773         while (Term != BB->begin()) {   // Remove instrs bottom-up
9774           BasicBlock::iterator I = Term; --I;
9775
9776           DOUT << "IC: DCE: " << *I;
9777           ++NumDeadInst;
9778
9779           if (!I->use_empty())
9780             I->replaceAllUsesWith(UndefValue::get(I->getType()));
9781           I->eraseFromParent();
9782         }
9783       }
9784   }
9785
9786   while (!Worklist.empty()) {
9787     Instruction *I = RemoveOneFromWorkList();
9788     if (I == 0) continue;  // skip null values.
9789
9790     // Check to see if we can DCE the instruction.
9791     if (isInstructionTriviallyDead(I)) {
9792       // Add operands to the worklist.
9793       if (I->getNumOperands() < 4)
9794         AddUsesToWorkList(*I);
9795       ++NumDeadInst;
9796
9797       DOUT << "IC: DCE: " << *I;
9798
9799       I->eraseFromParent();
9800       RemoveFromWorkList(I);
9801       continue;
9802     }
9803
9804     // Instruction isn't dead, see if we can constant propagate it.
9805     if (Constant *C = ConstantFoldInstruction(I, TD)) {
9806       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9807
9808       // Add operands to the worklist.
9809       AddUsesToWorkList(*I);
9810       ReplaceInstUsesWith(*I, C);
9811
9812       ++NumConstProp;
9813       I->eraseFromParent();
9814       RemoveFromWorkList(I);
9815       continue;
9816     }
9817
9818     // See if we can trivially sink this instruction to a successor basic block.
9819     if (I->hasOneUse()) {
9820       BasicBlock *BB = I->getParent();
9821       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9822       if (UserParent != BB) {
9823         bool UserIsSuccessor = false;
9824         // See if the user is one of our successors.
9825         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9826           if (*SI == UserParent) {
9827             UserIsSuccessor = true;
9828             break;
9829           }
9830
9831         // If the user is one of our immediate successors, and if that successor
9832         // only has us as a predecessors (we'd have to split the critical edge
9833         // otherwise), we can keep going.
9834         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9835             next(pred_begin(UserParent)) == pred_end(UserParent))
9836           // Okay, the CFG is simple enough, try to sink this instruction.
9837           Changed |= TryToSinkInstruction(I, UserParent);
9838       }
9839     }
9840
9841     // Now that we have an instruction, try combining it to simplify it...
9842 #ifndef NDEBUG
9843     std::string OrigI;
9844 #endif
9845     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
9846     if (Instruction *Result = visit(*I)) {
9847       ++NumCombined;
9848       // Should we replace the old instruction with a new one?
9849       if (Result != I) {
9850         DOUT << "IC: Old = " << *I
9851              << "    New = " << *Result;
9852
9853         // Everything uses the new instruction now.
9854         I->replaceAllUsesWith(Result);
9855
9856         // Push the new instruction and any users onto the worklist.
9857         AddToWorkList(Result);
9858         AddUsersToWorkList(*Result);
9859
9860         // Move the name to the new instruction first.
9861         Result->takeName(I);
9862
9863         // Insert the new instruction into the basic block...
9864         BasicBlock *InstParent = I->getParent();
9865         BasicBlock::iterator InsertPos = I;
9866
9867         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
9868           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9869             ++InsertPos;
9870
9871         InstParent->getInstList().insert(InsertPos, Result);
9872
9873         // Make sure that we reprocess all operands now that we reduced their
9874         // use counts.
9875         AddUsesToWorkList(*I);
9876
9877         // Instructions can end up on the worklist more than once.  Make sure
9878         // we do not process an instruction that has been deleted.
9879         RemoveFromWorkList(I);
9880
9881         // Erase the old instruction.
9882         InstParent->getInstList().erase(I);
9883       } else {
9884 #ifndef NDEBUG
9885         DOUT << "IC: Mod = " << OrigI
9886              << "    New = " << *I;
9887 #endif
9888
9889         // If the instruction was modified, it's possible that it is now dead.
9890         // if so, remove it.
9891         if (isInstructionTriviallyDead(I)) {
9892           // Make sure we process all operands now that we are reducing their
9893           // use counts.
9894           AddUsesToWorkList(*I);
9895
9896           // Instructions may end up in the worklist more than once.  Erase all
9897           // occurrences of this instruction.
9898           RemoveFromWorkList(I);
9899           I->eraseFromParent();
9900         } else {
9901           AddToWorkList(I);
9902           AddUsersToWorkList(*I);
9903         }
9904       }
9905       Changed = true;
9906     }
9907   }
9908
9909   assert(WorklistMap.empty() && "Worklist empty, but map not?");
9910   return Changed;
9911 }
9912
9913
9914 bool InstCombiner::runOnFunction(Function &F) {
9915   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9916   
9917   bool EverMadeChange = false;
9918
9919   // Iterate while there is work to do.
9920   unsigned Iteration = 0;
9921   while (DoOneIteration(F, Iteration++)) 
9922     EverMadeChange = true;
9923   return EverMadeChange;
9924 }
9925
9926 FunctionPass *llvm::createInstructionCombiningPass() {
9927   return new InstCombiner();
9928 }
9929