b7c14c6f003c3ab60bbdc6e70ba6efa8f783aaf3
[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
187     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
188                              ICmpInst::Predicate Cond, Instruction &I);
189     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
190                                      BinaryOperator &I);
191     Instruction *commonCastTransforms(CastInst &CI);
192     Instruction *commonIntCastTransforms(CastInst &CI);
193     Instruction *visitTrunc(CastInst &CI);
194     Instruction *visitZExt(CastInst &CI);
195     Instruction *visitSExt(CastInst &CI);
196     Instruction *visitFPTrunc(CastInst &CI);
197     Instruction *visitFPExt(CastInst &CI);
198     Instruction *visitFPToUI(CastInst &CI);
199     Instruction *visitFPToSI(CastInst &CI);
200     Instruction *visitUIToFP(CastInst &CI);
201     Instruction *visitSIToFP(CastInst &CI);
202     Instruction *visitPtrToInt(CastInst &CI);
203     Instruction *visitIntToPtr(CastInst &CI);
204     Instruction *visitBitCast(CastInst &CI);
205     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
206                                 Instruction *FI);
207     Instruction *visitSelectInst(SelectInst &CI);
208     Instruction *visitCallInst(CallInst &CI);
209     Instruction *visitInvokeInst(InvokeInst &II);
210     Instruction *visitPHINode(PHINode &PN);
211     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
212     Instruction *visitAllocationInst(AllocationInst &AI);
213     Instruction *visitFreeInst(FreeInst &FI);
214     Instruction *visitLoadInst(LoadInst &LI);
215     Instruction *visitStoreInst(StoreInst &SI);
216     Instruction *visitBranchInst(BranchInst &BI);
217     Instruction *visitSwitchInst(SwitchInst &SI);
218     Instruction *visitInsertElementInst(InsertElementInst &IE);
219     Instruction *visitExtractElementInst(ExtractElementInst &EI);
220     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
221
222     // visitInstruction - Specify what to return for unhandled instructions...
223     Instruction *visitInstruction(Instruction &I) { return 0; }
224
225   private:
226     Instruction *visitCallSite(CallSite CS);
227     bool transformConstExprCastCall(CallSite CS);
228
229   public:
230     // InsertNewInstBefore - insert an instruction New before instruction Old
231     // in the program.  Add the new instruction to the worklist.
232     //
233     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
234       assert(New && New->getParent() == 0 &&
235              "New instruction already inserted into a basic block!");
236       BasicBlock *BB = Old.getParent();
237       BB->getInstList().insert(&Old, New);  // Insert inst
238       AddToWorkList(New);
239       return New;
240     }
241
242     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
243     /// This also adds the cast to the worklist.  Finally, this returns the
244     /// cast.
245     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
246                             Instruction &Pos) {
247       if (V->getType() == Ty) return V;
248
249       if (Constant *CV = dyn_cast<Constant>(V))
250         return ConstantExpr::getCast(opc, CV, Ty);
251       
252       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
253       AddToWorkList(C);
254       return C;
255     }
256
257     // ReplaceInstUsesWith - This method is to be used when an instruction is
258     // found to be dead, replacable with another preexisting expression.  Here
259     // we add all uses of I to the worklist, replace all uses of I with the new
260     // value, then return I, so that the inst combiner will know that I was
261     // modified.
262     //
263     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
264       AddUsersToWorkList(I);         // Add all modified instrs to worklist
265       if (&I != V) {
266         I.replaceAllUsesWith(V);
267         return &I;
268       } else {
269         // If we are replacing the instruction with itself, this must be in a
270         // segment of unreachable code, so just clobber the instruction.
271         I.replaceAllUsesWith(UndefValue::get(I.getType()));
272         return &I;
273       }
274     }
275
276     // UpdateValueUsesWith - This method is to be used when an value is
277     // found to be replacable with another preexisting expression or was
278     // updated.  Here we add all uses of I to the worklist, replace all uses of
279     // I with the new value (unless the instruction was just updated), then
280     // return true, so that the inst combiner will know that I was modified.
281     //
282     bool UpdateValueUsesWith(Value *Old, Value *New) {
283       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
284       if (Old != New)
285         Old->replaceAllUsesWith(New);
286       if (Instruction *I = dyn_cast<Instruction>(Old))
287         AddToWorkList(I);
288       if (Instruction *I = dyn_cast<Instruction>(New))
289         AddToWorkList(I);
290       return true;
291     }
292     
293     // EraseInstFromFunction - When dealing with an instruction that has side
294     // effects or produces a void value, we can't rely on DCE to delete the
295     // instruction.  Instead, visit methods should return the value returned by
296     // this function.
297     Instruction *EraseInstFromFunction(Instruction &I) {
298       assert(I.use_empty() && "Cannot erase instruction that is used!");
299       AddUsesToWorkList(I);
300       RemoveFromWorkList(&I);
301       I.eraseFromParent();
302       return 0;  // Don't do anything with FI
303     }
304
305   private:
306     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
307     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
308     /// casts that are known to not do anything...
309     ///
310     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
311                                    Value *V, const Type *DestTy,
312                                    Instruction *InsertBefore);
313
314     /// SimplifyCommutative - This performs a few simplifications for 
315     /// commutative operators.
316     bool SimplifyCommutative(BinaryOperator &I);
317
318     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
319     /// most-complex to least-complex order.
320     bool SimplifyCompare(CmpInst &I);
321
322     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
323     /// on the demanded bits.
324     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
325                               APInt& KnownZero, APInt& KnownOne,
326                               unsigned Depth = 0);
327
328     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
329                                       uint64_t &UndefElts, unsigned Depth = 0);
330       
331     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
332     // PHI node as operand #0, see if we can fold the instruction into the PHI
333     // (which is only possible if all operands to the PHI are constants).
334     Instruction *FoldOpIntoPhi(Instruction &I);
335
336     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
337     // operator and they all are only used by the PHI, PHI together their
338     // inputs, and do the operation once, to the result of the PHI.
339     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
340     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
341     
342     
343     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
344                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
345     
346     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
347                               bool isSub, Instruction &I);
348     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
349                                  bool isSigned, bool Inside, Instruction &IB);
350     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
351     Instruction *MatchBSwap(BinaryOperator &I);
352
353     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
354   };
355
356   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
357 }
358
359 // getComplexity:  Assign a complexity or rank value to LLVM Values...
360 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
361 static unsigned getComplexity(Value *V) {
362   if (isa<Instruction>(V)) {
363     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
364       return 3;
365     return 4;
366   }
367   if (isa<Argument>(V)) return 3;
368   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
369 }
370
371 // isOnlyUse - Return true if this instruction will be deleted if we stop using
372 // it.
373 static bool isOnlyUse(Value *V) {
374   return V->hasOneUse() || isa<Constant>(V);
375 }
376
377 // getPromotedType - Return the specified type promoted as it would be to pass
378 // though a va_arg area...
379 static const Type *getPromotedType(const Type *Ty) {
380   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
381     if (ITy->getBitWidth() < 32)
382       return Type::Int32Ty;
383   } else if (Ty == Type::FloatTy)
384     return Type::DoubleTy;
385   return Ty;
386 }
387
388 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
389 /// expression bitcast,  return the operand value, otherwise return null.
390 static Value *getBitCastOperand(Value *V) {
391   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
392     return I->getOperand(0);
393   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
394     if (CE->getOpcode() == Instruction::BitCast)
395       return CE->getOperand(0);
396   return 0;
397 }
398
399 /// This function is a wrapper around CastInst::isEliminableCastPair. It
400 /// simply extracts arguments and returns what that function returns.
401 static Instruction::CastOps 
402 isEliminableCastPair(
403   const CastInst *CI, ///< The first cast instruction
404   unsigned opcode,       ///< The opcode of the second cast instruction
405   const Type *DstTy,     ///< The target type for the second cast instruction
406   TargetData *TD         ///< The target data for pointer size
407 ) {
408   
409   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
410   const Type *MidTy = CI->getType();                  // B from above
411
412   // Get the opcodes of the two Cast instructions
413   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
414   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
415
416   return Instruction::CastOps(
417       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
418                                      DstTy, TD->getIntPtrType()));
419 }
420
421 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
422 /// in any code being generated.  It does not require codegen if V is simple
423 /// enough or if the cast can be folded into other casts.
424 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
425                               const Type *Ty, TargetData *TD) {
426   if (V->getType() == Ty || isa<Constant>(V)) return false;
427   
428   // If this is another cast that can be eliminated, it isn't codegen either.
429   if (const CastInst *CI = dyn_cast<CastInst>(V))
430     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
431       return false;
432   return true;
433 }
434
435 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
436 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
437 /// casts that are known to not do anything...
438 ///
439 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
440                                              Value *V, const Type *DestTy,
441                                              Instruction *InsertBefore) {
442   if (V->getType() == DestTy) return V;
443   if (Constant *C = dyn_cast<Constant>(V))
444     return ConstantExpr::getCast(opcode, C, DestTy);
445   
446   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
447 }
448
449 // SimplifyCommutative - This performs a few simplifications for commutative
450 // operators:
451 //
452 //  1. Order operands such that they are listed from right (least complex) to
453 //     left (most complex).  This puts constants before unary operators before
454 //     binary operators.
455 //
456 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
457 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
458 //
459 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
460   bool Changed = false;
461   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
462     Changed = !I.swapOperands();
463
464   if (!I.isAssociative()) return Changed;
465   Instruction::BinaryOps Opcode = I.getOpcode();
466   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
467     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
468       if (isa<Constant>(I.getOperand(1))) {
469         Constant *Folded = ConstantExpr::get(I.getOpcode(),
470                                              cast<Constant>(I.getOperand(1)),
471                                              cast<Constant>(Op->getOperand(1)));
472         I.setOperand(0, Op->getOperand(0));
473         I.setOperand(1, Folded);
474         return true;
475       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
476         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
477             isOnlyUse(Op) && isOnlyUse(Op1)) {
478           Constant *C1 = cast<Constant>(Op->getOperand(1));
479           Constant *C2 = cast<Constant>(Op1->getOperand(1));
480
481           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
482           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
483           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
484                                                     Op1->getOperand(0),
485                                                     Op1->getName(), &I);
486           AddToWorkList(New);
487           I.setOperand(0, New);
488           I.setOperand(1, Folded);
489           return true;
490         }
491     }
492   return Changed;
493 }
494
495 /// SimplifyCompare - For a CmpInst this function just orders the operands
496 /// so that theyare listed from right (least complex) to left (most complex).
497 /// This puts constants before unary operators before binary operators.
498 bool InstCombiner::SimplifyCompare(CmpInst &I) {
499   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
500     return false;
501   I.swapOperands();
502   // Compare instructions are not associative so there's nothing else we can do.
503   return true;
504 }
505
506 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
507 // if the LHS is a constant zero (which is the 'negate' form).
508 //
509 static inline Value *dyn_castNegVal(Value *V) {
510   if (BinaryOperator::isNeg(V))
511     return BinaryOperator::getNegArgument(V);
512
513   // Constants can be considered to be negated values if they can be folded.
514   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
515     return ConstantExpr::getNeg(C);
516   return 0;
517 }
518
519 static inline Value *dyn_castNotVal(Value *V) {
520   if (BinaryOperator::isNot(V))
521     return BinaryOperator::getNotArgument(V);
522
523   // Constants can be considered to be not'ed values...
524   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
525     return ConstantExpr::getNot(C);
526   return 0;
527 }
528
529 // dyn_castFoldableMul - If this value is a multiply that can be folded into
530 // other computations (because it has a constant operand), return the
531 // non-constant operand of the multiply, and set CST to point to the multiplier.
532 // Otherwise, return null.
533 //
534 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
535   if (V->hasOneUse() && V->getType()->isInteger())
536     if (Instruction *I = dyn_cast<Instruction>(V)) {
537       if (I->getOpcode() == Instruction::Mul)
538         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
539           return I->getOperand(0);
540       if (I->getOpcode() == Instruction::Shl)
541         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
542           // The multiplier is really 1 << CST.
543           Constant *One = ConstantInt::get(V->getType(), 1);
544           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
545           return I->getOperand(0);
546         }
547     }
548   return 0;
549 }
550
551 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
552 /// expression, return it.
553 static User *dyn_castGetElementPtr(Value *V) {
554   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
555   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
556     if (CE->getOpcode() == Instruction::GetElementPtr)
557       return cast<User>(V);
558   return false;
559 }
560
561 /// AddOne - Add one to a ConstantInt
562 static ConstantInt *AddOne(ConstantInt *C) {
563   APInt Val(C->getValue());
564   return ConstantInt::get(++Val);
565 }
566 /// SubOne - Subtract one from a ConstantInt
567 static ConstantInt *SubOne(ConstantInt *C) {
568   APInt Val(C->getValue());
569   return ConstantInt::get(--Val);
570 }
571 /// Add - Add two ConstantInts together
572 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
573   return ConstantInt::get(C1->getValue() + C2->getValue());
574 }
575 /// And - Bitwise AND two ConstantInts together
576 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
577   return ConstantInt::get(C1->getValue() & C2->getValue());
578 }
579 /// Subtract - Subtract one ConstantInt from another
580 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
581   return ConstantInt::get(C1->getValue() - C2->getValue());
582 }
583 /// Multiply - Multiply two ConstantInts together
584 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
585   return ConstantInt::get(C1->getValue() * C2->getValue());
586 }
587
588 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
589 /// known to be either zero or one and return them in the KnownZero/KnownOne
590 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
591 /// processing.
592 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
593 /// we cannot optimize based on the assumption that it is zero without changing
594 /// it to be an explicit zero.  If we don't change it to zero, other code could
595 /// optimized based on the contradictory assumption that it is non-zero.
596 /// Because instcombine aggressively folds operations with undef args anyway,
597 /// this won't lose us code quality.
598 static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero, 
599                               APInt& KnownOne, unsigned Depth = 0) {
600   assert(V && "No Value?");
601   assert(Depth <= 6 && "Limit Search Depth");
602   uint32_t BitWidth = Mask.getBitWidth();
603   const IntegerType *VTy = cast<IntegerType>(V->getType());
604   assert(VTy->getBitWidth() == BitWidth &&
605          KnownZero.getBitWidth() == BitWidth && 
606          KnownOne.getBitWidth() == BitWidth &&
607          "VTy, Mask, KnownOne and KnownZero should have same BitWidth");
608   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
609     // We know all of the bits for a constant!
610     KnownOne = CI->getValue() & Mask;
611     KnownZero = ~KnownOne & Mask;
612     return;
613   }
614
615   if (Depth == 6 || Mask == 0)
616     return;  // Limit search depth.
617
618   Instruction *I = dyn_cast<Instruction>(V);
619   if (!I) return;
620
621   KnownZero.clear(); KnownOne.clear();   // Don't know anything.
622   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
623   
624   switch (I->getOpcode()) {
625   case Instruction::And: {
626     // If either the LHS or the RHS are Zero, the result is zero.
627     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
628     APInt Mask2(Mask & ~KnownZero);
629     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
630     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
631     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
632     
633     // Output known-1 bits are only known if set in both the LHS & RHS.
634     KnownOne &= KnownOne2;
635     // Output known-0 are known to be clear if zero in either the LHS | RHS.
636     KnownZero |= KnownZero2;
637     return;
638   }
639   case Instruction::Or: {
640     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
641     APInt Mask2(Mask & ~KnownOne);
642     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
643     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
644     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
645     
646     // Output known-0 bits are only known if clear in both the LHS & RHS.
647     KnownZero &= KnownZero2;
648     // Output known-1 are known to be set if set in either the LHS | RHS.
649     KnownOne |= KnownOne2;
650     return;
651   }
652   case Instruction::Xor: {
653     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
654     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
655     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
656     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
657     
658     // Output known-0 bits are known if clear or set in both the LHS & RHS.
659     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
660     // Output known-1 are known to be set if set in only one of the LHS, RHS.
661     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
662     KnownZero = KnownZeroOut;
663     return;
664   }
665   case Instruction::Select:
666     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
667     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
668     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
669     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
670
671     // Only known if known in both the LHS and RHS.
672     KnownOne &= KnownOne2;
673     KnownZero &= KnownZero2;
674     return;
675   case Instruction::FPTrunc:
676   case Instruction::FPExt:
677   case Instruction::FPToUI:
678   case Instruction::FPToSI:
679   case Instruction::SIToFP:
680   case Instruction::PtrToInt:
681   case Instruction::UIToFP:
682   case Instruction::IntToPtr:
683     return; // Can't work with floating point or pointers
684   case Instruction::Trunc: {
685     // All these have integer operands
686     uint32_t SrcBitWidth = 
687       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
688     ComputeMaskedBits(I->getOperand(0), APInt(Mask).zext(SrcBitWidth), 
689       KnownZero.zext(SrcBitWidth), KnownOne.zext(SrcBitWidth), Depth+1);
690     KnownZero.trunc(BitWidth);
691     KnownOne.trunc(BitWidth);
692     return;
693   }
694   case Instruction::BitCast: {
695     const Type *SrcTy = I->getOperand(0)->getType();
696     if (SrcTy->isInteger()) {
697       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
698       return;
699     }
700     break;
701   }
702   case Instruction::ZExt:  {
703     // Compute the bits in the result that are not present in the input.
704     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
705     uint32_t SrcBitWidth = SrcTy->getBitWidth();
706     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
707       
708     ComputeMaskedBits(I->getOperand(0), APInt(Mask).trunc(SrcBitWidth), 
709       KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
710     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
711     // The top bits are known to be zero.
712     KnownZero.zext(BitWidth);
713     KnownOne.zext(BitWidth);
714     KnownZero |= NewBits;
715     return;
716   }
717   case Instruction::SExt: {
718     // Compute the bits in the result that are not present in the input.
719     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
720     uint32_t SrcBitWidth = SrcTy->getBitWidth();
721     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
722       
723     ComputeMaskedBits(I->getOperand(0), APInt(Mask).trunc(SrcBitWidth), 
724       KnownZero.trunc(SrcBitWidth), KnownOne.trunc(SrcBitWidth), Depth+1);
725     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
726     KnownZero.zext(BitWidth);
727     KnownOne.zext(BitWidth);
728
729     // If the sign bit of the input is known set or clear, then we know the
730     // top bits of the result.
731     APInt InSignBit(APInt::getSignBit(SrcTy->getBitWidth()));
732     InSignBit.zext(BitWidth);
733     if ((KnownZero & InSignBit) != 0) {          // Input sign bit known zero
734       KnownZero |= NewBits;
735       KnownOne &= ~NewBits;
736     } else if ((KnownOne & InSignBit) != 0) {    // Input sign bit known set
737       KnownOne |= NewBits;
738       KnownZero &= ~NewBits;
739     } else {                              // Input sign bit unknown
740       KnownZero &= ~NewBits;
741       KnownOne &= ~NewBits;
742     }
743     return;
744   }
745   case Instruction::Shl:
746     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
747     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
748       uint64_t ShiftAmt = SA->getZExtValue();
749       APInt Mask2(Mask.lshr(ShiftAmt));
750       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
751       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
752       KnownZero <<= ShiftAmt;
753       KnownOne  <<= ShiftAmt;
754       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
755       return;
756     }
757     break;
758   case Instruction::LShr:
759     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
760     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
761       // Compute the new bits that are at the top now.
762       uint64_t ShiftAmt = SA->getZExtValue();
763       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
764       
765       // Unsigned shift right.
766       APInt Mask2(Mask.shl(ShiftAmt));
767       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
768       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
769       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
770       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
771       KnownZero |= HighBits;  // high bits known zero.
772       return;
773     }
774     break;
775   case Instruction::AShr:
776     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
777     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
778       // Compute the new bits that are at the top now.
779       uint64_t ShiftAmt = SA->getZExtValue();
780       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
781       
782       // Signed shift right.
783       APInt Mask2(Mask.shl(ShiftAmt));
784       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
785       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
786       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
787       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
788         
789       // Handle the sign bits and adjust to where it is now in the mask.
790       APInt SignBit(APInt::getSignBit(BitWidth).lshr(ShiftAmt));
791         
792       if ((KnownZero & SignBit) != 0) {       // New bits are known zero.
793         KnownZero |= HighBits;
794       } else if ((KnownOne & SignBit) != 0) { // New bits are known one.
795         KnownOne |= HighBits;
796       }
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   APInt SignBit(APInt::getSignBit(BitWidth));
853   
854   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
855   // bit if it is unknown.
856   Min = KnownOne;
857   Max = KnownOne|UnknownBits;
858   
859   if ((SignBit & UnknownBits) != 0) { // Sign bit is unknown
860     Min |= SignBit;
861     Max &= ~SignBit;
862   }
863 }
864
865 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
866 // a set of known zero and one bits, compute the maximum and minimum values that
867 // could have the specified known zero and known one bits, returning them in
868 // min/max.
869 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
870                                                      const APInt& KnownZero,
871                                                      const APInt& KnownOne,
872                                                      APInt& Min,
873                                                      APInt& Max) {
874   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
875   assert(KnownZero.getBitWidth() == BitWidth && 
876          KnownOne.getBitWidth() == BitWidth &&
877          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
878          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
879   APInt UnknownBits = ~(KnownZero|KnownOne);
880   
881   // The minimum value is when the unknown bits are all zeros.
882   Min = KnownOne;
883   // The maximum value is when the unknown bits are all ones.
884   Max = KnownOne|UnknownBits;
885 }
886
887 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
888 /// value based on the demanded bits. When this function is called, it is known
889 /// that only the bits set in DemandedMask of the result of V are ever used
890 /// downstream. Consequently, depending on the mask and V, it may be possible
891 /// to replace V with a constant or one of its operands. In such cases, this
892 /// function does the replacement and returns true. In all other cases, it
893 /// returns false after analyzing the expression and setting KnownOne and known
894 /// to be one in the expression. KnownZero contains all the bits that are known
895 /// to be zero in the expression. These are provided to potentially allow the
896 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
897 /// the expression. KnownOne and KnownZero always follow the invariant that 
898 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
899 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
900 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
901 /// and KnownOne must all be the same.
902 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
903                                         APInt& KnownZero, APInt& KnownOne,
904                                         unsigned Depth) {
905   assert(V != 0 && "Null pointer of Value???");
906   assert(Depth <= 6 && "Limit Search Depth");
907   uint32_t BitWidth = DemandedMask.getBitWidth();
908   const IntegerType *VTy = cast<IntegerType>(V->getType());
909   assert(VTy->getBitWidth() == BitWidth && 
910          KnownZero.getBitWidth() == BitWidth && 
911          KnownOne.getBitWidth() == BitWidth &&
912          "Value *V, DemandedMask, KnownZero and KnownOne \
913           must have same BitWidth");
914   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
915     // We know all of the bits for a constant!
916     KnownOne = CI->getValue() & DemandedMask;
917     KnownZero = ~KnownOne & DemandedMask;
918     return false;
919   }
920   
921   KnownZero.clear(); 
922   KnownOne.clear();
923   if (!V->hasOneUse()) {    // Other users may use these bits.
924     if (Depth != 0) {       // Not at the root.
925       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
926       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
927       return false;
928     }
929     // If this is the root being simplified, allow it to have multiple uses,
930     // just set the DemandedMask to all bits.
931     DemandedMask = APInt::getAllOnesValue(BitWidth);
932   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
933     if (V != UndefValue::get(VTy))
934       return UpdateValueUsesWith(V, UndefValue::get(VTy));
935     return false;
936   } else if (Depth == 6) {        // Limit search depth.
937     return false;
938   }
939   
940   Instruction *I = dyn_cast<Instruction>(V);
941   if (!I) return false;        // Only analyze instructions.
942
943   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
944   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
945   switch (I->getOpcode()) {
946   default: break;
947   case Instruction::And:
948     // If either the LHS or the RHS are Zero, the result is zero.
949     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
950                              RHSKnownZero, RHSKnownOne, Depth+1))
951       return true;
952     assert((RHSKnownZero & RHSKnownOne) == 0 && 
953            "Bits known to be one AND zero?"); 
954
955     // If something is known zero on the RHS, the bits aren't demanded on the
956     // LHS.
957     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
958                              LHSKnownZero, LHSKnownOne, Depth+1))
959       return true;
960     assert((LHSKnownZero & LHSKnownOne) == 0 && 
961            "Bits known to be one AND zero?"); 
962
963     // If all of the demanded bits are known 1 on one side, return the other.
964     // These bits cannot contribute to the result of the 'and'.
965     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
966         (DemandedMask & ~LHSKnownZero))
967       return UpdateValueUsesWith(I, I->getOperand(0));
968     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
969         (DemandedMask & ~RHSKnownZero))
970       return UpdateValueUsesWith(I, I->getOperand(1));
971     
972     // If all of the demanded bits in the inputs are known zeros, return zero.
973     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
974       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
975       
976     // If the RHS is a constant, see if we can simplify it.
977     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
978       return UpdateValueUsesWith(I, I);
979       
980     // Output known-1 bits are only known if set in both the LHS & RHS.
981     RHSKnownOne &= LHSKnownOne;
982     // Output known-0 are known to be clear if zero in either the LHS | RHS.
983     RHSKnownZero |= LHSKnownZero;
984     break;
985   case Instruction::Or:
986     // If either the LHS or the RHS are One, the result is One.
987     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
988                              RHSKnownZero, RHSKnownOne, Depth+1))
989       return true;
990     assert((RHSKnownZero & RHSKnownOne) == 0 && 
991            "Bits known to be one AND zero?"); 
992     // If something is known one on the RHS, the bits aren't demanded on the
993     // LHS.
994     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
995                              LHSKnownZero, LHSKnownOne, Depth+1))
996       return true;
997     assert((LHSKnownZero & LHSKnownOne) == 0 && 
998            "Bits known to be one AND zero?"); 
999     
1000     // If all of the demanded bits are known zero on one side, return the other.
1001     // These bits cannot contribute to the result of the 'or'.
1002     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1003         (DemandedMask & ~LHSKnownOne))
1004       return UpdateValueUsesWith(I, I->getOperand(0));
1005     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1006         (DemandedMask & ~RHSKnownOne))
1007       return UpdateValueUsesWith(I, I->getOperand(1));
1008
1009     // If all of the potentially set bits on one side are known to be set on
1010     // the other side, just use the 'other' side.
1011     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1012         (DemandedMask & (~RHSKnownZero)))
1013       return UpdateValueUsesWith(I, I->getOperand(0));
1014     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1015         (DemandedMask & (~LHSKnownZero)))
1016       return UpdateValueUsesWith(I, I->getOperand(1));
1017         
1018     // If the RHS is a constant, see if we can simplify it.
1019     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1020       return UpdateValueUsesWith(I, I);
1021           
1022     // Output known-0 bits are only known if clear in both the LHS & RHS.
1023     RHSKnownZero &= LHSKnownZero;
1024     // Output known-1 are known to be set if set in either the LHS | RHS.
1025     RHSKnownOne |= LHSKnownOne;
1026     break;
1027   case Instruction::Xor: {
1028     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1029                              RHSKnownZero, RHSKnownOne, Depth+1))
1030       return true;
1031     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1032            "Bits known to be one AND zero?"); 
1033     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1034                              LHSKnownZero, LHSKnownOne, Depth+1))
1035       return true;
1036     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1037            "Bits known to be one AND zero?"); 
1038     
1039     // If all of the demanded bits are known zero on one side, return the other.
1040     // These bits cannot contribute to the result of the 'xor'.
1041     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1042       return UpdateValueUsesWith(I, I->getOperand(0));
1043     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1044       return UpdateValueUsesWith(I, I->getOperand(1));
1045     
1046     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1047     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1048                          (RHSKnownOne & LHSKnownOne);
1049     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1050     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1051                         (RHSKnownOne & LHSKnownZero);
1052     
1053     // If all of the demanded bits are known to be zero on one side or the
1054     // other, turn this into an *inclusive* or.
1055     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1056     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1057       Instruction *Or =
1058         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1059                                  I->getName());
1060       InsertNewInstBefore(Or, *I);
1061       return UpdateValueUsesWith(I, Or);
1062     }
1063     
1064     // If all of the demanded bits on one side are known, and all of the set
1065     // bits on that side are also known to be set on the other side, turn this
1066     // into an AND, as we know the bits will be cleared.
1067     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1068     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1069       // all known
1070       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1071         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1072         Instruction *And = 
1073           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1074         InsertNewInstBefore(And, *I);
1075         return UpdateValueUsesWith(I, And);
1076       }
1077     }
1078     
1079     // If the RHS is a constant, see if we can simplify it.
1080     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1081     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1082       return UpdateValueUsesWith(I, I);
1083     
1084     RHSKnownZero = KnownZeroOut;
1085     RHSKnownOne  = KnownOneOut;
1086     break;
1087   }
1088   case Instruction::Select:
1089     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1090                              RHSKnownZero, RHSKnownOne, Depth+1))
1091       return true;
1092     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1093                              LHSKnownZero, LHSKnownOne, Depth+1))
1094       return true;
1095     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1096            "Bits known to be one AND zero?"); 
1097     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1098            "Bits known to be one AND zero?"); 
1099     
1100     // If the operands are constants, see if we can simplify them.
1101     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1102       return UpdateValueUsesWith(I, I);
1103     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1104       return UpdateValueUsesWith(I, I);
1105     
1106     // Only known if known in both the LHS and RHS.
1107     RHSKnownOne &= LHSKnownOne;
1108     RHSKnownZero &= LHSKnownZero;
1109     break;
1110   case Instruction::Trunc: {
1111     uint32_t truncBf = 
1112       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1113     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.zext(truncBf),
1114         RHSKnownZero.zext(truncBf), RHSKnownOne.zext(truncBf), Depth+1))
1115       return true;
1116     DemandedMask.trunc(BitWidth);
1117     RHSKnownZero.trunc(BitWidth);
1118     RHSKnownOne.trunc(BitWidth);
1119     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1120            "Bits known to be one AND zero?"); 
1121     break;
1122   }
1123   case Instruction::BitCast:
1124     if (!I->getOperand(0)->getType()->isInteger())
1125       return false;
1126       
1127     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1128                              RHSKnownZero, RHSKnownOne, Depth+1))
1129       return true;
1130     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1131            "Bits known to be one AND zero?"); 
1132     break;
1133   case Instruction::ZExt: {
1134     // Compute the bits in the result that are not present in the input.
1135     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1136     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1137     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1138     
1139     DemandedMask &= SrcTy->getMask().zext(BitWidth);
1140     uint32_t zextBf = SrcTy->getBitWidth();
1141     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.trunc(zextBf),
1142           RHSKnownZero.trunc(zextBf), RHSKnownOne.trunc(zextBf), Depth+1))
1143       return true;
1144     DemandedMask.zext(BitWidth);
1145     RHSKnownZero.zext(BitWidth);
1146     RHSKnownOne.zext(BitWidth);
1147     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1148            "Bits known to be one AND zero?"); 
1149     // The top bits are known to be zero.
1150     RHSKnownZero |= NewBits;
1151     break;
1152   }
1153   case Instruction::SExt: {
1154     // Compute the bits in the result that are not present in the input.
1155     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1156     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1157     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1158     
1159     // Get the sign bit for the source type
1160     APInt InSignBit(APInt::getSignBit(SrcTy->getPrimitiveSizeInBits()));
1161     InSignBit.zext(BitWidth);
1162     APInt InputDemandedBits = DemandedMask & 
1163                               SrcTy->getMask().zext(BitWidth);
1164
1165     // If any of the sign extended bits are demanded, we know that the sign
1166     // bit is demanded.
1167     if ((NewBits & DemandedMask) != 0)
1168       InputDemandedBits |= InSignBit;
1169       
1170     uint32_t sextBf = SrcTy->getBitWidth();
1171     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits.trunc(sextBf),
1172           RHSKnownZero.trunc(sextBf), RHSKnownOne.trunc(sextBf), 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 & InSignBit) != 0 || (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 & InSignBit) != 0) {    // Input sign bit known set
1191       RHSKnownOne |= NewBits;
1192       RHSKnownZero &= ~NewBits;
1193     } else {                              // Input sign bit unknown
1194       RHSKnownZero &= ~NewBits;
1195       RHSKnownOne &= ~NewBits;
1196     }
1197     break;
1198   }
1199   case Instruction::Add: {
1200     // Figure out what the input bits are.  If the top bits of the and result
1201     // are not demanded, then the add doesn't demand them from its input
1202     // either.
1203     uint32_t NLZ = DemandedMask.countLeadingZeros();
1204       
1205     // If there is a constant on the RHS, there are a variety of xformations
1206     // we can do.
1207     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1208       // If null, this should be simplified elsewhere.  Some of the xforms here
1209       // won't work if the RHS is zero.
1210       if (RHS->isZero())
1211         break;
1212       
1213       // If the top bit of the output is demanded, demand everything from the
1214       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1215       APInt InDemandedBits(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1216
1217       // Find information about known zero/one bits in the input.
1218       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1219                                LHSKnownZero, LHSKnownOne, Depth+1))
1220         return true;
1221
1222       // If the RHS of the add has bits set that can't affect the input, reduce
1223       // the constant.
1224       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1225         return UpdateValueUsesWith(I, I);
1226       
1227       // Avoid excess work.
1228       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1229         break;
1230       
1231       // Turn it into OR if input bits are zero.
1232       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1233         Instruction *Or =
1234           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1235                                    I->getName());
1236         InsertNewInstBefore(Or, *I);
1237         return UpdateValueUsesWith(I, Or);
1238       }
1239       
1240       // We can say something about the output known-zero and known-one bits,
1241       // depending on potential carries from the input constant and the
1242       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1243       // bits set and the RHS constant is 0x01001, then we know we have a known
1244       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1245       
1246       // To compute this, we first compute the potential carry bits.  These are
1247       // the bits which may be modified.  I'm not aware of a better way to do
1248       // this scan.
1249       APInt RHSVal(RHS->getValue());
1250       
1251       bool CarryIn = false;
1252       APInt CarryBits(BitWidth, 0);
1253       const uint64_t *LHSKnownZeroRawVal = LHSKnownZero.getRawData(),
1254                      *RHSRawVal = RHSVal.getRawData();
1255       for (uint32_t i = 0; i != RHSVal.getNumWords(); ++i) {
1256         uint64_t AddVal = ~LHSKnownZeroRawVal[i] + RHSRawVal[i],
1257                  XorVal = ~LHSKnownZeroRawVal[i] ^ RHSRawVal[i];
1258         uint64_t WordCarryBits = AddVal ^ XorVal + CarryIn;
1259         if (AddVal < RHSRawVal[i])
1260           CarryIn = true;
1261         else
1262           CarryIn = false;
1263         CarryBits.setWordToValue(i, WordCarryBits);
1264       }
1265       
1266       // Now that we know which bits have carries, compute the known-1/0 sets.
1267       
1268       // Bits are known one if they are known zero in one operand and one in the
1269       // other, and there is no input carry.
1270       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1271                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1272       
1273       // Bits are known zero if they are known zero in both operands and there
1274       // is no input carry.
1275       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1276     } else {
1277       // If the high-bits of this ADD are not demanded, then it does not demand
1278       // the high bits of its LHS or RHS.
1279       if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1280         // Right fill the mask of bits for this ADD to demand the most
1281         // significant bit and all those below it.
1282         APInt DemandedFromOps = APInt::getAllOnesValue(BitWidth).lshr(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     }
1291     break;
1292   }
1293   case Instruction::Sub:
1294     // If the high-bits of this SUB are not demanded, then it does not demand
1295     // the high bits of its LHS or RHS.
1296     if ((DemandedMask & APInt::getSignBit(BitWidth)) == 0) {
1297       // Right fill the mask of bits for this SUB to demand the most
1298       // significant bit and all those below it.
1299       unsigned NLZ = DemandedMask.countLeadingZeros();
1300       APInt DemandedFromOps(APInt::getAllOnesValue(BitWidth).lshr(NLZ));
1301       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1302                                LHSKnownZero, LHSKnownOne, Depth+1))
1303         return true;
1304       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1305                                LHSKnownZero, LHSKnownOne, Depth+1))
1306         return true;
1307     }
1308     break;
1309   case Instruction::Shl:
1310     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1311       uint64_t ShiftAmt = SA->getZExtValue();
1312       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask.lshr(ShiftAmt), 
1313                                RHSKnownZero, RHSKnownOne, Depth+1))
1314         return true;
1315       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1316              "Bits known to be one AND zero?"); 
1317       RHSKnownZero <<= ShiftAmt;
1318       RHSKnownOne  <<= ShiftAmt;
1319       // low bits known zero.
1320       if (ShiftAmt)
1321         RHSKnownZero |= APInt::getAllOnesValue(ShiftAmt).zextOrCopy(BitWidth);
1322     }
1323     break;
1324   case Instruction::LShr:
1325     // For a logical shift right
1326     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1327       unsigned ShiftAmt = SA->getZExtValue();
1328       
1329       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
1330       // Unsigned shift right.
1331       if (SimplifyDemandedBits(I->getOperand(0),
1332                               (DemandedMask.shl(ShiftAmt)) & TypeMask,
1333                                RHSKnownZero, RHSKnownOne, Depth+1))
1334         return true;
1335       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1336              "Bits known to be one AND zero?"); 
1337       RHSKnownZero &= TypeMask;
1338       RHSKnownOne  &= TypeMask;
1339       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1340       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1341       if (ShiftAmt) {
1342         // Compute the new bits that are at the top now.
1343         APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(
1344                          BitWidth - ShiftAmt));
1345         RHSKnownZero |= HighBits;  // high bits known zero.
1346       }
1347     }
1348     break;
1349   case Instruction::AShr:
1350     // If this is an arithmetic shift right and only the low-bit is set, we can
1351     // always convert this into a logical shr, even if the shift amount is
1352     // variable.  The low bit of the shift cannot be an input sign bit unless
1353     // the shift amount is >= the size of the datatype, which is undefined.
1354     if (DemandedMask == 1) {
1355       // Perform the logical shift right.
1356       Value *NewVal = BinaryOperator::createLShr(
1357                         I->getOperand(0), I->getOperand(1), I->getName());
1358       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1359       return UpdateValueUsesWith(I, NewVal);
1360     }    
1361     
1362     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1363       unsigned ShiftAmt = SA->getZExtValue();
1364       
1365       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
1366       // Signed shift right.
1367       if (SimplifyDemandedBits(I->getOperand(0),
1368                                (DemandedMask.shl(ShiftAmt)) & TypeMask,
1369                                RHSKnownZero, RHSKnownOne, Depth+1))
1370         return true;
1371       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1372              "Bits known to be one AND zero?"); 
1373       // Compute the new bits that are at the top now.
1374       APInt HighBits(APInt::getAllOnesValue(BitWidth).shl(BitWidth - ShiftAmt));
1375       RHSKnownZero &= TypeMask;
1376       RHSKnownOne  &= TypeMask;
1377       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1378       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1379         
1380       // Handle the sign bits.
1381       APInt SignBit(APInt::getSignBit(BitWidth));
1382       // Adjust to where it is now in the mask.
1383       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1384         
1385       // If the input sign bit is known to be zero, or if none of the top bits
1386       // are demanded, turn this into an unsigned shift right.
1387       if ((RHSKnownZero & SignBit) != 0 || 
1388           (HighBits & ~DemandedMask) == HighBits) {
1389         // Perform the logical shift right.
1390         Value *NewVal = BinaryOperator::createLShr(
1391                           I->getOperand(0), SA, I->getName());
1392         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1393         return UpdateValueUsesWith(I, NewVal);
1394       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1395         RHSKnownOne |= HighBits;
1396       }
1397     }
1398     break;
1399   }
1400   
1401   // If the client is only demanding bits that we know, return the known
1402   // constant.
1403   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1404     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1405   return false;
1406 }
1407
1408
1409 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1410 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1411 /// actually used by the caller.  This method analyzes which elements of the
1412 /// operand are undef and returns that information in UndefElts.
1413 ///
1414 /// If the information about demanded elements can be used to simplify the
1415 /// operation, the operation is simplified, then the resultant value is
1416 /// returned.  This returns null if no change was made.
1417 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1418                                                 uint64_t &UndefElts,
1419                                                 unsigned Depth) {
1420   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1421   assert(VWidth <= 64 && "Vector too wide to analyze!");
1422   uint64_t EltMask = ~0ULL >> (64-VWidth);
1423   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1424          "Invalid DemandedElts!");
1425
1426   if (isa<UndefValue>(V)) {
1427     // If the entire vector is undefined, just return this info.
1428     UndefElts = EltMask;
1429     return 0;
1430   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1431     UndefElts = EltMask;
1432     return UndefValue::get(V->getType());
1433   }
1434   
1435   UndefElts = 0;
1436   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1437     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1438     Constant *Undef = UndefValue::get(EltTy);
1439
1440     std::vector<Constant*> Elts;
1441     for (unsigned i = 0; i != VWidth; ++i)
1442       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1443         Elts.push_back(Undef);
1444         UndefElts |= (1ULL << i);
1445       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1446         Elts.push_back(Undef);
1447         UndefElts |= (1ULL << i);
1448       } else {                               // Otherwise, defined.
1449         Elts.push_back(CP->getOperand(i));
1450       }
1451         
1452     // If we changed the constant, return it.
1453     Constant *NewCP = ConstantVector::get(Elts);
1454     return NewCP != CP ? NewCP : 0;
1455   } else if (isa<ConstantAggregateZero>(V)) {
1456     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1457     // set to undef.
1458     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1459     Constant *Zero = Constant::getNullValue(EltTy);
1460     Constant *Undef = UndefValue::get(EltTy);
1461     std::vector<Constant*> Elts;
1462     for (unsigned i = 0; i != VWidth; ++i)
1463       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1464     UndefElts = DemandedElts ^ EltMask;
1465     return ConstantVector::get(Elts);
1466   }
1467   
1468   if (!V->hasOneUse()) {    // Other users may use these bits.
1469     if (Depth != 0) {       // Not at the root.
1470       // TODO: Just compute the UndefElts information recursively.
1471       return false;
1472     }
1473     return false;
1474   } else if (Depth == 10) {        // Limit search depth.
1475     return false;
1476   }
1477   
1478   Instruction *I = dyn_cast<Instruction>(V);
1479   if (!I) return false;        // Only analyze instructions.
1480   
1481   bool MadeChange = false;
1482   uint64_t UndefElts2;
1483   Value *TmpV;
1484   switch (I->getOpcode()) {
1485   default: break;
1486     
1487   case Instruction::InsertElement: {
1488     // If this is a variable index, we don't know which element it overwrites.
1489     // demand exactly the same input as we produce.
1490     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1491     if (Idx == 0) {
1492       // Note that we can't propagate undef elt info, because we don't know
1493       // which elt is getting updated.
1494       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1495                                         UndefElts2, Depth+1);
1496       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1497       break;
1498     }
1499     
1500     // If this is inserting an element that isn't demanded, remove this
1501     // insertelement.
1502     unsigned IdxNo = Idx->getZExtValue();
1503     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1504       return AddSoonDeadInstToWorklist(*I, 0);
1505     
1506     // Otherwise, the element inserted overwrites whatever was there, so the
1507     // input demanded set is simpler than the output set.
1508     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1509                                       DemandedElts & ~(1ULL << IdxNo),
1510                                       UndefElts, Depth+1);
1511     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1512
1513     // The inserted element is defined.
1514     UndefElts |= 1ULL << IdxNo;
1515     break;
1516   }
1517     
1518   case Instruction::And:
1519   case Instruction::Or:
1520   case Instruction::Xor:
1521   case Instruction::Add:
1522   case Instruction::Sub:
1523   case Instruction::Mul:
1524     // div/rem demand all inputs, because they don't want divide by zero.
1525     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1526                                       UndefElts, Depth+1);
1527     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1528     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1529                                       UndefElts2, Depth+1);
1530     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1531       
1532     // Output elements are undefined if both are undefined.  Consider things
1533     // like undef&0.  The result is known zero, not undef.
1534     UndefElts &= UndefElts2;
1535     break;
1536     
1537   case Instruction::Call: {
1538     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1539     if (!II) break;
1540     switch (II->getIntrinsicID()) {
1541     default: break;
1542       
1543     // Binary vector operations that work column-wise.  A dest element is a
1544     // function of the corresponding input elements from the two inputs.
1545     case Intrinsic::x86_sse_sub_ss:
1546     case Intrinsic::x86_sse_mul_ss:
1547     case Intrinsic::x86_sse_min_ss:
1548     case Intrinsic::x86_sse_max_ss:
1549     case Intrinsic::x86_sse2_sub_sd:
1550     case Intrinsic::x86_sse2_mul_sd:
1551     case Intrinsic::x86_sse2_min_sd:
1552     case Intrinsic::x86_sse2_max_sd:
1553       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1554                                         UndefElts, Depth+1);
1555       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1556       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1557                                         UndefElts2, Depth+1);
1558       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1559
1560       // If only the low elt is demanded and this is a scalarizable intrinsic,
1561       // scalarize it now.
1562       if (DemandedElts == 1) {
1563         switch (II->getIntrinsicID()) {
1564         default: break;
1565         case Intrinsic::x86_sse_sub_ss:
1566         case Intrinsic::x86_sse_mul_ss:
1567         case Intrinsic::x86_sse2_sub_sd:
1568         case Intrinsic::x86_sse2_mul_sd:
1569           // TODO: Lower MIN/MAX/ABS/etc
1570           Value *LHS = II->getOperand(1);
1571           Value *RHS = II->getOperand(2);
1572           // Extract the element as scalars.
1573           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1574           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1575           
1576           switch (II->getIntrinsicID()) {
1577           default: assert(0 && "Case stmts out of sync!");
1578           case Intrinsic::x86_sse_sub_ss:
1579           case Intrinsic::x86_sse2_sub_sd:
1580             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1581                                                         II->getName()), *II);
1582             break;
1583           case Intrinsic::x86_sse_mul_ss:
1584           case Intrinsic::x86_sse2_mul_sd:
1585             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1586                                                          II->getName()), *II);
1587             break;
1588           }
1589           
1590           Instruction *New =
1591             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1592                                   II->getName());
1593           InsertNewInstBefore(New, *II);
1594           AddSoonDeadInstToWorklist(*II, 0);
1595           return New;
1596         }            
1597       }
1598         
1599       // Output elements are undefined if both are undefined.  Consider things
1600       // like undef&0.  The result is known zero, not undef.
1601       UndefElts &= UndefElts2;
1602       break;
1603     }
1604     break;
1605   }
1606   }
1607   return MadeChange ? I : 0;
1608 }
1609
1610 /// @returns true if the specified compare instruction is
1611 /// true when both operands are equal...
1612 /// @brief Determine if the ICmpInst returns true if both operands are equal
1613 static bool isTrueWhenEqual(ICmpInst &ICI) {
1614   ICmpInst::Predicate pred = ICI.getPredicate();
1615   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1616          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1617          pred == ICmpInst::ICMP_SLE;
1618 }
1619
1620 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1621 /// function is designed to check a chain of associative operators for a
1622 /// potential to apply a certain optimization.  Since the optimization may be
1623 /// applicable if the expression was reassociated, this checks the chain, then
1624 /// reassociates the expression as necessary to expose the optimization
1625 /// opportunity.  This makes use of a special Functor, which must define
1626 /// 'shouldApply' and 'apply' methods.
1627 ///
1628 template<typename Functor>
1629 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1630   unsigned Opcode = Root.getOpcode();
1631   Value *LHS = Root.getOperand(0);
1632
1633   // Quick check, see if the immediate LHS matches...
1634   if (F.shouldApply(LHS))
1635     return F.apply(Root);
1636
1637   // Otherwise, if the LHS is not of the same opcode as the root, return.
1638   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1639   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1640     // Should we apply this transform to the RHS?
1641     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1642
1643     // If not to the RHS, check to see if we should apply to the LHS...
1644     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1645       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1646       ShouldApply = true;
1647     }
1648
1649     // If the functor wants to apply the optimization to the RHS of LHSI,
1650     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1651     if (ShouldApply) {
1652       BasicBlock *BB = Root.getParent();
1653
1654       // Now all of the instructions are in the current basic block, go ahead
1655       // and perform the reassociation.
1656       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1657
1658       // First move the selected RHS to the LHS of the root...
1659       Root.setOperand(0, LHSI->getOperand(1));
1660
1661       // Make what used to be the LHS of the root be the user of the root...
1662       Value *ExtraOperand = TmpLHSI->getOperand(1);
1663       if (&Root == TmpLHSI) {
1664         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1665         return 0;
1666       }
1667       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1668       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1669       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1670       BasicBlock::iterator ARI = &Root; ++ARI;
1671       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1672       ARI = Root;
1673
1674       // Now propagate the ExtraOperand down the chain of instructions until we
1675       // get to LHSI.
1676       while (TmpLHSI != LHSI) {
1677         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1678         // Move the instruction to immediately before the chain we are
1679         // constructing to avoid breaking dominance properties.
1680         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1681         BB->getInstList().insert(ARI, NextLHSI);
1682         ARI = NextLHSI;
1683
1684         Value *NextOp = NextLHSI->getOperand(1);
1685         NextLHSI->setOperand(1, ExtraOperand);
1686         TmpLHSI = NextLHSI;
1687         ExtraOperand = NextOp;
1688       }
1689
1690       // Now that the instructions are reassociated, have the functor perform
1691       // the transformation...
1692       return F.apply(Root);
1693     }
1694
1695     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1696   }
1697   return 0;
1698 }
1699
1700
1701 // AddRHS - Implements: X + X --> X << 1
1702 struct AddRHS {
1703   Value *RHS;
1704   AddRHS(Value *rhs) : RHS(rhs) {}
1705   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1706   Instruction *apply(BinaryOperator &Add) const {
1707     return BinaryOperator::createShl(Add.getOperand(0),
1708                                   ConstantInt::get(Add.getType(), 1));
1709   }
1710 };
1711
1712 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1713 //                 iff C1&C2 == 0
1714 struct AddMaskingAnd {
1715   Constant *C2;
1716   AddMaskingAnd(Constant *c) : C2(c) {}
1717   bool shouldApply(Value *LHS) const {
1718     ConstantInt *C1;
1719     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1720            ConstantExpr::getAnd(C1, C2)->isNullValue();
1721   }
1722   Instruction *apply(BinaryOperator &Add) const {
1723     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1724   }
1725 };
1726
1727 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1728                                              InstCombiner *IC) {
1729   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1730     if (Constant *SOC = dyn_cast<Constant>(SO))
1731       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1732
1733     return IC->InsertNewInstBefore(CastInst::create(
1734           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1735   }
1736
1737   // Figure out if the constant is the left or the right argument.
1738   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1739   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1740
1741   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1742     if (ConstIsRHS)
1743       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1744     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1745   }
1746
1747   Value *Op0 = SO, *Op1 = ConstOperand;
1748   if (!ConstIsRHS)
1749     std::swap(Op0, Op1);
1750   Instruction *New;
1751   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1752     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1753   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1754     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1755                           SO->getName()+".cmp");
1756   else {
1757     assert(0 && "Unknown binary instruction type!");
1758     abort();
1759   }
1760   return IC->InsertNewInstBefore(New, I);
1761 }
1762
1763 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1764 // constant as the other operand, try to fold the binary operator into the
1765 // select arguments.  This also works for Cast instructions, which obviously do
1766 // not have a second operand.
1767 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1768                                      InstCombiner *IC) {
1769   // Don't modify shared select instructions
1770   if (!SI->hasOneUse()) return 0;
1771   Value *TV = SI->getOperand(1);
1772   Value *FV = SI->getOperand(2);
1773
1774   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1775     // Bool selects with constant operands can be folded to logical ops.
1776     if (SI->getType() == Type::Int1Ty) return 0;
1777
1778     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1779     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1780
1781     return new SelectInst(SI->getCondition(), SelectTrueVal,
1782                           SelectFalseVal);
1783   }
1784   return 0;
1785 }
1786
1787
1788 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1789 /// node as operand #0, see if we can fold the instruction into the PHI (which
1790 /// is only possible if all operands to the PHI are constants).
1791 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1792   PHINode *PN = cast<PHINode>(I.getOperand(0));
1793   unsigned NumPHIValues = PN->getNumIncomingValues();
1794   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1795
1796   // Check to see if all of the operands of the PHI are constants.  If there is
1797   // one non-constant value, remember the BB it is.  If there is more than one
1798   // or if *it* is a PHI, bail out.
1799   BasicBlock *NonConstBB = 0;
1800   for (unsigned i = 0; i != NumPHIValues; ++i)
1801     if (!isa<Constant>(PN->getIncomingValue(i))) {
1802       if (NonConstBB) return 0;  // More than one non-const value.
1803       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1804       NonConstBB = PN->getIncomingBlock(i);
1805       
1806       // If the incoming non-constant value is in I's block, we have an infinite
1807       // loop.
1808       if (NonConstBB == I.getParent())
1809         return 0;
1810     }
1811   
1812   // If there is exactly one non-constant value, we can insert a copy of the
1813   // operation in that block.  However, if this is a critical edge, we would be
1814   // inserting the computation one some other paths (e.g. inside a loop).  Only
1815   // do this if the pred block is unconditionally branching into the phi block.
1816   if (NonConstBB) {
1817     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1818     if (!BI || !BI->isUnconditional()) return 0;
1819   }
1820
1821   // Okay, we can do the transformation: create the new PHI node.
1822   PHINode *NewPN = new PHINode(I.getType(), "");
1823   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1824   InsertNewInstBefore(NewPN, *PN);
1825   NewPN->takeName(PN);
1826
1827   // Next, add all of the operands to the PHI.
1828   if (I.getNumOperands() == 2) {
1829     Constant *C = cast<Constant>(I.getOperand(1));
1830     for (unsigned i = 0; i != NumPHIValues; ++i) {
1831       Value *InV;
1832       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1833         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1834           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1835         else
1836           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1837       } else {
1838         assert(PN->getIncomingBlock(i) == NonConstBB);
1839         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1840           InV = BinaryOperator::create(BO->getOpcode(),
1841                                        PN->getIncomingValue(i), C, "phitmp",
1842                                        NonConstBB->getTerminator());
1843         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1844           InV = CmpInst::create(CI->getOpcode(), 
1845                                 CI->getPredicate(),
1846                                 PN->getIncomingValue(i), C, "phitmp",
1847                                 NonConstBB->getTerminator());
1848         else
1849           assert(0 && "Unknown binop!");
1850         
1851         AddToWorkList(cast<Instruction>(InV));
1852       }
1853       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1854     }
1855   } else { 
1856     CastInst *CI = cast<CastInst>(&I);
1857     const Type *RetTy = CI->getType();
1858     for (unsigned i = 0; i != NumPHIValues; ++i) {
1859       Value *InV;
1860       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1861         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1862       } else {
1863         assert(PN->getIncomingBlock(i) == NonConstBB);
1864         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1865                                I.getType(), "phitmp", 
1866                                NonConstBB->getTerminator());
1867         AddToWorkList(cast<Instruction>(InV));
1868       }
1869       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1870     }
1871   }
1872   return ReplaceInstUsesWith(I, NewPN);
1873 }
1874
1875 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1876   bool Changed = SimplifyCommutative(I);
1877   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1878
1879   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1880     // X + undef -> undef
1881     if (isa<UndefValue>(RHS))
1882       return ReplaceInstUsesWith(I, RHS);
1883
1884     // X + 0 --> X
1885     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1886       if (RHSC->isNullValue())
1887         return ReplaceInstUsesWith(I, LHS);
1888     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1889       if (CFP->isExactlyValue(-0.0))
1890         return ReplaceInstUsesWith(I, LHS);
1891     }
1892
1893     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1894       // X + (signbit) --> X ^ signbit
1895       APInt Val(CI->getValue());
1896       unsigned BitWidth = Val.getBitWidth();
1897       if (Val == APInt::getSignBit(BitWidth))
1898         return BinaryOperator::createXor(LHS, RHS);
1899       
1900       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1901       // (X & 254)+1 -> (X&254)|1
1902       if (!isa<VectorType>(I.getType())) {
1903         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1904         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1905                                  KnownZero, KnownOne))
1906           return &I;
1907       }
1908     }
1909
1910     if (isa<PHINode>(LHS))
1911       if (Instruction *NV = FoldOpIntoPhi(I))
1912         return NV;
1913     
1914     ConstantInt *XorRHS = 0;
1915     Value *XorLHS = 0;
1916     if (isa<ConstantInt>(RHSC) &&
1917         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1918       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1919       APInt RHSVal(cast<ConstantInt>(RHSC)->getValue());
1920       
1921       unsigned Size = TySizeBits / 2;
1922       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1923       APInt CFF80Val(-C0080Val);
1924       do {
1925         if (TySizeBits > Size) {
1926           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1927           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1928           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1929               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1930             // This is a sign extend if the top bits are known zero.
1931             APInt Mask(APInt::getAllOnesValue(TySizeBits));
1932             Mask <<= Size;
1933             if (!MaskedValueIsZero(XorLHS, Mask))
1934               Size = 0;  // Not a sign ext, but can't be any others either.
1935             break;
1936           }
1937         }
1938         Size >>= 1;
1939         C0080Val = APIntOps::lshr(C0080Val, Size);
1940         CFF80Val = APIntOps::ashr(CFF80Val, Size);
1941       } while (Size >= 1);
1942       
1943       if (Size) {
1944         const Type *MiddleType = IntegerType::get(Size);
1945         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1946         InsertNewInstBefore(NewTrunc, I);
1947         return new SExtInst(NewTrunc, I.getType());
1948       }
1949     }
1950   }
1951
1952   // X + X --> X << 1
1953   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
1954     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1955
1956     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1957       if (RHSI->getOpcode() == Instruction::Sub)
1958         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1959           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1960     }
1961     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1962       if (LHSI->getOpcode() == Instruction::Sub)
1963         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1964           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1965     }
1966   }
1967
1968   // -A + B  -->  B - A
1969   if (Value *V = dyn_castNegVal(LHS))
1970     return BinaryOperator::createSub(RHS, V);
1971
1972   // A + -B  -->  A - B
1973   if (!isa<Constant>(RHS))
1974     if (Value *V = dyn_castNegVal(RHS))
1975       return BinaryOperator::createSub(LHS, V);
1976
1977
1978   ConstantInt *C2;
1979   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1980     if (X == RHS)   // X*C + X --> X * (C+1)
1981       return BinaryOperator::createMul(RHS, AddOne(C2));
1982
1983     // X*C1 + X*C2 --> X * (C1+C2)
1984     ConstantInt *C1;
1985     if (X == dyn_castFoldableMul(RHS, C1))
1986       return BinaryOperator::createMul(X, Add(C1, C2));
1987   }
1988
1989   // X + X*C --> X * (C+1)
1990   if (dyn_castFoldableMul(RHS, C2) == LHS)
1991     return BinaryOperator::createMul(LHS, AddOne(C2));
1992
1993   // X + ~X --> -1   since   ~X = -X-1
1994   if (dyn_castNotVal(LHS) == RHS ||
1995       dyn_castNotVal(RHS) == LHS)
1996     return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1997   
1998
1999   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2000   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2001     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2002       return R;
2003
2004   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2005     Value *X = 0;
2006     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2007       return BinaryOperator::createSub(SubOne(CRHS), X);
2008
2009     // (X & FF00) + xx00  -> (X+xx00) & FF00
2010     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2011       Constant *Anded = And(CRHS, C2);
2012       if (Anded == CRHS) {
2013         // See if all bits from the first bit set in the Add RHS up are included
2014         // in the mask.  First, get the rightmost bit.
2015         APInt AddRHSV(CRHS->getValue());
2016
2017         // Form a mask of all bits from the lowest bit added through the top.
2018         APInt AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
2019         AddRHSHighBits &= C2->getType()->getMask();
2020
2021         // See if the and mask includes all of these bits.
2022         APInt AddRHSHighBitsAnd = AddRHSHighBits & C2->getValue();
2023
2024         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2025           // Okay, the xform is safe.  Insert the new add pronto.
2026           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2027                                                             LHS->getName()), I);
2028           return BinaryOperator::createAnd(NewAdd, C2);
2029         }
2030       }
2031     }
2032
2033     // Try to fold constant add into select arguments.
2034     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2035       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2036         return R;
2037   }
2038
2039   // add (cast *A to intptrtype) B -> 
2040   //   cast (GEP (cast *A to sbyte*) B) -> 
2041   //     intptrtype
2042   {
2043     CastInst *CI = dyn_cast<CastInst>(LHS);
2044     Value *Other = RHS;
2045     if (!CI) {
2046       CI = dyn_cast<CastInst>(RHS);
2047       Other = LHS;
2048     }
2049     if (CI && CI->getType()->isSized() && 
2050         (CI->getType()->getPrimitiveSizeInBits() == 
2051          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2052         && isa<PointerType>(CI->getOperand(0)->getType())) {
2053       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
2054                                    PointerType::get(Type::Int8Ty), I);
2055       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2056       return new PtrToIntInst(I2, CI->getType());
2057     }
2058   }
2059
2060   return Changed ? &I : 0;
2061 }
2062
2063 // isSignBit - Return true if the value represented by the constant only has the
2064 // highest order bit set.
2065 static bool isSignBit(ConstantInt *CI) {
2066   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
2067   return CI->getValue() == APInt::getSignBit(NumBits);
2068 }
2069
2070 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2071   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2072
2073   if (Op0 == Op1)         // sub X, X  -> 0
2074     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2075
2076   // If this is a 'B = x-(-A)', change to B = x+A...
2077   if (Value *V = dyn_castNegVal(Op1))
2078     return BinaryOperator::createAdd(Op0, V);
2079
2080   if (isa<UndefValue>(Op0))
2081     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2082   if (isa<UndefValue>(Op1))
2083     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2084
2085   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2086     // Replace (-1 - A) with (~A)...
2087     if (C->isAllOnesValue())
2088       return BinaryOperator::createNot(Op1);
2089
2090     // C - ~X == X + (1+C)
2091     Value *X = 0;
2092     if (match(Op1, m_Not(m_Value(X))))
2093       return BinaryOperator::createAdd(X, AddOne(C));
2094
2095     // -(X >>u 31) -> (X >>s 31)
2096     // -(X >>s 31) -> (X >>u 31)
2097     if (C->isNullValue()) {
2098       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2099         if (SI->getOpcode() == Instruction::LShr) {
2100           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2101             // Check to see if we are shifting out everything but the sign bit.
2102             if (CU->getZExtValue() == 
2103                 SI->getType()->getPrimitiveSizeInBits()-1) {
2104               // Ok, the transformation is safe.  Insert AShr.
2105               return BinaryOperator::create(Instruction::AShr, 
2106                                           SI->getOperand(0), CU, SI->getName());
2107             }
2108           }
2109         }
2110         else if (SI->getOpcode() == Instruction::AShr) {
2111           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2112             // Check to see if we are shifting out everything but the sign bit.
2113             if (CU->getZExtValue() == 
2114                 SI->getType()->getPrimitiveSizeInBits()-1) {
2115               // Ok, the transformation is safe.  Insert LShr. 
2116               return BinaryOperator::createLShr(
2117                                           SI->getOperand(0), CU, SI->getName());
2118             }
2119           }
2120         } 
2121     }
2122
2123     // Try to fold constant sub into select arguments.
2124     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2125       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2126         return R;
2127
2128     if (isa<PHINode>(Op0))
2129       if (Instruction *NV = FoldOpIntoPhi(I))
2130         return NV;
2131   }
2132
2133   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2134     if (Op1I->getOpcode() == Instruction::Add &&
2135         !Op0->getType()->isFPOrFPVector()) {
2136       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2137         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2138       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2139         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2140       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2141         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2142           // C1-(X+C2) --> (C1-C2)-X
2143           return BinaryOperator::createSub(Subtract(CI1, CI2), 
2144                                            Op1I->getOperand(0));
2145       }
2146     }
2147
2148     if (Op1I->hasOneUse()) {
2149       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2150       // is not used by anyone else...
2151       //
2152       if (Op1I->getOpcode() == Instruction::Sub &&
2153           !Op1I->getType()->isFPOrFPVector()) {
2154         // Swap the two operands of the subexpr...
2155         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2156         Op1I->setOperand(0, IIOp1);
2157         Op1I->setOperand(1, IIOp0);
2158
2159         // Create the new top level add instruction...
2160         return BinaryOperator::createAdd(Op0, Op1);
2161       }
2162
2163       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2164       //
2165       if (Op1I->getOpcode() == Instruction::And &&
2166           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2167         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2168
2169         Value *NewNot =
2170           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2171         return BinaryOperator::createAnd(Op0, NewNot);
2172       }
2173
2174       // 0 - (X sdiv C)  -> (X sdiv -C)
2175       if (Op1I->getOpcode() == Instruction::SDiv)
2176         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2177           if (CSI->isNullValue())
2178             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2179               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2180                                                ConstantExpr::getNeg(DivRHS));
2181
2182       // X - X*C --> X * (1-C)
2183       ConstantInt *C2 = 0;
2184       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2185         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2186         return BinaryOperator::createMul(Op0, CP1);
2187       }
2188     }
2189   }
2190
2191   if (!Op0->getType()->isFPOrFPVector())
2192     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2193       if (Op0I->getOpcode() == Instruction::Add) {
2194         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2195           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2196         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2197           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2198       } else if (Op0I->getOpcode() == Instruction::Sub) {
2199         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2200           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2201       }
2202
2203   ConstantInt *C1;
2204   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2205     if (X == Op1)  // X*C - X --> X * (C-1)
2206       return BinaryOperator::createMul(Op1, SubOne(C1));
2207
2208     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2209     if (X == dyn_castFoldableMul(Op1, C2))
2210       return BinaryOperator::createMul(Op1, Subtract(C1, C2));
2211   }
2212   return 0;
2213 }
2214
2215 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2216 /// really just returns true if the most significant (sign) bit is set.
2217 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2218   switch (pred) {
2219     case ICmpInst::ICMP_SLT: 
2220       // True if LHS s< RHS and RHS == 0
2221       return RHS->isNullValue();
2222     case ICmpInst::ICMP_SLE: 
2223       // True if LHS s<= RHS and RHS == -1
2224       return RHS->isAllOnesValue();
2225     case ICmpInst::ICMP_UGE: 
2226       // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2227       return RHS->getValue() == 
2228              APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2229     case ICmpInst::ICMP_UGT:
2230       // True if LHS u> RHS and RHS == high-bit-mask - 1
2231       return RHS->getValue() ==
2232              APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2233     default:
2234       return false;
2235   }
2236 }
2237
2238 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2239   bool Changed = SimplifyCommutative(I);
2240   Value *Op0 = I.getOperand(0);
2241
2242   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2243     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2244
2245   // Simplify mul instructions with a constant RHS...
2246   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2247     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2248
2249       // ((X << C1)*C2) == (X * (C2 << C1))
2250       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2251         if (SI->getOpcode() == Instruction::Shl)
2252           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2253             return BinaryOperator::createMul(SI->getOperand(0),
2254                                              ConstantExpr::getShl(CI, ShOp));
2255
2256       if (CI->isNullValue())
2257         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2258       if (CI->equalsInt(1))                  // X * 1  == X
2259         return ReplaceInstUsesWith(I, Op0);
2260       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2261         return BinaryOperator::createNeg(Op0, I.getName());
2262
2263       APInt Val(cast<ConstantInt>(CI)->getValue());
2264       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2265         return BinaryOperator::createShl(Op0,
2266                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2267       }
2268     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2269       if (Op1F->isNullValue())
2270         return ReplaceInstUsesWith(I, Op1);
2271
2272       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2273       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2274       if (Op1F->getValue() == 1.0)
2275         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2276     }
2277     
2278     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2279       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2280           isa<ConstantInt>(Op0I->getOperand(1))) {
2281         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2282         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2283                                                      Op1, "tmp");
2284         InsertNewInstBefore(Add, I);
2285         Value *C1C2 = ConstantExpr::getMul(Op1, 
2286                                            cast<Constant>(Op0I->getOperand(1)));
2287         return BinaryOperator::createAdd(Add, C1C2);
2288         
2289       }
2290
2291     // Try to fold constant mul into select arguments.
2292     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2293       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2294         return R;
2295
2296     if (isa<PHINode>(Op0))
2297       if (Instruction *NV = FoldOpIntoPhi(I))
2298         return NV;
2299   }
2300
2301   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2302     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2303       return BinaryOperator::createMul(Op0v, Op1v);
2304
2305   // If one of the operands of the multiply is a cast from a boolean value, then
2306   // we know the bool is either zero or one, so this is a 'masking' multiply.
2307   // See if we can simplify things based on how the boolean was originally
2308   // formed.
2309   CastInst *BoolCast = 0;
2310   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2311     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2312       BoolCast = CI;
2313   if (!BoolCast)
2314     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2315       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2316         BoolCast = CI;
2317   if (BoolCast) {
2318     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2319       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2320       const Type *SCOpTy = SCIOp0->getType();
2321
2322       // If the icmp is true iff the sign bit of X is set, then convert this
2323       // multiply into a shift/and combination.
2324       if (isa<ConstantInt>(SCIOp1) &&
2325           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
2326         // Shift the X value right to turn it into "all signbits".
2327         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2328                                           SCOpTy->getPrimitiveSizeInBits()-1);
2329         Value *V =
2330           InsertNewInstBefore(
2331             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2332                                             BoolCast->getOperand(0)->getName()+
2333                                             ".mask"), I);
2334
2335         // If the multiply type is not the same as the source type, sign extend
2336         // or truncate to the multiply type.
2337         if (I.getType() != V->getType()) {
2338           unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2339           unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2340           Instruction::CastOps opcode = 
2341             (SrcBits == DstBits ? Instruction::BitCast : 
2342              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2343           V = InsertCastBefore(opcode, V, I.getType(), I);
2344         }
2345
2346         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2347         return BinaryOperator::createAnd(V, OtherOp);
2348       }
2349     }
2350   }
2351
2352   return Changed ? &I : 0;
2353 }
2354
2355 /// This function implements the transforms on div instructions that work
2356 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2357 /// used by the visitors to those instructions.
2358 /// @brief Transforms common to all three div instructions
2359 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2360   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2361
2362   // undef / X -> 0
2363   if (isa<UndefValue>(Op0))
2364     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2365
2366   // X / undef -> undef
2367   if (isa<UndefValue>(Op1))
2368     return ReplaceInstUsesWith(I, Op1);
2369
2370   // Handle cases involving: div X, (select Cond, Y, Z)
2371   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2372     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2373     // same basic block, then we replace the select with Y, and the condition 
2374     // of the select with false (if the cond value is in the same BB).  If the
2375     // select has uses other than the div, this allows them to be simplified
2376     // also. Note that div X, Y is just as good as div X, 0 (undef)
2377     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2378       if (ST->isNullValue()) {
2379         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2380         if (CondI && CondI->getParent() == I.getParent())
2381           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2382         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2383           I.setOperand(1, SI->getOperand(2));
2384         else
2385           UpdateValueUsesWith(SI, SI->getOperand(2));
2386         return &I;
2387       }
2388
2389     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2390     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2391       if (ST->isNullValue()) {
2392         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2393         if (CondI && CondI->getParent() == I.getParent())
2394           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2395         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2396           I.setOperand(1, SI->getOperand(1));
2397         else
2398           UpdateValueUsesWith(SI, SI->getOperand(1));
2399         return &I;
2400       }
2401   }
2402
2403   return 0;
2404 }
2405
2406 /// This function implements the transforms common to both integer division
2407 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2408 /// division instructions.
2409 /// @brief Common integer divide transforms
2410 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2411   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2412
2413   if (Instruction *Common = commonDivTransforms(I))
2414     return Common;
2415
2416   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2417     // div X, 1 == X
2418     if (RHS->equalsInt(1))
2419       return ReplaceInstUsesWith(I, Op0);
2420
2421     // (X / C1) / C2  -> X / (C1*C2)
2422     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2423       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2424         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2425           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2426                                         Multiply(RHS, LHSRHS));
2427         }
2428
2429     if (!RHS->isZero()) { // avoid X udiv 0
2430       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2431         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2432           return R;
2433       if (isa<PHINode>(Op0))
2434         if (Instruction *NV = FoldOpIntoPhi(I))
2435           return NV;
2436     }
2437   }
2438
2439   // 0 / X == 0, we don't need to preserve faults!
2440   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2441     if (LHS->equalsInt(0))
2442       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2443
2444   return 0;
2445 }
2446
2447 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2448   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2449
2450   // Handle the integer div common cases
2451   if (Instruction *Common = commonIDivTransforms(I))
2452     return Common;
2453
2454   // X udiv C^2 -> X >> C
2455   // Check to see if this is an unsigned division with an exact power of 2,
2456   // if so, convert to a right shift.
2457   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2458     if (!C->isZero() && C->getValue().isPowerOf2())  // Don't break X / 0
2459       return BinaryOperator::createLShr(Op0, 
2460                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2461   }
2462
2463   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2464   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2465     if (RHSI->getOpcode() == Instruction::Shl &&
2466         isa<ConstantInt>(RHSI->getOperand(0))) {
2467       APInt C1(cast<ConstantInt>(RHSI->getOperand(0))->getValue());
2468       if (C1.isPowerOf2()) {
2469         Value *N = RHSI->getOperand(1);
2470         const Type *NTy = N->getType();
2471         if (uint32_t C2 = C1.logBase2()) {
2472           Constant *C2V = ConstantInt::get(NTy, C2);
2473           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2474         }
2475         return BinaryOperator::createLShr(Op0, N);
2476       }
2477     }
2478   }
2479   
2480   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2481   // where C1&C2 are powers of two.
2482   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2483     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2484       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2485         APInt TVA(STO->getValue()), FVA(SFO->getValue());
2486         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2487           // Compute the shift amounts
2488           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2489           // Construct the "on true" case of the select
2490           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2491           Instruction *TSI = BinaryOperator::createLShr(
2492                                                  Op0, TC, SI->getName()+".t");
2493           TSI = InsertNewInstBefore(TSI, I);
2494   
2495           // Construct the "on false" case of the select
2496           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2497           Instruction *FSI = BinaryOperator::createLShr(
2498                                                  Op0, FC, SI->getName()+".f");
2499           FSI = InsertNewInstBefore(FSI, I);
2500
2501           // construct the select instruction and return it.
2502           return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2503         }
2504       }
2505   return 0;
2506 }
2507
2508 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2509   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2510
2511   // Handle the integer div common cases
2512   if (Instruction *Common = commonIDivTransforms(I))
2513     return Common;
2514
2515   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2516     // sdiv X, -1 == -X
2517     if (RHS->isAllOnesValue())
2518       return BinaryOperator::createNeg(Op0);
2519
2520     // -X/C -> X/-C
2521     if (Value *LHSNeg = dyn_castNegVal(Op0))
2522       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2523   }
2524
2525   // If the sign bits of both operands are zero (i.e. we can prove they are
2526   // unsigned inputs), turn this into a udiv.
2527   if (I.getType()->isInteger()) {
2528     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2529     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2530       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2531     }
2532   }      
2533   
2534   return 0;
2535 }
2536
2537 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2538   return commonDivTransforms(I);
2539 }
2540
2541 /// GetFactor - If we can prove that the specified value is at least a multiple
2542 /// of some factor, return that factor.
2543 static Constant *GetFactor(Value *V) {
2544   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2545     return CI;
2546   
2547   // Unless we can be tricky, we know this is a multiple of 1.
2548   Constant *Result = ConstantInt::get(V->getType(), 1);
2549   
2550   Instruction *I = dyn_cast<Instruction>(V);
2551   if (!I) return Result;
2552   
2553   if (I->getOpcode() == Instruction::Mul) {
2554     // Handle multiplies by a constant, etc.
2555     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2556                                 GetFactor(I->getOperand(1)));
2557   } else if (I->getOpcode() == Instruction::Shl) {
2558     // (X<<C) -> X * (1 << C)
2559     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2560       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2561       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2562     }
2563   } else if (I->getOpcode() == Instruction::And) {
2564     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2565       // X & 0xFFF0 is known to be a multiple of 16.
2566       uint32_t Zeros = RHS->getValue().countTrailingZeros();
2567       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2568         return ConstantExpr::getShl(Result, 
2569                                     ConstantInt::get(Result->getType(), Zeros));
2570     }
2571   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2572     // Only handle int->int casts.
2573     if (!CI->isIntegerCast())
2574       return Result;
2575     Value *Op = CI->getOperand(0);
2576     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2577   }    
2578   return Result;
2579 }
2580
2581 /// This function implements the transforms on rem instructions that work
2582 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2583 /// is used by the visitors to those instructions.
2584 /// @brief Transforms common to all three rem instructions
2585 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2586   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2587
2588   // 0 % X == 0, we don't need to preserve faults!
2589   if (Constant *LHS = dyn_cast<Constant>(Op0))
2590     if (LHS->isNullValue())
2591       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2592
2593   if (isa<UndefValue>(Op0))              // undef % X -> 0
2594     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2595   if (isa<UndefValue>(Op1))
2596     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2597
2598   // Handle cases involving: rem X, (select Cond, Y, Z)
2599   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2600     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2601     // the same basic block, then we replace the select with Y, and the
2602     // condition of the select with false (if the cond value is in the same
2603     // BB).  If the select has uses other than the div, this allows them to be
2604     // simplified also.
2605     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2606       if (ST->isNullValue()) {
2607         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2608         if (CondI && CondI->getParent() == I.getParent())
2609           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2610         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2611           I.setOperand(1, SI->getOperand(2));
2612         else
2613           UpdateValueUsesWith(SI, SI->getOperand(2));
2614         return &I;
2615       }
2616     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2617     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2618       if (ST->isNullValue()) {
2619         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2620         if (CondI && CondI->getParent() == I.getParent())
2621           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2622         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2623           I.setOperand(1, SI->getOperand(1));
2624         else
2625           UpdateValueUsesWith(SI, SI->getOperand(1));
2626         return &I;
2627       }
2628   }
2629
2630   return 0;
2631 }
2632
2633 /// This function implements the transforms common to both integer remainder
2634 /// instructions (urem and srem). It is called by the visitors to those integer
2635 /// remainder instructions.
2636 /// @brief Common integer remainder transforms
2637 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2638   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2639
2640   if (Instruction *common = commonRemTransforms(I))
2641     return common;
2642
2643   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2644     // X % 0 == undef, we don't need to preserve faults!
2645     if (RHS->equalsInt(0))
2646       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2647     
2648     if (RHS->equalsInt(1))  // X % 1 == 0
2649       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2650
2651     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2652       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2653         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2654           return R;
2655       } else if (isa<PHINode>(Op0I)) {
2656         if (Instruction *NV = FoldOpIntoPhi(I))
2657           return NV;
2658       }
2659       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2660       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2661         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2662     }
2663   }
2664
2665   return 0;
2666 }
2667
2668 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2669   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2670
2671   if (Instruction *common = commonIRemTransforms(I))
2672     return common;
2673   
2674   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2675     // X urem C^2 -> X and C
2676     // Check to see if this is an unsigned remainder with an exact power of 2,
2677     // if so, convert to a bitwise and.
2678     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2679       if (C->getValue().isPowerOf2())
2680         return BinaryOperator::createAnd(Op0, SubOne(C));
2681   }
2682
2683   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2684     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2685     if (RHSI->getOpcode() == Instruction::Shl &&
2686         isa<ConstantInt>(RHSI->getOperand(0))) {
2687       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2688         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2689         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2690                                                                    "tmp"), I);
2691         return BinaryOperator::createAnd(Op0, Add);
2692       }
2693     }
2694   }
2695
2696   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2697   // where C1&C2 are powers of two.
2698   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2699     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2700       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2701         // STO == 0 and SFO == 0 handled above.
2702         if ((STO->getValue().isPowerOf2()) && 
2703             (SFO->getValue().isPowerOf2())) {
2704           Value *TrueAnd = InsertNewInstBefore(
2705             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2706           Value *FalseAnd = InsertNewInstBefore(
2707             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2708           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2709         }
2710       }
2711   }
2712   
2713   return 0;
2714 }
2715
2716 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2717   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2718
2719   if (Instruction *common = commonIRemTransforms(I))
2720     return common;
2721   
2722   if (Value *RHSNeg = dyn_castNegVal(Op1))
2723     if (!isa<ConstantInt>(RHSNeg) || 
2724         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2725       // X % -Y -> X % Y
2726       AddUsesToWorkList(I);
2727       I.setOperand(1, RHSNeg);
2728       return &I;
2729     }
2730  
2731   // If the top bits of both operands are zero (i.e. we can prove they are
2732   // unsigned inputs), turn this into a urem.
2733   APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2734   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2735     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2736     return BinaryOperator::createURem(Op0, Op1, I.getName());
2737   }
2738
2739   return 0;
2740 }
2741
2742 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2743   return commonRemTransforms(I);
2744 }
2745
2746 // isMaxValueMinusOne - return true if this is Max-1
2747 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2748   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2749   if (isSigned) {
2750     // Calculate 0111111111..11111
2751     APInt Val(APInt::getSignedMaxValue(TypeBits));
2752     return C->getValue() == Val-1;
2753   }
2754   return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2755 }
2756
2757 // isMinValuePlusOne - return true if this is Min+1
2758 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2759   if (isSigned) {
2760     // Calculate 1111111111000000000000
2761     uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2762     APInt Val(APInt::getSignedMinValue(TypeBits));
2763     return C->getValue() == Val+1;
2764   }
2765   return C->getValue() == 1; // unsigned
2766 }
2767
2768 // isOneBitSet - Return true if there is exactly one bit set in the specified
2769 // constant.
2770 static bool isOneBitSet(const ConstantInt *CI) {
2771   return CI->getValue().isPowerOf2();
2772 }
2773
2774 // isHighOnes - Return true if the constant is of the form 1+0+.
2775 // This is the same as lowones(~X).
2776 static bool isHighOnes(const ConstantInt *CI) {
2777   return (~CI->getValue() + 1).isPowerOf2();
2778 }
2779
2780 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2781 /// are carefully arranged to allow folding of expressions such as:
2782 ///
2783 ///      (A < B) | (A > B) --> (A != B)
2784 ///
2785 /// Note that this is only valid if the first and second predicates have the
2786 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2787 ///
2788 /// Three bits are used to represent the condition, as follows:
2789 ///   0  A > B
2790 ///   1  A == B
2791 ///   2  A < B
2792 ///
2793 /// <=>  Value  Definition
2794 /// 000     0   Always false
2795 /// 001     1   A >  B
2796 /// 010     2   A == B
2797 /// 011     3   A >= B
2798 /// 100     4   A <  B
2799 /// 101     5   A != B
2800 /// 110     6   A <= B
2801 /// 111     7   Always true
2802 ///  
2803 static unsigned getICmpCode(const ICmpInst *ICI) {
2804   switch (ICI->getPredicate()) {
2805     // False -> 0
2806   case ICmpInst::ICMP_UGT: return 1;  // 001
2807   case ICmpInst::ICMP_SGT: return 1;  // 001
2808   case ICmpInst::ICMP_EQ:  return 2;  // 010
2809   case ICmpInst::ICMP_UGE: return 3;  // 011
2810   case ICmpInst::ICMP_SGE: return 3;  // 011
2811   case ICmpInst::ICMP_ULT: return 4;  // 100
2812   case ICmpInst::ICMP_SLT: return 4;  // 100
2813   case ICmpInst::ICMP_NE:  return 5;  // 101
2814   case ICmpInst::ICMP_ULE: return 6;  // 110
2815   case ICmpInst::ICMP_SLE: return 6;  // 110
2816     // True -> 7
2817   default:
2818     assert(0 && "Invalid ICmp predicate!");
2819     return 0;
2820   }
2821 }
2822
2823 /// getICmpValue - This is the complement of getICmpCode, which turns an
2824 /// opcode and two operands into either a constant true or false, or a brand 
2825 /// new /// ICmp instruction. The sign is passed in to determine which kind
2826 /// of predicate to use in new icmp instructions.
2827 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2828   switch (code) {
2829   default: assert(0 && "Illegal ICmp code!");
2830   case  0: return ConstantInt::getFalse();
2831   case  1: 
2832     if (sign)
2833       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2834     else
2835       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2836   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
2837   case  3: 
2838     if (sign)
2839       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2840     else
2841       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2842   case  4: 
2843     if (sign)
2844       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2845     else
2846       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2847   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
2848   case  6: 
2849     if (sign)
2850       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2851     else
2852       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2853   case  7: return ConstantInt::getTrue();
2854   }
2855 }
2856
2857 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2858   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2859     (ICmpInst::isSignedPredicate(p1) && 
2860      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2861     (ICmpInst::isSignedPredicate(p2) && 
2862      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2863 }
2864
2865 namespace { 
2866 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2867 struct FoldICmpLogical {
2868   InstCombiner &IC;
2869   Value *LHS, *RHS;
2870   ICmpInst::Predicate pred;
2871   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2872     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2873       pred(ICI->getPredicate()) {}
2874   bool shouldApply(Value *V) const {
2875     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2876       if (PredicatesFoldable(pred, ICI->getPredicate()))
2877         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2878                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2879     return false;
2880   }
2881   Instruction *apply(Instruction &Log) const {
2882     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2883     if (ICI->getOperand(0) != LHS) {
2884       assert(ICI->getOperand(1) == LHS);
2885       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
2886     }
2887
2888     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
2889     unsigned LHSCode = getICmpCode(ICI);
2890     unsigned RHSCode = getICmpCode(RHSICI);
2891     unsigned Code;
2892     switch (Log.getOpcode()) {
2893     case Instruction::And: Code = LHSCode & RHSCode; break;
2894     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2895     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2896     default: assert(0 && "Illegal logical opcode!"); return 0;
2897     }
2898
2899     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
2900                     ICmpInst::isSignedPredicate(ICI->getPredicate());
2901       
2902     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
2903     if (Instruction *I = dyn_cast<Instruction>(RV))
2904       return I;
2905     // Otherwise, it's a constant boolean value...
2906     return IC.ReplaceInstUsesWith(Log, RV);
2907   }
2908 };
2909 } // end anonymous namespace
2910
2911 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2912 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2913 // guaranteed to be a binary operator.
2914 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2915                                     ConstantInt *OpRHS,
2916                                     ConstantInt *AndRHS,
2917                                     BinaryOperator &TheAnd) {
2918   Value *X = Op->getOperand(0);
2919   Constant *Together = 0;
2920   if (!Op->isShift())
2921     Together = And(AndRHS, OpRHS);
2922
2923   switch (Op->getOpcode()) {
2924   case Instruction::Xor:
2925     if (Op->hasOneUse()) {
2926       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2927       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
2928       InsertNewInstBefore(And, TheAnd);
2929       And->takeName(Op);
2930       return BinaryOperator::createXor(And, Together);
2931     }
2932     break;
2933   case Instruction::Or:
2934     if (Together == AndRHS) // (X | C) & C --> C
2935       return ReplaceInstUsesWith(TheAnd, AndRHS);
2936
2937     if (Op->hasOneUse() && Together != OpRHS) {
2938       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2939       Instruction *Or = BinaryOperator::createOr(X, Together);
2940       InsertNewInstBefore(Or, TheAnd);
2941       Or->takeName(Op);
2942       return BinaryOperator::createAnd(Or, AndRHS);
2943     }
2944     break;
2945   case Instruction::Add:
2946     if (Op->hasOneUse()) {
2947       // Adding a one to a single bit bit-field should be turned into an XOR
2948       // of the bit.  First thing to check is to see if this AND is with a
2949       // single bit constant.
2950       APInt AndRHSV(cast<ConstantInt>(AndRHS)->getValue());
2951
2952       // If there is only one bit set...
2953       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2954         // Ok, at this point, we know that we are masking the result of the
2955         // ADD down to exactly one bit.  If the constant we are adding has
2956         // no bits set below this bit, then we can eliminate the ADD.
2957         APInt AddRHS(cast<ConstantInt>(OpRHS)->getValue());
2958
2959         // Check to see if any bits below the one bit set in AndRHSV are set.
2960         if ((AddRHS & (AndRHSV-1)) == 0) {
2961           // If not, the only thing that can effect the output of the AND is
2962           // the bit specified by AndRHSV.  If that bit is set, the effect of
2963           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2964           // no effect.
2965           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2966             TheAnd.setOperand(0, X);
2967             return &TheAnd;
2968           } else {
2969             // Pull the XOR out of the AND.
2970             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
2971             InsertNewInstBefore(NewAnd, TheAnd);
2972             NewAnd->takeName(Op);
2973             return BinaryOperator::createXor(NewAnd, AndRHS);
2974           }
2975         }
2976       }
2977     }
2978     break;
2979
2980   case Instruction::Shl: {
2981     // We know that the AND will not produce any of the bits shifted in, so if
2982     // the anded constant includes them, clear them now!
2983     //
2984     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2985     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2986     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2987
2988     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2989       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2990     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2991       TheAnd.setOperand(1, CI);
2992       return &TheAnd;
2993     }
2994     break;
2995   }
2996   case Instruction::LShr:
2997   {
2998     // We know that the AND will not produce any of the bits shifted in, so if
2999     // the anded constant includes them, clear them now!  This only applies to
3000     // unsigned shifts, because a signed shr may bring in set bits!
3001     //
3002     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
3003     Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3004     Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
3005
3006     if (CI == ShrMask) {   // Masking out bits that the shift already masks.
3007       return ReplaceInstUsesWith(TheAnd, Op);
3008     } else if (CI != AndRHS) {
3009       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3010       return &TheAnd;
3011     }
3012     break;
3013   }
3014   case Instruction::AShr:
3015     // Signed shr.
3016     // See if this is shifting in some sign extension, then masking it out
3017     // with an and.
3018     if (Op->hasOneUse()) {
3019       Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
3020       Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
3021       Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
3022       if (C == AndRHS) {          // Masking out bits shifted in.
3023         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3024         // Make the argument unsigned.
3025         Value *ShVal = Op->getOperand(0);
3026         ShVal = InsertNewInstBefore(
3027             BinaryOperator::createLShr(ShVal, OpRHS, 
3028                                    Op->getName()), TheAnd);
3029         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3030       }
3031     }
3032     break;
3033   }
3034   return 0;
3035 }
3036
3037
3038 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3039 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3040 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3041 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3042 /// insert new instructions.
3043 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3044                                            bool isSigned, bool Inside, 
3045                                            Instruction &IB) {
3046   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3047             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3048          "Lo is not <= Hi in range emission code!");
3049     
3050   if (Inside) {
3051     if (Lo == Hi)  // Trivially false.
3052       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3053
3054     // V >= Min && V < Hi --> V < Hi
3055     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3056       ICmpInst::Predicate pred = (isSigned ? 
3057         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3058       return new ICmpInst(pred, V, Hi);
3059     }
3060
3061     // Emit V-Lo <u Hi-Lo
3062     Constant *NegLo = ConstantExpr::getNeg(Lo);
3063     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3064     InsertNewInstBefore(Add, IB);
3065     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3066     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3067   }
3068
3069   if (Lo == Hi)  // Trivially true.
3070     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3071
3072   // V < Min || V >= Hi -> V > Hi-1
3073   Hi = SubOne(cast<ConstantInt>(Hi));
3074   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3075     ICmpInst::Predicate pred = (isSigned ? 
3076         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3077     return new ICmpInst(pred, V, Hi);
3078   }
3079
3080   // Emit V-Lo >u Hi-1-Lo
3081   // Note that Hi has already had one subtracted from it, above.
3082   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3083   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3084   InsertNewInstBefore(Add, IB);
3085   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3086   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3087 }
3088
3089 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3090 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3091 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3092 // not, since all 1s are not contiguous.
3093 static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
3094   APInt V = Val->getValue();
3095   uint32_t BitWidth = Val->getType()->getBitWidth();
3096   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3097
3098   // look for the first zero bit after the run of ones
3099   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3100   // look for the first non-zero bit
3101   ME = V.getActiveBits(); 
3102   return true;
3103 }
3104
3105 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3106 /// where isSub determines whether the operator is a sub.  If we can fold one of
3107 /// the following xforms:
3108 /// 
3109 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3110 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3111 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3112 ///
3113 /// return (A +/- B).
3114 ///
3115 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3116                                         ConstantInt *Mask, bool isSub,
3117                                         Instruction &I) {
3118   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3119   if (!LHSI || LHSI->getNumOperands() != 2 ||
3120       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3121
3122   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3123
3124   switch (LHSI->getOpcode()) {
3125   default: return 0;
3126   case Instruction::And:
3127     if (And(N, Mask) == Mask) {
3128       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3129       if ((Mask->getValue().countLeadingZeros() + 
3130            Mask->getValue().countPopulation()) == 
3131           Mask->getValue().getBitWidth())
3132         break;
3133
3134       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3135       // part, we don't need any explicit masks to take them out of A.  If that
3136       // is all N is, ignore it.
3137       unsigned MB = 0, ME = 0;
3138       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3139         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3140         APInt Mask(APInt::getAllOnesValue(BitWidth));
3141         Mask = Mask.lshr(BitWidth-MB+1);
3142         if (MaskedValueIsZero(RHS, Mask))
3143           break;
3144       }
3145     }
3146     return 0;
3147   case Instruction::Or:
3148   case Instruction::Xor:
3149     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3150     if ((Mask->getValue().countLeadingZeros() + 
3151          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3152         && And(N, Mask)->isNullValue())
3153       break;
3154     return 0;
3155   }
3156   
3157   Instruction *New;
3158   if (isSub)
3159     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3160   else
3161     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3162   return InsertNewInstBefore(New, I);
3163 }
3164
3165 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3166   bool Changed = SimplifyCommutative(I);
3167   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3168
3169   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3170     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3171
3172   // and X, X = X
3173   if (Op0 == Op1)
3174     return ReplaceInstUsesWith(I, Op1);
3175
3176   // See if we can simplify any instructions used by the instruction whose sole 
3177   // purpose is to compute bits we don't care about.
3178   if (!isa<VectorType>(I.getType())) {
3179     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3180     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3181     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3182                              KnownZero, KnownOne))
3183     return &I;
3184   } else {
3185     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3186       if (CP->isAllOnesValue())
3187         return ReplaceInstUsesWith(I, I.getOperand(0));
3188     }
3189   }
3190   
3191   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3192     APInt AndRHSMask(AndRHS->getValue());
3193     APInt TypeMask(cast<IntegerType>(Op0->getType())->getMask());
3194     APInt NotAndRHS = AndRHSMask^TypeMask;
3195
3196     // Optimize a variety of ((val OP C1) & C2) combinations...
3197     if (isa<BinaryOperator>(Op0)) {
3198       Instruction *Op0I = cast<Instruction>(Op0);
3199       Value *Op0LHS = Op0I->getOperand(0);
3200       Value *Op0RHS = Op0I->getOperand(1);
3201       switch (Op0I->getOpcode()) {
3202       case Instruction::Xor:
3203       case Instruction::Or:
3204         // If the mask is only needed on one incoming arm, push it up.
3205         if (Op0I->hasOneUse()) {
3206           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3207             // Not masking anything out for the LHS, move to RHS.
3208             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3209                                                    Op0RHS->getName()+".masked");
3210             InsertNewInstBefore(NewRHS, I);
3211             return BinaryOperator::create(
3212                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3213           }
3214           if (!isa<Constant>(Op0RHS) &&
3215               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3216             // Not masking anything out for the RHS, move to LHS.
3217             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3218                                                    Op0LHS->getName()+".masked");
3219             InsertNewInstBefore(NewLHS, I);
3220             return BinaryOperator::create(
3221                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3222           }
3223         }
3224
3225         break;
3226       case Instruction::Add:
3227         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3228         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3229         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3230         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3231           return BinaryOperator::createAnd(V, AndRHS);
3232         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3233           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3234         break;
3235
3236       case Instruction::Sub:
3237         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3238         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3239         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3240         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3241           return BinaryOperator::createAnd(V, AndRHS);
3242         break;
3243       }
3244
3245       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3246         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3247           return Res;
3248     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3249       // If this is an integer truncation or change from signed-to-unsigned, and
3250       // if the source is an and/or with immediate, transform it.  This
3251       // frequently occurs for bitfield accesses.
3252       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3253         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3254             CastOp->getNumOperands() == 2)
3255           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3256             if (CastOp->getOpcode() == Instruction::And) {
3257               // Change: and (cast (and X, C1) to T), C2
3258               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3259               // This will fold the two constants together, which may allow 
3260               // other simplifications.
3261               Instruction *NewCast = CastInst::createTruncOrBitCast(
3262                 CastOp->getOperand(0), I.getType(), 
3263                 CastOp->getName()+".shrunk");
3264               NewCast = InsertNewInstBefore(NewCast, I);
3265               // trunc_or_bitcast(C1)&C2
3266               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3267               C3 = ConstantExpr::getAnd(C3, AndRHS);
3268               return BinaryOperator::createAnd(NewCast, C3);
3269             } else if (CastOp->getOpcode() == Instruction::Or) {
3270               // Change: and (cast (or X, C1) to T), C2
3271               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3272               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3273               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3274                 return ReplaceInstUsesWith(I, AndRHS);
3275             }
3276       }
3277     }
3278
3279     // Try to fold constant and into select arguments.
3280     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3281       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3282         return R;
3283     if (isa<PHINode>(Op0))
3284       if (Instruction *NV = FoldOpIntoPhi(I))
3285         return NV;
3286   }
3287
3288   Value *Op0NotVal = dyn_castNotVal(Op0);
3289   Value *Op1NotVal = dyn_castNotVal(Op1);
3290
3291   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3292     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3293
3294   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3295   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3296     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3297                                                I.getName()+".demorgan");
3298     InsertNewInstBefore(Or, I);
3299     return BinaryOperator::createNot(Or);
3300   }
3301   
3302   {
3303     Value *A = 0, *B = 0;
3304     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3305       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3306         return ReplaceInstUsesWith(I, Op1);
3307     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3308       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3309         return ReplaceInstUsesWith(I, Op0);
3310     
3311     if (Op0->hasOneUse() &&
3312         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3313       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3314         I.swapOperands();     // Simplify below
3315         std::swap(Op0, Op1);
3316       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3317         cast<BinaryOperator>(Op0)->swapOperands();
3318         I.swapOperands();     // Simplify below
3319         std::swap(Op0, Op1);
3320       }
3321     }
3322     if (Op1->hasOneUse() &&
3323         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3324       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3325         cast<BinaryOperator>(Op1)->swapOperands();
3326         std::swap(A, B);
3327       }
3328       if (A == Op0) {                                // A&(A^B) -> A & ~B
3329         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3330         InsertNewInstBefore(NotB, I);
3331         return BinaryOperator::createAnd(A, NotB);
3332       }
3333     }
3334   }
3335   
3336   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3337     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3338     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3339       return R;
3340
3341     Value *LHSVal, *RHSVal;
3342     ConstantInt *LHSCst, *RHSCst;
3343     ICmpInst::Predicate LHSCC, RHSCC;
3344     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3345       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3346         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3347             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3348             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3349             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3350             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3351             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3352           // Ensure that the larger constant is on the RHS.
3353           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3354             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3355           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3356           ICmpInst *LHS = cast<ICmpInst>(Op0);
3357           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3358             std::swap(LHS, RHS);
3359             std::swap(LHSCst, RHSCst);
3360             std::swap(LHSCC, RHSCC);
3361           }
3362
3363           // At this point, we know we have have two icmp instructions
3364           // comparing a value against two constants and and'ing the result
3365           // together.  Because of the above check, we know that we only have
3366           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3367           // (from the FoldICmpLogical check above), that the two constants 
3368           // are not equal and that the larger constant is on the RHS
3369           assert(LHSCst != RHSCst && "Compares not folded above?");
3370
3371           switch (LHSCC) {
3372           default: assert(0 && "Unknown integer condition code!");
3373           case ICmpInst::ICMP_EQ:
3374             switch (RHSCC) {
3375             default: assert(0 && "Unknown integer condition code!");
3376             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3377             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3378             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3379               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3380             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3381             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3382             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3383               return ReplaceInstUsesWith(I, LHS);
3384             }
3385           case ICmpInst::ICMP_NE:
3386             switch (RHSCC) {
3387             default: assert(0 && "Unknown integer condition code!");
3388             case ICmpInst::ICMP_ULT:
3389               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3390                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3391               break;                        // (X != 13 & X u< 15) -> no change
3392             case ICmpInst::ICMP_SLT:
3393               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3394                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3395               break;                        // (X != 13 & X s< 15) -> no change
3396             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3397             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3398             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3399               return ReplaceInstUsesWith(I, RHS);
3400             case ICmpInst::ICMP_NE:
3401               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3402                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3403                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3404                                                       LHSVal->getName()+".off");
3405                 InsertNewInstBefore(Add, I);
3406                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3407                                     ConstantInt::get(Add->getType(), 1));
3408               }
3409               break;                        // (X != 13 & X != 15) -> no change
3410             }
3411             break;
3412           case ICmpInst::ICMP_ULT:
3413             switch (RHSCC) {
3414             default: assert(0 && "Unknown integer condition code!");
3415             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3416             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3417               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3418             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3419               break;
3420             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3421             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3422               return ReplaceInstUsesWith(I, LHS);
3423             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3424               break;
3425             }
3426             break;
3427           case ICmpInst::ICMP_SLT:
3428             switch (RHSCC) {
3429             default: assert(0 && "Unknown integer condition code!");
3430             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3431             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3432               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3433             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3434               break;
3435             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3436             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3437               return ReplaceInstUsesWith(I, LHS);
3438             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3439               break;
3440             }
3441             break;
3442           case ICmpInst::ICMP_UGT:
3443             switch (RHSCC) {
3444             default: assert(0 && "Unknown integer condition code!");
3445             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3446               return ReplaceInstUsesWith(I, LHS);
3447             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3448               return ReplaceInstUsesWith(I, RHS);
3449             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3450               break;
3451             case ICmpInst::ICMP_NE:
3452               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3453                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3454               break;                        // (X u> 13 & X != 15) -> no change
3455             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3456               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3457                                      true, I);
3458             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3459               break;
3460             }
3461             break;
3462           case ICmpInst::ICMP_SGT:
3463             switch (RHSCC) {
3464             default: assert(0 && "Unknown integer condition code!");
3465             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
3466               return ReplaceInstUsesWith(I, LHS);
3467             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3468               return ReplaceInstUsesWith(I, RHS);
3469             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3470               break;
3471             case ICmpInst::ICMP_NE:
3472               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3473                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3474               break;                        // (X s> 13 & X != 15) -> no change
3475             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3476               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3477                                      true, I);
3478             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3479               break;
3480             }
3481             break;
3482           }
3483         }
3484   }
3485
3486   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3487   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3488     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3489       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3490         const Type *SrcTy = Op0C->getOperand(0)->getType();
3491         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3492             // Only do this if the casts both really cause code to be generated.
3493             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3494                               I.getType(), TD) &&
3495             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3496                               I.getType(), TD)) {
3497           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3498                                                          Op1C->getOperand(0),
3499                                                          I.getName());
3500           InsertNewInstBefore(NewOp, I);
3501           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3502         }
3503       }
3504     
3505   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3506   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3507     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3508       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3509           SI0->getOperand(1) == SI1->getOperand(1) &&
3510           (SI0->hasOneUse() || SI1->hasOneUse())) {
3511         Instruction *NewOp =
3512           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3513                                                         SI1->getOperand(0),
3514                                                         SI0->getName()), I);
3515         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3516                                       SI1->getOperand(1));
3517       }
3518   }
3519
3520   return Changed ? &I : 0;
3521 }
3522
3523 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3524 /// in the result.  If it does, and if the specified byte hasn't been filled in
3525 /// yet, fill it in and return false.
3526 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3527   Instruction *I = dyn_cast<Instruction>(V);
3528   if (I == 0) return true;
3529
3530   // If this is an or instruction, it is an inner node of the bswap.
3531   if (I->getOpcode() == Instruction::Or)
3532     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3533            CollectBSwapParts(I->getOperand(1), ByteValues);
3534   
3535   // If this is a shift by a constant int, and it is "24", then its operand
3536   // defines a byte.  We only handle unsigned types here.
3537   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3538     // Not shifting the entire input by N-1 bytes?
3539     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3540         8*(ByteValues.size()-1))
3541       return true;
3542     
3543     unsigned DestNo;
3544     if (I->getOpcode() == Instruction::Shl) {
3545       // X << 24 defines the top byte with the lowest of the input bytes.
3546       DestNo = ByteValues.size()-1;
3547     } else {
3548       // X >>u 24 defines the low byte with the highest of the input bytes.
3549       DestNo = 0;
3550     }
3551     
3552     // If the destination byte value is already defined, the values are or'd
3553     // together, which isn't a bswap (unless it's an or of the same bits).
3554     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3555       return true;
3556     ByteValues[DestNo] = I->getOperand(0);
3557     return false;
3558   }
3559   
3560   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3561   // don't have this.
3562   Value *Shift = 0, *ShiftLHS = 0;
3563   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3564   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3565       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3566     return true;
3567   Instruction *SI = cast<Instruction>(Shift);
3568
3569   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3570   if (ShiftAmt->getZExtValue() & 7 ||
3571       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3572     return true;
3573   
3574   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3575   unsigned DestByte;
3576   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3577     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3578       break;
3579   // Unknown mask for bswap.
3580   if (DestByte == ByteValues.size()) return true;
3581   
3582   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3583   unsigned SrcByte;
3584   if (SI->getOpcode() == Instruction::Shl)
3585     SrcByte = DestByte - ShiftBytes;
3586   else
3587     SrcByte = DestByte + ShiftBytes;
3588   
3589   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3590   if (SrcByte != ByteValues.size()-DestByte-1)
3591     return true;
3592   
3593   // If the destination byte value is already defined, the values are or'd
3594   // together, which isn't a bswap (unless it's an or of the same bits).
3595   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3596     return true;
3597   ByteValues[DestByte] = SI->getOperand(0);
3598   return false;
3599 }
3600
3601 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3602 /// If so, insert the new bswap intrinsic and return it.
3603 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3604   // We cannot bswap one byte.
3605   if (I.getType() == Type::Int8Ty)
3606     return 0;
3607   
3608   /// ByteValues - For each byte of the result, we keep track of which value
3609   /// defines each byte.
3610   SmallVector<Value*, 8> ByteValues;
3611   ByteValues.resize(TD->getTypeSize(I.getType()));
3612     
3613   // Try to find all the pieces corresponding to the bswap.
3614   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3615       CollectBSwapParts(I.getOperand(1), ByteValues))
3616     return 0;
3617   
3618   // Check to see if all of the bytes come from the same value.
3619   Value *V = ByteValues[0];
3620   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3621   
3622   // Check to make sure that all of the bytes come from the same value.
3623   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3624     if (ByteValues[i] != V)
3625       return 0;
3626     
3627   // If they do then *success* we can turn this into a bswap.  Figure out what
3628   // bswap to make it into.
3629   Module *M = I.getParent()->getParent()->getParent();
3630   const char *FnName = 0;
3631   if (I.getType() == Type::Int16Ty)
3632     FnName = "llvm.bswap.i16";
3633   else if (I.getType() == Type::Int32Ty)
3634     FnName = "llvm.bswap.i32";
3635   else if (I.getType() == Type::Int64Ty)
3636     FnName = "llvm.bswap.i64";
3637   else
3638     assert(0 && "Unknown integer type!");
3639   Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3640   return new CallInst(F, V);
3641 }
3642
3643
3644 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3645   bool Changed = SimplifyCommutative(I);
3646   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3647
3648   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3649     return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
3650
3651   // or X, X = X
3652   if (Op0 == Op1)
3653     return ReplaceInstUsesWith(I, Op0);
3654
3655   // See if we can simplify any instructions used by the instruction whose sole 
3656   // purpose is to compute bits we don't care about.
3657   if (!isa<VectorType>(I.getType())) {
3658     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3659     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3660     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3661                              KnownZero, KnownOne))
3662       return &I;
3663   }
3664   
3665   // or X, -1 == -1
3666   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3667     ConstantInt *C1 = 0; Value *X = 0;
3668     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3669     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3670       Instruction *Or = BinaryOperator::createOr(X, RHS);
3671       InsertNewInstBefore(Or, I);
3672       Or->takeName(Op0);
3673       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3674     }
3675
3676     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3677     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3678       Instruction *Or = BinaryOperator::createOr(X, RHS);
3679       InsertNewInstBefore(Or, I);
3680       Or->takeName(Op0);
3681       return BinaryOperator::createXor(Or,
3682                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3683     }
3684
3685     // Try to fold constant and into select arguments.
3686     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3687       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3688         return R;
3689     if (isa<PHINode>(Op0))
3690       if (Instruction *NV = FoldOpIntoPhi(I))
3691         return NV;
3692   }
3693
3694   Value *A = 0, *B = 0;
3695   ConstantInt *C1 = 0, *C2 = 0;
3696
3697   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3698     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3699       return ReplaceInstUsesWith(I, Op1);
3700   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3701     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3702       return ReplaceInstUsesWith(I, Op0);
3703
3704   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3705   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3706   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3707       match(Op1, m_Or(m_Value(), m_Value())) ||
3708       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3709        match(Op1, m_Shift(m_Value(), m_Value())))) {
3710     if (Instruction *BSwap = MatchBSwap(I))
3711       return BSwap;
3712   }
3713   
3714   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3715   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3716       MaskedValueIsZero(Op1, C1->getValue())) {
3717     Instruction *NOr = BinaryOperator::createOr(A, Op1);
3718     InsertNewInstBefore(NOr, I);
3719     NOr->takeName(Op0);
3720     return BinaryOperator::createXor(NOr, C1);
3721   }
3722
3723   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3724   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3725       MaskedValueIsZero(Op0, C1->getValue())) {
3726     Instruction *NOr = BinaryOperator::createOr(A, Op0);
3727     InsertNewInstBefore(NOr, I);
3728     NOr->takeName(Op0);
3729     return BinaryOperator::createXor(NOr, C1);
3730   }
3731
3732   // (A & C1)|(B & C2)
3733   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3734       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3735
3736     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3737       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3738
3739
3740     // If we have: ((V + N) & C1) | (V & C2)
3741     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3742     // replace with V+N.
3743     if (C1 == ConstantExpr::getNot(C2)) {
3744       Value *V1 = 0, *V2 = 0;
3745       if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3746           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3747         // Add commutes, try both ways.
3748         if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3749           return ReplaceInstUsesWith(I, A);
3750         if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3751           return ReplaceInstUsesWith(I, A);
3752       }
3753       // Or commutes, try both ways.
3754       if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3755           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3756         // Add commutes, try both ways.
3757         if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3758           return ReplaceInstUsesWith(I, B);
3759         if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3760           return ReplaceInstUsesWith(I, B);
3761       }
3762     }
3763   }
3764   
3765   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3766   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3767     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3768       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3769           SI0->getOperand(1) == SI1->getOperand(1) &&
3770           (SI0->hasOneUse() || SI1->hasOneUse())) {
3771         Instruction *NewOp =
3772         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3773                                                      SI1->getOperand(0),
3774                                                      SI0->getName()), I);
3775         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3776                                       SI1->getOperand(1));
3777       }
3778   }
3779
3780   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3781     if (A == Op1)   // ~A | A == -1
3782       return ReplaceInstUsesWith(I,
3783                                 ConstantInt::getAllOnesValue(I.getType()));
3784   } else {
3785     A = 0;
3786   }
3787   // Note, A is still live here!
3788   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3789     if (Op0 == B)
3790       return ReplaceInstUsesWith(I,
3791                                 ConstantInt::getAllOnesValue(I.getType()));
3792
3793     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3794     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3795       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3796                                               I.getName()+".demorgan"), I);
3797       return BinaryOperator::createNot(And);
3798     }
3799   }
3800
3801   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3802   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3803     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3804       return R;
3805
3806     Value *LHSVal, *RHSVal;
3807     ConstantInt *LHSCst, *RHSCst;
3808     ICmpInst::Predicate LHSCC, RHSCC;
3809     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3810       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3811         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
3812             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3813             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3814             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3815             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3816             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3817           // Ensure that the larger constant is on the RHS.
3818           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3819             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3820           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3821           ICmpInst *LHS = cast<ICmpInst>(Op0);
3822           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3823             std::swap(LHS, RHS);
3824             std::swap(LHSCst, RHSCst);
3825             std::swap(LHSCC, RHSCC);
3826           }
3827
3828           // At this point, we know we have have two icmp instructions
3829           // comparing a value against two constants and or'ing the result
3830           // together.  Because of the above check, we know that we only have
3831           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3832           // FoldICmpLogical check above), that the two constants are not
3833           // equal.
3834           assert(LHSCst != RHSCst && "Compares not folded above?");
3835
3836           switch (LHSCC) {
3837           default: assert(0 && "Unknown integer condition code!");
3838           case ICmpInst::ICMP_EQ:
3839             switch (RHSCC) {
3840             default: assert(0 && "Unknown integer condition code!");
3841             case ICmpInst::ICMP_EQ:
3842               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3843                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3844                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3845                                                       LHSVal->getName()+".off");
3846                 InsertNewInstBefore(Add, I);
3847                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3848                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3849               }
3850               break;                         // (X == 13 | X == 15) -> no change
3851             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
3852             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
3853               break;
3854             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
3855             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
3856             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
3857               return ReplaceInstUsesWith(I, RHS);
3858             }
3859             break;
3860           case ICmpInst::ICMP_NE:
3861             switch (RHSCC) {
3862             default: assert(0 && "Unknown integer condition code!");
3863             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
3864             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
3865             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
3866               return ReplaceInstUsesWith(I, LHS);
3867             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
3868             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
3869             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
3870               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3871             }
3872             break;
3873           case ICmpInst::ICMP_ULT:
3874             switch (RHSCC) {
3875             default: assert(0 && "Unknown integer condition code!");
3876             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
3877               break;
3878             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
3879               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
3880                                      false, I);
3881             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
3882               break;
3883             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
3884             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
3885               return ReplaceInstUsesWith(I, RHS);
3886             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
3887               break;
3888             }
3889             break;
3890           case ICmpInst::ICMP_SLT:
3891             switch (RHSCC) {
3892             default: assert(0 && "Unknown integer condition code!");
3893             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
3894               break;
3895             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
3896               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
3897                                      false, I);
3898             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
3899               break;
3900             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
3901             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
3902               return ReplaceInstUsesWith(I, RHS);
3903             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
3904               break;
3905             }
3906             break;
3907           case ICmpInst::ICMP_UGT:
3908             switch (RHSCC) {
3909             default: assert(0 && "Unknown integer condition code!");
3910             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
3911             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
3912               return ReplaceInstUsesWith(I, LHS);
3913             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
3914               break;
3915             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
3916             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
3917               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3918             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
3919               break;
3920             }
3921             break;
3922           case ICmpInst::ICMP_SGT:
3923             switch (RHSCC) {
3924             default: assert(0 && "Unknown integer condition code!");
3925             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
3926             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
3927               return ReplaceInstUsesWith(I, LHS);
3928             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
3929               break;
3930             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
3931             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
3932               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3933             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
3934               break;
3935             }
3936             break;
3937           }
3938         }
3939   }
3940     
3941   // fold (or (cast A), (cast B)) -> (cast (or A, B))
3942   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3943     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3944       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3945         const Type *SrcTy = Op0C->getOperand(0)->getType();
3946         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3947             // Only do this if the casts both really cause code to be generated.
3948             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3949                               I.getType(), TD) &&
3950             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3951                               I.getType(), TD)) {
3952           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3953                                                         Op1C->getOperand(0),
3954                                                         I.getName());
3955           InsertNewInstBefore(NewOp, I);
3956           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3957         }
3958       }
3959       
3960
3961   return Changed ? &I : 0;
3962 }
3963
3964 // XorSelf - Implements: X ^ X --> 0
3965 struct XorSelf {
3966   Value *RHS;
3967   XorSelf(Value *rhs) : RHS(rhs) {}
3968   bool shouldApply(Value *LHS) const { return LHS == RHS; }
3969   Instruction *apply(BinaryOperator &Xor) const {
3970     return &Xor;
3971   }
3972 };
3973
3974
3975 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3976   bool Changed = SimplifyCommutative(I);
3977   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3978
3979   if (isa<UndefValue>(Op1))
3980     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
3981
3982   // xor X, X = 0, even if X is nested in a sequence of Xor's.
3983   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3984     assert(Result == &I && "AssociativeOpt didn't work?");
3985     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3986   }
3987   
3988   // See if we can simplify any instructions used by the instruction whose sole 
3989   // purpose is to compute bits we don't care about.
3990   if (!isa<VectorType>(I.getType())) {
3991     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3992     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3993     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3994                              KnownZero, KnownOne))
3995       return &I;
3996   }
3997
3998   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3999     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4000     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4001       if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
4002         return new ICmpInst(ICI->getInversePredicate(),
4003                             ICI->getOperand(0), ICI->getOperand(1));
4004
4005     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4006       // ~(c-X) == X-c-1 == X+(-c-1)
4007       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4008         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4009           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4010           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4011                                               ConstantInt::get(I.getType(), 1));
4012           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4013         }
4014
4015       // ~(~X & Y) --> (X | ~Y)
4016       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4017         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4018         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4019           Instruction *NotY =
4020             BinaryOperator::createNot(Op0I->getOperand(1),
4021                                       Op0I->getOperand(1)->getName()+".not");
4022           InsertNewInstBefore(NotY, I);
4023           return BinaryOperator::createOr(Op0NotVal, NotY);
4024         }
4025       }
4026
4027       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4028         if (Op0I->getOpcode() == Instruction::Add) {
4029           // ~(X-c) --> (-c-1)-X
4030           if (RHS->isAllOnesValue()) {
4031             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4032             return BinaryOperator::createSub(
4033                            ConstantExpr::getSub(NegOp0CI,
4034                                              ConstantInt::get(I.getType(), 1)),
4035                                           Op0I->getOperand(0));
4036           }
4037         } else if (Op0I->getOpcode() == Instruction::Or) {
4038           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4039           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4040             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4041             // Anything in both C1 and C2 is known to be zero, remove it from
4042             // NewRHS.
4043             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
4044             NewRHS = ConstantExpr::getAnd(NewRHS, 
4045                                           ConstantExpr::getNot(CommonBits));
4046             AddToWorkList(Op0I);
4047             I.setOperand(0, Op0I->getOperand(0));
4048             I.setOperand(1, NewRHS);
4049             return &I;
4050           }
4051         }
4052     }
4053
4054     // Try to fold constant and into select arguments.
4055     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4056       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4057         return R;
4058     if (isa<PHINode>(Op0))
4059       if (Instruction *NV = FoldOpIntoPhi(I))
4060         return NV;
4061   }
4062
4063   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4064     if (X == Op1)
4065       return ReplaceInstUsesWith(I,
4066                                 ConstantInt::getAllOnesValue(I.getType()));
4067
4068   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4069     if (X == Op0)
4070       return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
4071
4072   
4073   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4074   if (Op1I) {
4075     Value *A, *B;
4076     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4077       if (A == Op0) {              // B^(B|A) == (A|B)^B
4078         Op1I->swapOperands();
4079         I.swapOperands();
4080         std::swap(Op0, Op1);
4081       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4082         I.swapOperands();     // Simplified below.
4083         std::swap(Op0, Op1);
4084       }
4085     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4086       if (Op0 == A)                                          // A^(A^B) == B
4087         return ReplaceInstUsesWith(I, B);
4088       else if (Op0 == B)                                     // A^(B^A) == B
4089         return ReplaceInstUsesWith(I, A);
4090     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4091       if (A == Op0)                                        // A^(A&B) -> A^(B&A)
4092         Op1I->swapOperands();
4093       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4094         I.swapOperands();     // Simplified below.
4095         std::swap(Op0, Op1);
4096       }
4097     }
4098   }
4099   
4100   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4101   if (Op0I) {
4102     Value *A, *B;
4103     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4104       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4105         std::swap(A, B);
4106       if (B == Op1) {                                // (A|B)^B == A & ~B
4107         Instruction *NotB =
4108           InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4109         return BinaryOperator::createAnd(A, NotB);
4110       }
4111     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4112       if (Op1 == A)                                          // (A^B)^A == B
4113         return ReplaceInstUsesWith(I, B);
4114       else if (Op1 == B)                                     // (B^A)^A == B
4115         return ReplaceInstUsesWith(I, A);
4116     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4117       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4118         std::swap(A, B);
4119       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4120           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4121         Instruction *N =
4122           InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4123         return BinaryOperator::createAnd(N, Op1);
4124       }
4125     }
4126   }
4127   
4128   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4129   if (Op0I && Op1I && Op0I->isShift() && 
4130       Op0I->getOpcode() == Op1I->getOpcode() && 
4131       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4132       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4133     Instruction *NewOp =
4134       InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4135                                                     Op1I->getOperand(0),
4136                                                     Op0I->getName()), I);
4137     return BinaryOperator::create(Op1I->getOpcode(), NewOp, 
4138                                   Op1I->getOperand(1));
4139   }
4140     
4141   if (Op0I && Op1I) {
4142     Value *A, *B, *C, *D;
4143     // (A & B)^(A | B) -> A ^ B
4144     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4145         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4146       if ((A == C && B == D) || (A == D && B == C)) 
4147         return BinaryOperator::createXor(A, B);
4148     }
4149     // (A | B)^(A & B) -> A ^ B
4150     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4151         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4152       if ((A == C && B == D) || (A == D && B == C)) 
4153         return BinaryOperator::createXor(A, B);
4154     }
4155     
4156     // (A & B)^(C & D)
4157     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4158         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4159         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4160       // (X & Y)^(X & Y) -> (Y^Z) & X
4161       Value *X = 0, *Y = 0, *Z = 0;
4162       if (A == C)
4163         X = A, Y = B, Z = D;
4164       else if (A == D)
4165         X = A, Y = B, Z = C;
4166       else if (B == C)
4167         X = B, Y = A, Z = D;
4168       else if (B == D)
4169         X = B, Y = A, Z = C;
4170       
4171       if (X) {
4172         Instruction *NewOp =
4173         InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4174         return BinaryOperator::createAnd(NewOp, X);
4175       }
4176     }
4177   }
4178     
4179   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4180   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4181     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4182       return R;
4183
4184   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4185   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4186     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4187       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4188         const Type *SrcTy = Op0C->getOperand(0)->getType();
4189         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4190             // Only do this if the casts both really cause code to be generated.
4191             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4192                               I.getType(), TD) &&
4193             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4194                               I.getType(), TD)) {
4195           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4196                                                          Op1C->getOperand(0),
4197                                                          I.getName());
4198           InsertNewInstBefore(NewOp, I);
4199           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4200         }
4201       }
4202
4203   return Changed ? &I : 0;
4204 }
4205
4206 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4207 /// overflowed for this type.
4208 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4209                             ConstantInt *In2, bool IsSigned = false) {
4210   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4211
4212   if (IsSigned)
4213     if (In2->getValue().isNegative())
4214       return Result->getValue().sgt(In1->getValue());
4215     else
4216       return Result->getValue().slt(In1->getValue());
4217   else
4218     return Result->getValue().ult(In1->getValue());
4219 }
4220
4221 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4222 /// code necessary to compute the offset from the base pointer (without adding
4223 /// in the base pointer).  Return the result as a signed integer of intptr size.
4224 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4225   TargetData &TD = IC.getTargetData();
4226   gep_type_iterator GTI = gep_type_begin(GEP);
4227   const Type *IntPtrTy = TD.getIntPtrType();
4228   Value *Result = Constant::getNullValue(IntPtrTy);
4229
4230   // Build a mask for high order bits.
4231   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4232
4233   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4234     Value *Op = GEP->getOperand(i);
4235     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4236     Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4237     if (Constant *OpC = dyn_cast<Constant>(Op)) {
4238       if (!OpC->isNullValue()) {
4239         OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4240         Scale = ConstantExpr::getMul(OpC, Scale);
4241         if (Constant *RC = dyn_cast<Constant>(Result))
4242           Result = ConstantExpr::getAdd(RC, Scale);
4243         else {
4244           // Emit an add instruction.
4245           Result = IC.InsertNewInstBefore(
4246              BinaryOperator::createAdd(Result, Scale,
4247                                        GEP->getName()+".offs"), I);
4248         }
4249       }
4250     } else {
4251       // Convert to correct type.
4252       Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4253                                                Op->getName()+".c"), I);
4254       if (Size != 1)
4255         // We'll let instcombine(mul) convert this to a shl if possible.
4256         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4257                                                     GEP->getName()+".idx"), I);
4258
4259       // Emit an add instruction.
4260       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4261                                                     GEP->getName()+".offs"), I);
4262     }
4263   }
4264   return Result;
4265 }
4266
4267 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4268 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4269 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4270                                        ICmpInst::Predicate Cond,
4271                                        Instruction &I) {
4272   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4273
4274   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4275     if (isa<PointerType>(CI->getOperand(0)->getType()))
4276       RHS = CI->getOperand(0);
4277
4278   Value *PtrBase = GEPLHS->getOperand(0);
4279   if (PtrBase == RHS) {
4280     // As an optimization, we don't actually have to compute the actual value of
4281     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4282     // each index is zero or not.
4283     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4284       Instruction *InVal = 0;
4285       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4286       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4287         bool EmitIt = true;
4288         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4289           if (isa<UndefValue>(C))  // undef index -> undef.
4290             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4291           if (C->isNullValue())
4292             EmitIt = false;
4293           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4294             EmitIt = false;  // This is indexing into a zero sized array?
4295           } else if (isa<ConstantInt>(C))
4296             return ReplaceInstUsesWith(I, // No comparison is needed here.
4297                                  ConstantInt::get(Type::Int1Ty, 
4298                                                   Cond == ICmpInst::ICMP_NE));
4299         }
4300
4301         if (EmitIt) {
4302           Instruction *Comp =
4303             new ICmpInst(Cond, GEPLHS->getOperand(i),
4304                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4305           if (InVal == 0)
4306             InVal = Comp;
4307           else {
4308             InVal = InsertNewInstBefore(InVal, I);
4309             InsertNewInstBefore(Comp, I);
4310             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4311               InVal = BinaryOperator::createOr(InVal, Comp);
4312             else                              // True if all are equal
4313               InVal = BinaryOperator::createAnd(InVal, Comp);
4314           }
4315         }
4316       }
4317
4318       if (InVal)
4319         return InVal;
4320       else
4321         // No comparison is needed here, all indexes = 0
4322         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4323                                                 Cond == ICmpInst::ICMP_EQ));
4324     }
4325
4326     // Only lower this if the icmp is the only user of the GEP or if we expect
4327     // the result to fold to a constant!
4328     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4329       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4330       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4331       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4332                           Constant::getNullValue(Offset->getType()));
4333     }
4334   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4335     // If the base pointers are different, but the indices are the same, just
4336     // compare the base pointer.
4337     if (PtrBase != GEPRHS->getOperand(0)) {
4338       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4339       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4340                         GEPRHS->getOperand(0)->getType();
4341       if (IndicesTheSame)
4342         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4343           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4344             IndicesTheSame = false;
4345             break;
4346           }
4347
4348       // If all indices are the same, just compare the base pointers.
4349       if (IndicesTheSame)
4350         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4351                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4352
4353       // Otherwise, the base pointers are different and the indices are
4354       // different, bail out.
4355       return 0;
4356     }
4357
4358     // If one of the GEPs has all zero indices, recurse.
4359     bool AllZeros = true;
4360     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4361       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4362           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4363         AllZeros = false;
4364         break;
4365       }
4366     if (AllZeros)
4367       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4368                           ICmpInst::getSwappedPredicate(Cond), I);
4369
4370     // If the other GEP has all zero indices, recurse.
4371     AllZeros = true;
4372     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4373       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4374           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4375         AllZeros = false;
4376         break;
4377       }
4378     if (AllZeros)
4379       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4380
4381     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4382       // If the GEPs only differ by one index, compare it.
4383       unsigned NumDifferences = 0;  // Keep track of # differences.
4384       unsigned DiffOperand = 0;     // The operand that differs.
4385       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4386         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4387           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4388                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4389             // Irreconcilable differences.
4390             NumDifferences = 2;
4391             break;
4392           } else {
4393             if (NumDifferences++) break;
4394             DiffOperand = i;
4395           }
4396         }
4397
4398       if (NumDifferences == 0)   // SAME GEP?
4399         return ReplaceInstUsesWith(I, // No comparison is needed here.
4400                                    ConstantInt::get(Type::Int1Ty, 
4401                                                     Cond == ICmpInst::ICMP_EQ));
4402       else if (NumDifferences == 1) {
4403         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4404         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4405         // Make sure we do a signed comparison here.
4406         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4407       }
4408     }
4409
4410     // Only lower this if the icmp is the only user of the GEP or if we expect
4411     // the result to fold to a constant!
4412     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4413         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4414       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4415       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4416       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4417       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4418     }
4419   }
4420   return 0;
4421 }
4422
4423 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4424   bool Changed = SimplifyCompare(I);
4425   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4426
4427   // Fold trivial predicates.
4428   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4429     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4430   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4431     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4432   
4433   // Simplify 'fcmp pred X, X'
4434   if (Op0 == Op1) {
4435     switch (I.getPredicate()) {
4436     default: assert(0 && "Unknown predicate!");
4437     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4438     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4439     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4440       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4441     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4442     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4443     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4444       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4445       
4446     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4447     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4448     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4449     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4450       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4451       I.setPredicate(FCmpInst::FCMP_UNO);
4452       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4453       return &I;
4454       
4455     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4456     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4457     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4458     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4459       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4460       I.setPredicate(FCmpInst::FCMP_ORD);
4461       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4462       return &I;
4463     }
4464   }
4465     
4466   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4467     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4468
4469   // Handle fcmp with constant RHS
4470   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4471     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4472       switch (LHSI->getOpcode()) {
4473       case Instruction::PHI:
4474         if (Instruction *NV = FoldOpIntoPhi(I))
4475           return NV;
4476         break;
4477       case Instruction::Select:
4478         // If either operand of the select is a constant, we can fold the
4479         // comparison into the select arms, which will cause one to be
4480         // constant folded and the select turned into a bitwise or.
4481         Value *Op1 = 0, *Op2 = 0;
4482         if (LHSI->hasOneUse()) {
4483           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4484             // Fold the known value into the constant operand.
4485             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4486             // Insert a new FCmp of the other select operand.
4487             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4488                                                       LHSI->getOperand(2), RHSC,
4489                                                       I.getName()), I);
4490           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4491             // Fold the known value into the constant operand.
4492             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4493             // Insert a new FCmp of the other select operand.
4494             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4495                                                       LHSI->getOperand(1), RHSC,
4496                                                       I.getName()), I);
4497           }
4498         }
4499
4500         if (Op1)
4501           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4502         break;
4503       }
4504   }
4505
4506   return Changed ? &I : 0;
4507 }
4508
4509 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4510   bool Changed = SimplifyCompare(I);
4511   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4512   const Type *Ty = Op0->getType();
4513
4514   // icmp X, X
4515   if (Op0 == Op1)
4516     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4517                                                    isTrueWhenEqual(I)));
4518
4519   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4520     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4521
4522   // icmp of GlobalValues can never equal each other as long as they aren't
4523   // external weak linkage type.
4524   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4525     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4526       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4527         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4528                                                        !isTrueWhenEqual(I)));
4529
4530   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4531   // addresses never equal each other!  We already know that Op0 != Op1.
4532   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4533        isa<ConstantPointerNull>(Op0)) &&
4534       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4535        isa<ConstantPointerNull>(Op1)))
4536     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4537                                                    !isTrueWhenEqual(I)));
4538
4539   // icmp's with boolean values can always be turned into bitwise operations
4540   if (Ty == Type::Int1Ty) {
4541     switch (I.getPredicate()) {
4542     default: assert(0 && "Invalid icmp instruction!");
4543     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4544       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4545       InsertNewInstBefore(Xor, I);
4546       return BinaryOperator::createNot(Xor);
4547     }
4548     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4549       return BinaryOperator::createXor(Op0, Op1);
4550
4551     case ICmpInst::ICMP_UGT:
4552     case ICmpInst::ICMP_SGT:
4553       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4554       // FALL THROUGH
4555     case ICmpInst::ICMP_ULT:
4556     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4557       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4558       InsertNewInstBefore(Not, I);
4559       return BinaryOperator::createAnd(Not, Op1);
4560     }
4561     case ICmpInst::ICMP_UGE:
4562     case ICmpInst::ICMP_SGE:
4563       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4564       // FALL THROUGH
4565     case ICmpInst::ICMP_ULE:
4566     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4567       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4568       InsertNewInstBefore(Not, I);
4569       return BinaryOperator::createOr(Not, Op1);
4570     }
4571     }
4572   }
4573
4574   // See if we are doing a comparison between a constant and an instruction that
4575   // can be folded into the comparison.
4576   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4577     switch (I.getPredicate()) {
4578     default: break;
4579     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4580       if (CI->isMinValue(false))
4581         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4582       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4583         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4584       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4585         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4586       break;
4587
4588     case ICmpInst::ICMP_SLT:
4589       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4590         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4591       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4592         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4593       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4594         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4595       break;
4596
4597     case ICmpInst::ICMP_UGT:
4598       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4599         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4600       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4601         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4602       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4603         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4604       break;
4605
4606     case ICmpInst::ICMP_SGT:
4607       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4608         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4609       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4610         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4611       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4612         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4613       break;
4614
4615     case ICmpInst::ICMP_ULE:
4616       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4617         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4618       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4619         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4620       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4621         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4622       break;
4623
4624     case ICmpInst::ICMP_SLE:
4625       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4626         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4627       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4628         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4629       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4630         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4631       break;
4632
4633     case ICmpInst::ICMP_UGE:
4634       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4635         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4636       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4637         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4638       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4639         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4640       break;
4641
4642     case ICmpInst::ICMP_SGE:
4643       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4644         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4645       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4646         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4647       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4648         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4649       break;
4650     }
4651
4652     // If we still have a icmp le or icmp ge instruction, turn it into the
4653     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4654     // already been handled above, this requires little checking.
4655     //
4656     switch (I.getPredicate()) {
4657       default: break;
4658       case ICmpInst::ICMP_ULE: 
4659         return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4660       case ICmpInst::ICMP_SLE:
4661         return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4662       case ICmpInst::ICMP_UGE:
4663         return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4664       case ICmpInst::ICMP_SGE:
4665         return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4666     }
4667     
4668     // See if we can fold the comparison based on bits known to be zero or one
4669     // in the input.
4670     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4671     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4672     if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
4673                              KnownZero, KnownOne, 0))
4674       return &I;
4675         
4676     // Given the known and unknown bits, compute a range that the LHS could be
4677     // in.
4678     if ((KnownOne | KnownZero) != 0) {
4679       // Compute the Min, Max and RHS values based on the known bits. For the
4680       // EQ and NE we use unsigned values.
4681       APInt Min(BitWidth, 0), Max(BitWidth, 0), RHSVal(CI->getValue());
4682       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4683         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
4684                                                Max);
4685       } else {
4686         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
4687                                                  Max);
4688       }
4689       switch (I.getPredicate()) {  // LE/GE have been folded already.
4690       default: assert(0 && "Unknown icmp opcode!");
4691       case ICmpInst::ICMP_EQ:
4692         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4693           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4694         break;
4695       case ICmpInst::ICMP_NE:
4696         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4697           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4698         break;
4699       case ICmpInst::ICMP_ULT:
4700         if (Max.ult(RHSVal))
4701           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4702         if (Min.ugt(RHSVal))
4703           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4704         break;
4705       case ICmpInst::ICMP_UGT:
4706         if (Min.ugt(RHSVal))
4707           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4708         if (Max.ult(RHSVal))
4709           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4710         break;
4711       case ICmpInst::ICMP_SLT:
4712         if (Max.slt(RHSVal))
4713           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4714         if (Min.sgt(RHSVal))
4715           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4716         break;
4717       case ICmpInst::ICMP_SGT: 
4718         if (Min.sgt(RHSVal))
4719           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4720         if (Max.slt(RHSVal))
4721           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4722         break;
4723       }
4724     }
4725           
4726     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
4727     // instruction, see if that instruction also has constants so that the 
4728     // instruction can be folded into the icmp 
4729     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4730       switch (LHSI->getOpcode()) {
4731       case Instruction::And:
4732         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4733             LHSI->getOperand(0)->hasOneUse()) {
4734           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4735
4736           // If the LHS is an AND of a truncating cast, we can widen the
4737           // and/compare to be the input width without changing the value
4738           // produced, eliminating a cast.
4739           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4740             // We can do this transformation if either the AND constant does not
4741             // have its sign bit set or if it is an equality comparison. 
4742             // Extending a relational comparison when we're checking the sign
4743             // bit would not work.
4744             if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4745                 (I.isEquality() || AndCST->getValue().isPositive() && 
4746                  CI->getValue().isPositive())) {
4747               ConstantInt *NewCST;
4748               ConstantInt *NewCI;
4749               APInt NewCSTVal(AndCST->getValue()), NewCIVal(CI->getValue());
4750               uint32_t BitWidth = cast<IntegerType>(
4751                 Cast->getOperand(0)->getType())->getBitWidth();
4752               NewCST = ConstantInt::get(NewCSTVal.zext(BitWidth));
4753               NewCI = ConstantInt::get(NewCIVal.zext(BitWidth));
4754               Instruction *NewAnd = 
4755                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4756                                           LHSI->getName());
4757               InsertNewInstBefore(NewAnd, I);
4758               return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
4759             }
4760           }
4761           
4762           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4763           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4764           // happens a LOT in code produced by the C front-end, for bitfield
4765           // access.
4766           BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4767           if (Shift && !Shift->isShift())
4768             Shift = 0;
4769
4770           ConstantInt *ShAmt;
4771           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4772           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4773           const Type *AndTy = AndCST->getType();          // Type of the and.
4774
4775           // We can fold this as long as we can't shift unknown bits
4776           // into the mask.  This can only happen with signed shift
4777           // rights, as they sign-extend.
4778           if (ShAmt) {
4779             bool CanFold = Shift->isLogicalShift();
4780             if (!CanFold) {
4781               // To test for the bad case of the signed shr, see if any
4782               // of the bits shifted in could be tested after the mask.
4783               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4784               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4785
4786               Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
4787               Constant *ShVal =
4788                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4789                                      OShAmt);
4790               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4791                 CanFold = true;
4792             }
4793
4794             if (CanFold) {
4795               Constant *NewCst;
4796               if (Shift->getOpcode() == Instruction::Shl)
4797                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4798               else
4799                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4800
4801               // Check to see if we are shifting out any of the bits being
4802               // compared.
4803               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4804                 // If we shifted bits out, the fold is not going to work out.
4805                 // As a special case, check to see if this means that the
4806                 // result is always true or false now.
4807                 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4808                   return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4809                 if (I.getPredicate() == ICmpInst::ICMP_NE)
4810                   return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4811               } else {
4812                 I.setOperand(1, NewCst);
4813                 Constant *NewAndCST;
4814                 if (Shift->getOpcode() == Instruction::Shl)
4815                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4816                 else
4817                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4818                 LHSI->setOperand(1, NewAndCST);
4819                 LHSI->setOperand(0, Shift->getOperand(0));
4820                 AddToWorkList(Shift); // Shift is dead.
4821                 AddUsesToWorkList(I);
4822                 return &I;
4823               }
4824             }
4825           }
4826           
4827           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4828           // preferable because it allows the C<<Y expression to be hoisted out
4829           // of a loop if Y is invariant and X is not.
4830           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4831               I.isEquality() && !Shift->isArithmeticShift() &&
4832               isa<Instruction>(Shift->getOperand(0))) {
4833             // Compute C << Y.
4834             Value *NS;
4835             if (Shift->getOpcode() == Instruction::LShr) {
4836               NS = BinaryOperator::createShl(AndCST, 
4837                                           Shift->getOperand(1), "tmp");
4838             } else {
4839               // Insert a logical shift.
4840               NS = BinaryOperator::createLShr(AndCST,
4841                                           Shift->getOperand(1), "tmp");
4842             }
4843             InsertNewInstBefore(cast<Instruction>(NS), I);
4844
4845             // Compute X & (C << Y).
4846             Instruction *NewAnd = BinaryOperator::createAnd(
4847                 Shift->getOperand(0), NS, LHSI->getName());
4848             InsertNewInstBefore(NewAnd, I);
4849             
4850             I.setOperand(0, NewAnd);
4851             return &I;
4852           }
4853         }
4854         break;
4855
4856       case Instruction::Shl:         // (icmp pred (shl X, ShAmt), CI)
4857         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4858           if (I.isEquality()) {
4859             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4860
4861             // Check that the shift amount is in range.  If not, don't perform
4862             // undefined shifts.  When the shift is visited it will be
4863             // simplified.
4864             if (ShAmt->getZExtValue() >= TypeBits)
4865               break;
4866
4867             // If we are comparing against bits always shifted out, the
4868             // comparison cannot succeed.
4869             Constant *Comp =
4870               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4871             if (Comp != CI) {// Comparing against a bit that we know is zero.
4872               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4873               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4874               return ReplaceInstUsesWith(I, Cst);
4875             }
4876
4877             if (LHSI->hasOneUse()) {
4878               // Otherwise strength reduce the shift into an and.
4879               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4880               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4881               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4882
4883               Instruction *AndI =
4884                 BinaryOperator::createAnd(LHSI->getOperand(0),
4885                                           Mask, LHSI->getName()+".mask");
4886               Value *And = InsertNewInstBefore(AndI, I);
4887               return new ICmpInst(I.getPredicate(), And,
4888                                      ConstantExpr::getLShr(CI, ShAmt));
4889             }
4890           }
4891         }
4892         break;
4893
4894       case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
4895       case Instruction::AShr:
4896         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4897           if (I.isEquality()) {
4898             // Check that the shift amount is in range.  If not, don't perform
4899             // undefined shifts.  When the shift is visited it will be
4900             // simplified.
4901             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4902             if (ShAmt->getZExtValue() >= TypeBits)
4903               break;
4904
4905             // If we are comparing against bits always shifted out, the
4906             // comparison cannot succeed.
4907             Constant *Comp;
4908             if (LHSI->getOpcode() == Instruction::LShr) 
4909               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
4910                                            ShAmt);
4911             else
4912               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
4913                                            ShAmt);
4914
4915             if (Comp != CI) {// Comparing against a bit that we know is zero.
4916               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4917               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4918               return ReplaceInstUsesWith(I, Cst);
4919             }
4920
4921             if (LHSI->hasOneUse() || CI->isNullValue()) {
4922               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4923
4924               // Otherwise strength reduce the shift into an and.
4925               APInt Val(APInt::getAllOnesValue(TypeBits).shl(ShAmtVal));
4926               Constant *Mask = ConstantInt::get(Val);
4927
4928               Instruction *AndI =
4929                 BinaryOperator::createAnd(LHSI->getOperand(0),
4930                                           Mask, LHSI->getName()+".mask");
4931               Value *And = InsertNewInstBefore(AndI, I);
4932               return new ICmpInst(I.getPredicate(), And,
4933                                      ConstantExpr::getShl(CI, ShAmt));
4934             }
4935           }
4936         }
4937         break;
4938
4939       case Instruction::SDiv:
4940       case Instruction::UDiv:
4941         // Fold: icmp pred ([us]div X, C1), C2 -> range test
4942         // Fold this div into the comparison, producing a range check. 
4943         // Determine, based on the divide type, what the range is being 
4944         // checked.  If there is an overflow on the low or high side, remember 
4945         // it, otherwise compute the range [low, hi) bounding the new value.
4946         // See: InsertRangeTest above for the kinds of replacements possible.
4947         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4948           // FIXME: If the operand types don't match the type of the divide 
4949           // then don't attempt this transform. The code below doesn't have the
4950           // logic to deal with a signed divide and an unsigned compare (and
4951           // vice versa). This is because (x /s C1) <s C2  produces different 
4952           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4953           // (x /u C1) <u C2.  Simply casting the operands and result won't 
4954           // work. :(  The if statement below tests that condition and bails 
4955           // if it finds it. 
4956           bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4957           if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
4958             break;
4959           if (DivRHS->isZero())
4960             break; // Don't hack on div by zero
4961
4962           // Initialize the variables that will indicate the nature of the
4963           // range check.
4964           bool LoOverflow = false, HiOverflow = false;
4965           ConstantInt *LoBound = 0, *HiBound = 0;
4966
4967           // Compute Prod = CI * DivRHS. We are essentially solving an equation
4968           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
4969           // C2 (CI). By solving for X we can turn this into a range check 
4970           // instead of computing a divide. 
4971           ConstantInt *Prod = 
4972             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4973
4974           // Determine if the product overflows by seeing if the product is
4975           // not equal to the divide. Make sure we do the same kind of divide
4976           // as in the LHS instruction that we're folding. 
4977           bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
4978                                      ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4979
4980           // Get the ICmp opcode
4981           ICmpInst::Predicate predicate = I.getPredicate();
4982
4983           if (!DivIsSigned) {  // udiv
4984             LoBound = Prod;
4985             LoOverflow = ProdOV;
4986             HiOverflow = ProdOV || 
4987                          AddWithOverflow(HiBound, LoBound, DivRHS, false);
4988           } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
4989             if (CI->isNullValue()) {       // (X / pos) op 0
4990               // Can't overflow.
4991               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4992               HiBound = DivRHS;
4993             } else if (CI->getValue().isPositive()) {   // (X / pos) op pos
4994               LoBound = Prod;
4995               LoOverflow = ProdOV;
4996               HiOverflow = ProdOV || 
4997                            AddWithOverflow(HiBound, Prod, DivRHS, true);
4998             } else {                       // (X / pos) op neg
4999               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5000               LoOverflow = AddWithOverflow(LoBound, Prod,
5001                                            cast<ConstantInt>(DivRHSH), true);
5002               HiBound = AddOne(Prod);
5003               HiOverflow = ProdOV;
5004             }
5005           } else {                         // Divisor is < 0.
5006             if (CI->isNullValue()) {       // (X / neg) op 0
5007               LoBound = AddOne(DivRHS);
5008               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5009               if (HiBound == DivRHS)
5010                 LoBound = 0;               // - INTMIN = INTMIN
5011             } else if (CI->getValue().isPositive()) {   // (X / neg) op pos
5012               HiOverflow = LoOverflow = ProdOV;
5013               if (!LoOverflow)
5014                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
5015                                              true);
5016               HiBound = AddOne(Prod);
5017             } else {                       // (X / neg) op neg
5018               LoBound = Prod;
5019               LoOverflow = HiOverflow = ProdOV;
5020               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
5021             }
5022
5023             // Dividing by a negate swaps the condition.
5024             predicate = ICmpInst::getSwappedPredicate(predicate);
5025           }
5026
5027           if (LoBound) {
5028             Value *X = LHSI->getOperand(0);
5029             switch (predicate) {
5030             default: assert(0 && "Unhandled icmp opcode!");
5031             case ICmpInst::ICMP_EQ:
5032               if (LoOverflow && HiOverflow)
5033                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5034               else if (HiOverflow)
5035                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SGE : 
5036                                     ICmpInst::ICMP_UGE, X, LoBound);
5037               else if (LoOverflow)
5038                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5039                                     ICmpInst::ICMP_ULT, X, HiBound);
5040               else
5041                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
5042                                        true, I);
5043             case ICmpInst::ICMP_NE:
5044               if (LoOverflow && HiOverflow)
5045                 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5046               else if (HiOverflow)
5047                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SLT : 
5048                                     ICmpInst::ICMP_ULT, X, LoBound);
5049               else if (LoOverflow)
5050                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5051                                     ICmpInst::ICMP_UGE, X, HiBound);
5052               else
5053                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
5054                                        false, I);
5055             case ICmpInst::ICMP_ULT:
5056             case ICmpInst::ICMP_SLT:
5057               if (LoOverflow)
5058                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5059               return new ICmpInst(predicate, X, LoBound);
5060             case ICmpInst::ICMP_UGT:
5061             case ICmpInst::ICMP_SGT:
5062               if (HiOverflow)
5063                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5064               if (predicate == ICmpInst::ICMP_UGT)
5065                 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5066               else
5067                 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5068             }
5069           }
5070         }
5071         break;
5072       }
5073
5074     // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5075     if (I.isEquality()) {
5076       bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
5077
5078       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
5079       // the second operand is a constant, simplify a bit.
5080       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
5081         switch (BO->getOpcode()) {
5082         case Instruction::SRem:
5083           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5084           if (CI->isZero() && isa<ConstantInt>(BO->getOperand(1)) &&
5085               BO->hasOneUse()) {
5086             APInt V(cast<ConstantInt>(BO->getOperand(1))->getValue());
5087             if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5088               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
5089                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
5090               return new ICmpInst(I.getPredicate(), NewRem, 
5091                                   Constant::getNullValue(BO->getType()));
5092             }
5093           }
5094           break;
5095         case Instruction::Add:
5096           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5097           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5098             if (BO->hasOneUse())
5099               return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5100                                   ConstantExpr::getSub(CI, BOp1C));
5101           } else if (CI->isNullValue()) {
5102             // Replace ((add A, B) != 0) with (A != -B) if A or B is
5103             // efficiently invertible, or if the add has just this one use.
5104             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5105
5106             if (Value *NegVal = dyn_castNegVal(BOp1))
5107               return new ICmpInst(I.getPredicate(), BOp0, NegVal);
5108             else if (Value *NegVal = dyn_castNegVal(BOp0))
5109               return new ICmpInst(I.getPredicate(), NegVal, BOp1);
5110             else if (BO->hasOneUse()) {
5111               Instruction *Neg = BinaryOperator::createNeg(BOp1);
5112               InsertNewInstBefore(Neg, I);
5113               Neg->takeName(BO);
5114               return new ICmpInst(I.getPredicate(), BOp0, Neg);
5115             }
5116           }
5117           break;
5118         case Instruction::Xor:
5119           // For the xor case, we can xor two constants together, eliminating
5120           // the explicit xor.
5121           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5122             return new ICmpInst(I.getPredicate(), BO->getOperand(0), 
5123                                 ConstantExpr::getXor(CI, BOC));
5124
5125           // FALLTHROUGH
5126         case Instruction::Sub:
5127           // Replace (([sub|xor] A, B) != 0) with (A != B)
5128           if (CI->isZero())
5129             return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5130                                 BO->getOperand(1));
5131           break;
5132
5133         case Instruction::Or:
5134           // If bits are being or'd in that are not present in the constant we
5135           // are comparing against, then the comparison could never succeed!
5136           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5137             Constant *NotCI = ConstantExpr::getNot(CI);
5138             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5139               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5140                                                              isICMP_NE));
5141           }
5142           break;
5143
5144         case Instruction::And:
5145           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5146             // If bits are being compared against that are and'd out, then the
5147             // comparison can never succeed!
5148             if (!ConstantExpr::getAnd(CI,
5149                                       ConstantExpr::getNot(BOC))->isNullValue())
5150               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5151                                                              isICMP_NE));
5152
5153             // If we have ((X & C) == C), turn it into ((X & C) != 0).
5154             if (CI == BOC && isOneBitSet(CI))
5155               return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5156                                   ICmpInst::ICMP_NE, Op0,
5157                                   Constant::getNullValue(CI->getType()));
5158
5159             // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5160             if (isSignBit(BOC)) {
5161               Value *X = BO->getOperand(0);
5162               Constant *Zero = Constant::getNullValue(X->getType());
5163               ICmpInst::Predicate pred = isICMP_NE ? 
5164                 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5165               return new ICmpInst(pred, X, Zero);
5166             }
5167
5168             // ((X & ~7) == 0) --> X < 8
5169             if (CI->isNullValue() && isHighOnes(BOC)) {
5170               Value *X = BO->getOperand(0);
5171               Constant *NegX = ConstantExpr::getNeg(BOC);
5172               ICmpInst::Predicate pred = isICMP_NE ? 
5173                 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5174               return new ICmpInst(pred, X, NegX);
5175             }
5176
5177           }
5178         default: break;
5179         }
5180       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5181         // Handle set{eq|ne} <intrinsic>, intcst.
5182         switch (II->getIntrinsicID()) {
5183         default: break;
5184         case Intrinsic::bswap_i16: 
5185           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5186           AddToWorkList(II);  // Dead?
5187           I.setOperand(0, II->getOperand(1));
5188           I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5189                                            ByteSwap_16(CI->getZExtValue())));
5190           return &I;
5191         case Intrinsic::bswap_i32:   
5192           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5193           AddToWorkList(II);  // Dead?
5194           I.setOperand(0, II->getOperand(1));
5195           I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5196                                            ByteSwap_32(CI->getZExtValue())));
5197           return &I;
5198         case Intrinsic::bswap_i64:   
5199           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5200           AddToWorkList(II);  // Dead?
5201           I.setOperand(0, II->getOperand(1));
5202           I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5203                                            ByteSwap_64(CI->getZExtValue())));
5204           return &I;
5205         }
5206       }
5207     } else {  // Not a ICMP_EQ/ICMP_NE
5208       // If the LHS is a cast from an integral value of the same size, then 
5209       // since we know the RHS is a constant, try to simlify.
5210       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5211         Value *CastOp = Cast->getOperand(0);
5212         const Type *SrcTy = CastOp->getType();
5213         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5214         if (SrcTy->isInteger() && 
5215             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5216           // If this is an unsigned comparison, try to make the comparison use
5217           // smaller constant values.
5218           switch (I.getPredicate()) {
5219             default: break;
5220             case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5221               ConstantInt *CUI = cast<ConstantInt>(CI);
5222               if (CUI->getValue() == APInt::getSignBit(SrcTySize))
5223                 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5224                   ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5225               break;
5226             }
5227             case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5228               ConstantInt *CUI = cast<ConstantInt>(CI);
5229               if (CUI->getValue() == APInt::getSignedMaxValue(SrcTySize))
5230                 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5231                                     Constant::getNullValue(SrcTy));
5232               break;
5233             }
5234           }
5235
5236         }
5237       }
5238     }
5239   }
5240
5241   // Handle icmp with constant RHS
5242   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5243     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5244       switch (LHSI->getOpcode()) {
5245       case Instruction::GetElementPtr:
5246         if (RHSC->isNullValue()) {
5247           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5248           bool isAllZeros = true;
5249           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5250             if (!isa<Constant>(LHSI->getOperand(i)) ||
5251                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5252               isAllZeros = false;
5253               break;
5254             }
5255           if (isAllZeros)
5256             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5257                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5258         }
5259         break;
5260
5261       case Instruction::PHI:
5262         if (Instruction *NV = FoldOpIntoPhi(I))
5263           return NV;
5264         break;
5265       case Instruction::Select:
5266         // If either operand of the select is a constant, we can fold the
5267         // comparison into the select arms, which will cause one to be
5268         // constant folded and the select turned into a bitwise or.
5269         Value *Op1 = 0, *Op2 = 0;
5270         if (LHSI->hasOneUse()) {
5271           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5272             // Fold the known value into the constant operand.
5273             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5274             // Insert a new ICmp of the other select operand.
5275             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5276                                                    LHSI->getOperand(2), RHSC,
5277                                                    I.getName()), I);
5278           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5279             // Fold the known value into the constant operand.
5280             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5281             // Insert a new ICmp of the other select operand.
5282             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5283                                                    LHSI->getOperand(1), RHSC,
5284                                                    I.getName()), I);
5285           }
5286         }
5287
5288         if (Op1)
5289           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5290         break;
5291       }
5292   }
5293
5294   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5295   if (User *GEP = dyn_castGetElementPtr(Op0))
5296     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5297       return NI;
5298   if (User *GEP = dyn_castGetElementPtr(Op1))
5299     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5300                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5301       return NI;
5302
5303   // Test to see if the operands of the icmp are casted versions of other
5304   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5305   // now.
5306   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5307     if (isa<PointerType>(Op0->getType()) && 
5308         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5309       // We keep moving the cast from the left operand over to the right
5310       // operand, where it can often be eliminated completely.
5311       Op0 = CI->getOperand(0);
5312
5313       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5314       // so eliminate it as well.
5315       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5316         Op1 = CI2->getOperand(0);
5317
5318       // If Op1 is a constant, we can fold the cast into the constant.
5319       if (Op0->getType() != Op1->getType())
5320         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5321           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5322         } else {
5323           // Otherwise, cast the RHS right before the icmp
5324           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5325         }
5326       return new ICmpInst(I.getPredicate(), Op0, Op1);
5327     }
5328   }
5329   
5330   if (isa<CastInst>(Op0)) {
5331     // Handle the special case of: icmp (cast bool to X), <cst>
5332     // This comes up when you have code like
5333     //   int X = A < B;
5334     //   if (X) ...
5335     // For generality, we handle any zero-extension of any operand comparison
5336     // with a constant or another cast from the same type.
5337     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5338       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5339         return R;
5340   }
5341   
5342   if (I.isEquality()) {
5343     Value *A, *B, *C, *D;
5344     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5345       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5346         Value *OtherVal = A == Op1 ? B : A;
5347         return new ICmpInst(I.getPredicate(), OtherVal,
5348                             Constant::getNullValue(A->getType()));
5349       }
5350
5351       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5352         // A^c1 == C^c2 --> A == C^(c1^c2)
5353         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5354           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5355             if (Op1->hasOneUse()) {
5356               Constant *NC = ConstantExpr::getXor(C1, C2);
5357               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5358               return new ICmpInst(I.getPredicate(), A,
5359                                   InsertNewInstBefore(Xor, I));
5360             }
5361         
5362         // A^B == A^D -> B == D
5363         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5364         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5365         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5366         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5367       }
5368     }
5369     
5370     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5371         (A == Op0 || B == Op0)) {
5372       // A == (A^B)  ->  B == 0
5373       Value *OtherVal = A == Op0 ? B : A;
5374       return new ICmpInst(I.getPredicate(), OtherVal,
5375                           Constant::getNullValue(A->getType()));
5376     }
5377     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5378       // (A-B) == A  ->  B == 0
5379       return new ICmpInst(I.getPredicate(), B,
5380                           Constant::getNullValue(B->getType()));
5381     }
5382     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5383       // A == (A-B)  ->  B == 0
5384       return new ICmpInst(I.getPredicate(), B,
5385                           Constant::getNullValue(B->getType()));
5386     }
5387     
5388     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5389     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5390         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5391         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5392       Value *X = 0, *Y = 0, *Z = 0;
5393       
5394       if (A == C) {
5395         X = B; Y = D; Z = A;
5396       } else if (A == D) {
5397         X = B; Y = C; Z = A;
5398       } else if (B == C) {
5399         X = A; Y = D; Z = B;
5400       } else if (B == D) {
5401         X = A; Y = C; Z = B;
5402       }
5403       
5404       if (X) {   // Build (X^Y) & Z
5405         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5406         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5407         I.setOperand(0, Op1);
5408         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5409         return &I;
5410       }
5411     }
5412   }
5413   return Changed ? &I : 0;
5414 }
5415
5416 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5417 // We only handle extending casts so far.
5418 //
5419 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5420   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5421   Value *LHSCIOp        = LHSCI->getOperand(0);
5422   const Type *SrcTy     = LHSCIOp->getType();
5423   const Type *DestTy    = LHSCI->getType();
5424   Value *RHSCIOp;
5425
5426   // We only handle extension cast instructions, so far. Enforce this.
5427   if (LHSCI->getOpcode() != Instruction::ZExt &&
5428       LHSCI->getOpcode() != Instruction::SExt)
5429     return 0;
5430
5431   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5432   bool isSignedCmp = ICI.isSignedPredicate();
5433
5434   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5435     // Not an extension from the same type?
5436     RHSCIOp = CI->getOperand(0);
5437     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5438       return 0;
5439     
5440     // If the signedness of the two compares doesn't agree (i.e. one is a sext
5441     // and the other is a zext), then we can't handle this.
5442     if (CI->getOpcode() != LHSCI->getOpcode())
5443       return 0;
5444
5445     // Likewise, if the signedness of the [sz]exts and the compare don't match, 
5446     // then we can't handle this.
5447     if (isSignedExt != isSignedCmp && !ICI.isEquality())
5448       return 0;
5449     
5450     // Okay, just insert a compare of the reduced operands now!
5451     return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5452   }
5453
5454   // If we aren't dealing with a constant on the RHS, exit early
5455   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5456   if (!CI)
5457     return 0;
5458
5459   // Compute the constant that would happen if we truncated to SrcTy then
5460   // reextended to DestTy.
5461   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5462   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5463
5464   // If the re-extended constant didn't change...
5465   if (Res2 == CI) {
5466     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5467     // For example, we might have:
5468     //    %A = sext short %X to uint
5469     //    %B = icmp ugt uint %A, 1330
5470     // It is incorrect to transform this into 
5471     //    %B = icmp ugt short %X, 1330 
5472     // because %A may have negative value. 
5473     //
5474     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5475     // OR operation is EQ/NE.
5476     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5477       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5478     else
5479       return 0;
5480   }
5481
5482   // The re-extended constant changed so the constant cannot be represented 
5483   // in the shorter type. Consequently, we cannot emit a simple comparison.
5484
5485   // First, handle some easy cases. We know the result cannot be equal at this
5486   // point so handle the ICI.isEquality() cases
5487   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5488     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5489   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5490     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5491
5492   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5493   // should have been folded away previously and not enter in here.
5494   Value *Result;
5495   if (isSignedCmp) {
5496     // We're performing a signed comparison.
5497     if (cast<ConstantInt>(CI)->getValue().isNegative())
5498       Result = ConstantInt::getFalse();          // X < (small) --> false
5499     else
5500       Result = ConstantInt::getTrue();           // X < (large) --> true
5501   } else {
5502     // We're performing an unsigned comparison.
5503     if (isSignedExt) {
5504       // We're performing an unsigned comp with a sign extended value.
5505       // This is true if the input is >= 0. [aka >s -1]
5506       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5507       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5508                                    NegOne, ICI.getName()), ICI);
5509     } else {
5510       // Unsigned extend & unsigned compare -> always true.
5511       Result = ConstantInt::getTrue();
5512     }
5513   }
5514
5515   // Finally, return the value computed.
5516   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5517       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5518     return ReplaceInstUsesWith(ICI, Result);
5519   } else {
5520     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5521             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5522            "ICmp should be folded!");
5523     if (Constant *CI = dyn_cast<Constant>(Result))
5524       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5525     else
5526       return BinaryOperator::createNot(Result);
5527   }
5528 }
5529
5530 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5531   return commonShiftTransforms(I);
5532 }
5533
5534 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5535   return commonShiftTransforms(I);
5536 }
5537
5538 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5539   return commonShiftTransforms(I);
5540 }
5541
5542 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5543   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
5544   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5545
5546   // shl X, 0 == X and shr X, 0 == X
5547   // shl 0, X == 0 and shr 0, X == 0
5548   if (Op1 == Constant::getNullValue(Op1->getType()) ||
5549       Op0 == Constant::getNullValue(Op0->getType()))
5550     return ReplaceInstUsesWith(I, Op0);
5551   
5552   if (isa<UndefValue>(Op0)) {            
5553     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5554       return ReplaceInstUsesWith(I, Op0);
5555     else                                    // undef << X -> 0, undef >>u X -> 0
5556       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5557   }
5558   if (isa<UndefValue>(Op1)) {
5559     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5560       return ReplaceInstUsesWith(I, Op0);          
5561     else                                     // X << undef, X >>u undef -> 0
5562       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5563   }
5564
5565   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5566   if (I.getOpcode() == Instruction::AShr)
5567     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5568       if (CSI->isAllOnesValue())
5569         return ReplaceInstUsesWith(I, CSI);
5570
5571   // Try to fold constant and into select arguments.
5572   if (isa<Constant>(Op0))
5573     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5574       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5575         return R;
5576
5577   // See if we can turn a signed shr into an unsigned shr.
5578   if (I.isArithmeticShift()) {
5579     if (MaskedValueIsZero(Op0, 
5580           APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
5581       return BinaryOperator::createLShr(Op0, Op1, I.getName());
5582     }
5583   }
5584
5585   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5586     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5587       return Res;
5588   return 0;
5589 }
5590
5591 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5592                                                BinaryOperator &I) {
5593   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5594
5595   // See if we can simplify any instructions used by the instruction whose sole 
5596   // purpose is to compute bits we don't care about.
5597   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5598   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5599   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
5600                            KnownZero, KnownOne))
5601     return &I;
5602   
5603   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5604   // of a signed value.
5605   //
5606   if (Op1->getZExtValue() >= TypeBits) {  // shift amount always <= 32 bits
5607     if (I.getOpcode() != Instruction::AShr)
5608       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5609     else {
5610       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
5611       return &I;
5612     }
5613   }
5614   
5615   // ((X*C1) << C2) == (X * (C1 << C2))
5616   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5617     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5618       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5619         return BinaryOperator::createMul(BO->getOperand(0),
5620                                          ConstantExpr::getShl(BOOp, Op1));
5621   
5622   // Try to fold constant and into select arguments.
5623   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5624     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5625       return R;
5626   if (isa<PHINode>(Op0))
5627     if (Instruction *NV = FoldOpIntoPhi(I))
5628       return NV;
5629   
5630   if (Op0->hasOneUse()) {
5631     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5632       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5633       Value *V1, *V2;
5634       ConstantInt *CC;
5635       switch (Op0BO->getOpcode()) {
5636         default: break;
5637         case Instruction::Add:
5638         case Instruction::And:
5639         case Instruction::Or:
5640         case Instruction::Xor: {
5641           // These operators commute.
5642           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5643           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5644               match(Op0BO->getOperand(1),
5645                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5646             Instruction *YS = BinaryOperator::createShl(
5647                                             Op0BO->getOperand(0), Op1,
5648                                             Op0BO->getName());
5649             InsertNewInstBefore(YS, I); // (Y << C)
5650             Instruction *X = 
5651               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5652                                      Op0BO->getOperand(1)->getName());
5653             InsertNewInstBefore(X, I);  // (X + (Y << C))
5654             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5655             C2 = ConstantExpr::getShl(C2, Op1);
5656             return BinaryOperator::createAnd(X, C2);
5657           }
5658           
5659           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5660           Value *Op0BOOp1 = Op0BO->getOperand(1);
5661           if (isLeftShift && Op0BOOp1->hasOneUse() &&
5662               match(Op0BOOp1, 
5663                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
5664               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5665               V2 == Op1) {
5666             Instruction *YS = BinaryOperator::createShl(
5667                                                      Op0BO->getOperand(0), Op1,
5668                                                      Op0BO->getName());
5669             InsertNewInstBefore(YS, I); // (Y << C)
5670             Instruction *XM =
5671               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5672                                         V1->getName()+".mask");
5673             InsertNewInstBefore(XM, I); // X & (CC << C)
5674             
5675             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5676           }
5677         }
5678           
5679         // FALL THROUGH.
5680         case Instruction::Sub: {
5681           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5682           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5683               match(Op0BO->getOperand(0),
5684                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5685             Instruction *YS = BinaryOperator::createShl(
5686                                                      Op0BO->getOperand(1), Op1,
5687                                                      Op0BO->getName());
5688             InsertNewInstBefore(YS, I); // (Y << C)
5689             Instruction *X =
5690               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5691                                      Op0BO->getOperand(0)->getName());
5692             InsertNewInstBefore(X, I);  // (X + (Y << C))
5693             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5694             C2 = ConstantExpr::getShl(C2, Op1);
5695             return BinaryOperator::createAnd(X, C2);
5696           }
5697           
5698           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5699           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5700               match(Op0BO->getOperand(0),
5701                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5702                           m_ConstantInt(CC))) && V2 == Op1 &&
5703               cast<BinaryOperator>(Op0BO->getOperand(0))
5704                   ->getOperand(0)->hasOneUse()) {
5705             Instruction *YS = BinaryOperator::createShl(
5706                                                      Op0BO->getOperand(1), Op1,
5707                                                      Op0BO->getName());
5708             InsertNewInstBefore(YS, I); // (Y << C)
5709             Instruction *XM =
5710               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5711                                         V1->getName()+".mask");
5712             InsertNewInstBefore(XM, I); // X & (CC << C)
5713             
5714             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5715           }
5716           
5717           break;
5718         }
5719       }
5720       
5721       
5722       // If the operand is an bitwise operator with a constant RHS, and the
5723       // shift is the only use, we can pull it out of the shift.
5724       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5725         bool isValid = true;     // Valid only for And, Or, Xor
5726         bool highBitSet = false; // Transform if high bit of constant set?
5727         
5728         switch (Op0BO->getOpcode()) {
5729           default: isValid = false; break;   // Do not perform transform!
5730           case Instruction::Add:
5731             isValid = isLeftShift;
5732             break;
5733           case Instruction::Or:
5734           case Instruction::Xor:
5735             highBitSet = false;
5736             break;
5737           case Instruction::And:
5738             highBitSet = true;
5739             break;
5740         }
5741         
5742         // If this is a signed shift right, and the high bit is modified
5743         // by the logical operation, do not perform the transformation.
5744         // The highBitSet boolean indicates the value of the high bit of
5745         // the constant which would cause it to be modified for this
5746         // operation.
5747         //
5748         if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
5749           isValid = ((Op0C->getValue() & APInt::getSignBit(TypeBits)) != 0) == 
5750                     highBitSet;
5751         }
5752         
5753         if (isValid) {
5754           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5755           
5756           Instruction *NewShift =
5757             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
5758           InsertNewInstBefore(NewShift, I);
5759           NewShift->takeName(Op0BO);
5760           
5761           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5762                                         NewRHS);
5763         }
5764       }
5765     }
5766   }
5767   
5768   // Find out if this is a shift of a shift by a constant.
5769   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5770   if (ShiftOp && !ShiftOp->isShift())
5771     ShiftOp = 0;
5772   
5773   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5774     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5775     // These shift amounts are always <= 32 bits.
5776     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5777     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5778     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5779     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
5780     Value *X = ShiftOp->getOperand(0);
5781     
5782     unsigned AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5783     if (AmtSum > TypeBits)
5784       AmtSum = TypeBits;
5785     
5786     const IntegerType *Ty = cast<IntegerType>(I.getType());
5787     
5788     // Check for (X << c1) << c2  and  (X >> c1) >> c2
5789     if (I.getOpcode() == ShiftOp->getOpcode()) {
5790       return BinaryOperator::create(I.getOpcode(), X,
5791                                     ConstantInt::get(Ty, AmtSum));
5792     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5793                I.getOpcode() == Instruction::AShr) {
5794       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
5795       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5796     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5797                I.getOpcode() == Instruction::LShr) {
5798       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5799       Instruction *Shift =
5800         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5801       InsertNewInstBefore(Shift, I);
5802
5803       APInt Mask(Ty->getMask().lshr(ShiftAmt2));
5804       return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
5805     }
5806     
5807     // Okay, if we get here, one shift must be left, and the other shift must be
5808     // right.  See if the amounts are equal.
5809     if (ShiftAmt1 == ShiftAmt2) {
5810       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5811       if (I.getOpcode() == Instruction::Shl) {
5812         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
5813         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
5814       }
5815       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5816       if (I.getOpcode() == Instruction::LShr) {
5817         APInt Mask(Ty->getMask().lshr(ShiftAmt1));
5818         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
5819       }
5820       // We can simplify ((X << C) >>s C) into a trunc + sext.
5821       // NOTE: we could do this for any C, but that would make 'unusual' integer
5822       // types.  For now, just stick to ones well-supported by the code
5823       // generators.
5824       const Type *SExtType = 0;
5825       switch (Ty->getBitWidth() - ShiftAmt1) {
5826       case 1  : SExtType = Type::Int1Ty; break;
5827       case 8  : SExtType = Type::Int8Ty; break;
5828       case 16 : SExtType = Type::Int16Ty; break;
5829       case 32 : SExtType = Type::Int32Ty; break;
5830       case 64 : SExtType = Type::Int64Ty; break;
5831       default: break;
5832       }
5833       if (SExtType) {
5834         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5835         InsertNewInstBefore(NewTrunc, I);
5836         return new SExtInst(NewTrunc, Ty);
5837       }
5838       // Otherwise, we can't handle it yet.
5839     } else if (ShiftAmt1 < ShiftAmt2) {
5840       unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
5841       
5842       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
5843       if (I.getOpcode() == Instruction::Shl) {
5844         assert(ShiftOp->getOpcode() == Instruction::LShr ||
5845                ShiftOp->getOpcode() == Instruction::AShr);
5846         Instruction *Shift =
5847           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5848         InsertNewInstBefore(Shift, I);
5849         
5850         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
5851         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
5852       }
5853       
5854       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
5855       if (I.getOpcode() == Instruction::LShr) {
5856         assert(ShiftOp->getOpcode() == Instruction::Shl);
5857         Instruction *Shift =
5858           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5859         InsertNewInstBefore(Shift, I);
5860         
5861         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
5862         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
5863       }
5864       
5865       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5866     } else {
5867       assert(ShiftAmt2 < ShiftAmt1);
5868       unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
5869
5870       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
5871       if (I.getOpcode() == Instruction::Shl) {
5872         assert(ShiftOp->getOpcode() == Instruction::LShr ||
5873                ShiftOp->getOpcode() == Instruction::AShr);
5874         Instruction *Shift =
5875           BinaryOperator::create(ShiftOp->getOpcode(), X,
5876                                  ConstantInt::get(Ty, ShiftDiff));
5877         InsertNewInstBefore(Shift, I);
5878         
5879         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
5880         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
5881       }
5882       
5883       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
5884       if (I.getOpcode() == Instruction::LShr) {
5885         assert(ShiftOp->getOpcode() == Instruction::Shl);
5886         Instruction *Shift =
5887           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5888         InsertNewInstBefore(Shift, I);
5889         
5890         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
5891         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
5892       }
5893       
5894       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
5895     }
5896   }
5897   return 0;
5898 }
5899
5900
5901 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5902 /// expression.  If so, decompose it, returning some value X, such that Val is
5903 /// X*Scale+Offset.
5904 ///
5905 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5906                                         unsigned &Offset) {
5907   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
5908   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5909     Offset = CI->getZExtValue();
5910     Scale  = 1;
5911     return ConstantInt::get(Type::Int32Ty, 0);
5912   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5913     if (I->getNumOperands() == 2) {
5914       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5915         if (I->getOpcode() == Instruction::Shl) {
5916           // This is a value scaled by '1 << the shift amt'.
5917           Scale = 1U << CUI->getZExtValue();
5918           Offset = 0;
5919           return I->getOperand(0);
5920         } else if (I->getOpcode() == Instruction::Mul) {
5921           // This value is scaled by 'CUI'.
5922           Scale = CUI->getZExtValue();
5923           Offset = 0;
5924           return I->getOperand(0);
5925         } else if (I->getOpcode() == Instruction::Add) {
5926           // We have X+C.  Check to see if we really have (X*C2)+C1, 
5927           // where C1 is divisible by C2.
5928           unsigned SubScale;
5929           Value *SubVal = 
5930             DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5931           Offset += CUI->getZExtValue();
5932           if (SubScale > 1 && (Offset % SubScale == 0)) {
5933             Scale = SubScale;
5934             return SubVal;
5935           }
5936         }
5937       }
5938     }
5939   }
5940
5941   // Otherwise, we can't look past this.
5942   Scale = 1;
5943   Offset = 0;
5944   return Val;
5945 }
5946
5947
5948 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5949 /// try to eliminate the cast by moving the type information into the alloc.
5950 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5951                                                    AllocationInst &AI) {
5952   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5953   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
5954   
5955   // Remove any uses of AI that are dead.
5956   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5957   
5958   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5959     Instruction *User = cast<Instruction>(*UI++);
5960     if (isInstructionTriviallyDead(User)) {
5961       while (UI != E && *UI == User)
5962         ++UI; // If this instruction uses AI more than once, don't break UI.
5963       
5964       ++NumDeadInst;
5965       DOUT << "IC: DCE: " << *User;
5966       EraseInstFromFunction(*User);
5967     }
5968   }
5969   
5970   // Get the type really allocated and the type casted to.
5971   const Type *AllocElTy = AI.getAllocatedType();
5972   const Type *CastElTy = PTy->getElementType();
5973   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5974
5975   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
5976   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
5977   if (CastElTyAlign < AllocElTyAlign) return 0;
5978
5979   // If the allocation has multiple uses, only promote it if we are strictly
5980   // increasing the alignment of the resultant allocation.  If we keep it the
5981   // same, we open the door to infinite loops of various kinds.
5982   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5983
5984   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5985   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5986   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5987
5988   // See if we can satisfy the modulus by pulling a scale out of the array
5989   // size argument.
5990   unsigned ArraySizeScale, ArrayOffset;
5991   Value *NumElements = // See if the array size is a decomposable linear expr.
5992     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5993  
5994   // If we can now satisfy the modulus, by using a non-1 scale, we really can
5995   // do the xform.
5996   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5997       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
5998
5999   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6000   Value *Amt = 0;
6001   if (Scale == 1) {
6002     Amt = NumElements;
6003   } else {
6004     // If the allocation size is constant, form a constant mul expression
6005     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6006     if (isa<ConstantInt>(NumElements))
6007       Amt = ConstantExpr::getMul(
6008               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6009     // otherwise multiply the amount and the number of elements
6010     else if (Scale != 1) {
6011       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6012       Amt = InsertNewInstBefore(Tmp, AI);
6013     }
6014   }
6015   
6016   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6017     Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
6018     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6019     Amt = InsertNewInstBefore(Tmp, AI);
6020   }
6021   
6022   AllocationInst *New;
6023   if (isa<MallocInst>(AI))
6024     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6025   else
6026     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6027   InsertNewInstBefore(New, AI);
6028   New->takeName(&AI);
6029   
6030   // If the allocation has multiple uses, insert a cast and change all things
6031   // that used it to use the new cast.  This will also hack on CI, but it will
6032   // die soon.
6033   if (!AI.hasOneUse()) {
6034     AddUsesToWorkList(AI);
6035     // New is the allocation instruction, pointer typed. AI is the original
6036     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6037     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6038     InsertNewInstBefore(NewCast, AI);
6039     AI.replaceAllUsesWith(NewCast);
6040   }
6041   return ReplaceInstUsesWith(CI, New);
6042 }
6043
6044 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6045 /// and return it as type Ty without inserting any new casts and without
6046 /// changing the computed value.  This is used by code that tries to decide
6047 /// whether promoting or shrinking integer operations to wider or smaller types
6048 /// will allow us to eliminate a truncate or extend.
6049 ///
6050 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6051 /// extension operation if Ty is larger.
6052 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6053                                        int &NumCastsRemoved) {
6054   // We can always evaluate constants in another type.
6055   if (isa<ConstantInt>(V))
6056     return true;
6057   
6058   Instruction *I = dyn_cast<Instruction>(V);
6059   if (!I) return false;
6060   
6061   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6062   
6063   switch (I->getOpcode()) {
6064   case Instruction::Add:
6065   case Instruction::Sub:
6066   case Instruction::And:
6067   case Instruction::Or:
6068   case Instruction::Xor:
6069     if (!I->hasOneUse()) return false;
6070     // These operators can all arbitrarily be extended or truncated.
6071     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6072            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
6073
6074   case Instruction::Shl:
6075     if (!I->hasOneUse()) return false;
6076     // If we are truncating the result of this SHL, and if it's a shift of a
6077     // constant amount, we can always perform a SHL in a smaller type.
6078     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6079       if (Ty->getBitWidth() < OrigTy->getBitWidth() &&
6080           CI->getZExtValue() < Ty->getBitWidth())
6081         return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6082     }
6083     break;
6084   case Instruction::LShr:
6085     if (!I->hasOneUse()) return false;
6086     // If this is a truncate of a logical shr, we can truncate it to a smaller
6087     // lshr iff we know that the bits we would otherwise be shifting in are
6088     // already zeros.
6089     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6090       uint32_t BitWidth = OrigTy->getBitWidth();
6091       if (Ty->getBitWidth() < BitWidth &&
6092           MaskedValueIsZero(I->getOperand(0),
6093             APInt::getAllOnesValue(BitWidth) & 
6094          APInt::getAllOnesValue(Ty->getBitWidth()).zextOrTrunc(BitWidth).flip())
6095          && CI->getZExtValue() < Ty->getBitWidth()) {
6096         return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
6097       }
6098     }
6099     break;
6100   case Instruction::Trunc:
6101   case Instruction::ZExt:
6102   case Instruction::SExt:
6103     // If this is a cast from the destination type, we can trivially eliminate
6104     // it, and this will remove a cast overall.
6105     if (I->getOperand(0)->getType() == Ty) {
6106       // If the first operand is itself a cast, and is eliminable, do not count
6107       // this as an eliminable cast.  We would prefer to eliminate those two
6108       // casts first.
6109       if (isa<CastInst>(I->getOperand(0)))
6110         return true;
6111       
6112       ++NumCastsRemoved;
6113       return true;
6114     }
6115     break;
6116   default:
6117     // TODO: Can handle more cases here.
6118     break;
6119   }
6120   
6121   return false;
6122 }
6123
6124 /// EvaluateInDifferentType - Given an expression that 
6125 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6126 /// evaluate the expression.
6127 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6128                                              bool isSigned) {
6129   if (Constant *C = dyn_cast<Constant>(V))
6130     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6131
6132   // Otherwise, it must be an instruction.
6133   Instruction *I = cast<Instruction>(V);
6134   Instruction *Res = 0;
6135   switch (I->getOpcode()) {
6136   case Instruction::Add:
6137   case Instruction::Sub:
6138   case Instruction::And:
6139   case Instruction::Or:
6140   case Instruction::Xor:
6141   case Instruction::AShr:
6142   case Instruction::LShr:
6143   case Instruction::Shl: {
6144     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6145     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6146     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6147                                  LHS, RHS, I->getName());
6148     break;
6149   }    
6150   case Instruction::Trunc:
6151   case Instruction::ZExt:
6152   case Instruction::SExt:
6153   case Instruction::BitCast:
6154     // If the source type of the cast is the type we're trying for then we can
6155     // just return the source. There's no need to insert it because its not new.
6156     if (I->getOperand(0)->getType() == Ty)
6157       return I->getOperand(0);
6158     
6159     // Some other kind of cast, which shouldn't happen, so just ..
6160     // FALL THROUGH
6161   default: 
6162     // TODO: Can handle more cases here.
6163     assert(0 && "Unreachable!");
6164     break;
6165   }
6166   
6167   return InsertNewInstBefore(Res, *I);
6168 }
6169
6170 /// @brief Implement the transforms common to all CastInst visitors.
6171 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6172   Value *Src = CI.getOperand(0);
6173
6174   // Casting undef to anything results in undef so might as just replace it and
6175   // get rid of the cast.
6176   if (isa<UndefValue>(Src))   // cast undef -> undef
6177     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6178
6179   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6180   // eliminate it now.
6181   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6182     if (Instruction::CastOps opc = 
6183         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6184       // The first cast (CSrc) is eliminable so we need to fix up or replace
6185       // the second cast (CI). CSrc will then have a good chance of being dead.
6186       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6187     }
6188   }
6189
6190   // If casting the result of a getelementptr instruction with no offset, turn
6191   // this into a cast of the original pointer!
6192   //
6193   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6194     bool AllZeroOperands = true;
6195     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6196       if (!isa<Constant>(GEP->getOperand(i)) ||
6197           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6198         AllZeroOperands = false;
6199         break;
6200       }
6201     if (AllZeroOperands) {
6202       // Changing the cast operand is usually not a good idea but it is safe
6203       // here because the pointer operand is being replaced with another 
6204       // pointer operand so the opcode doesn't need to change.
6205       CI.setOperand(0, GEP->getOperand(0));
6206       return &CI;
6207     }
6208   }
6209     
6210   // If we are casting a malloc or alloca to a pointer to a type of the same
6211   // size, rewrite the allocation instruction to allocate the "right" type.
6212   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
6213     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6214       return V;
6215
6216   // If we are casting a select then fold the cast into the select
6217   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6218     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6219       return NV;
6220
6221   // If we are casting a PHI then fold the cast into the PHI
6222   if (isa<PHINode>(Src))
6223     if (Instruction *NV = FoldOpIntoPhi(CI))
6224       return NV;
6225   
6226   return 0;
6227 }
6228
6229 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6230 /// integer types. This function implements the common transforms for all those
6231 /// cases.
6232 /// @brief Implement the transforms common to CastInst with integer operands
6233 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6234   if (Instruction *Result = commonCastTransforms(CI))
6235     return Result;
6236
6237   Value *Src = CI.getOperand(0);
6238   const Type *SrcTy = Src->getType();
6239   const Type *DestTy = CI.getType();
6240   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6241   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6242
6243   // See if we can simplify any instructions used by the LHS whose sole 
6244   // purpose is to compute bits we don't care about.
6245   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6246   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6247                            KnownZero, KnownOne))
6248     return &CI;
6249
6250   // If the source isn't an instruction or has more than one use then we
6251   // can't do anything more. 
6252   Instruction *SrcI = dyn_cast<Instruction>(Src);
6253   if (!SrcI || !Src->hasOneUse())
6254     return 0;
6255
6256   // Attempt to propagate the cast into the instruction for int->int casts.
6257   int NumCastsRemoved = 0;
6258   if (!isa<BitCastInst>(CI) &&
6259       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6260                                  NumCastsRemoved)) {
6261     // If this cast is a truncate, evaluting in a different type always
6262     // eliminates the cast, so it is always a win.  If this is a noop-cast
6263     // this just removes a noop cast which isn't pointful, but simplifies
6264     // the code.  If this is a zero-extension, we need to do an AND to
6265     // maintain the clear top-part of the computation, so we require that
6266     // the input have eliminated at least one cast.  If this is a sign
6267     // extension, we insert two new casts (to do the extension) so we
6268     // require that two casts have been eliminated.
6269     bool DoXForm;
6270     switch (CI.getOpcode()) {
6271     default:
6272       // All the others use floating point so we shouldn't actually 
6273       // get here because of the check above.
6274       assert(0 && "Unknown cast type");
6275     case Instruction::Trunc:
6276       DoXForm = true;
6277       break;
6278     case Instruction::ZExt:
6279       DoXForm = NumCastsRemoved >= 1;
6280       break;
6281     case Instruction::SExt:
6282       DoXForm = NumCastsRemoved >= 2;
6283       break;
6284     case Instruction::BitCast:
6285       DoXForm = false;
6286       break;
6287     }
6288     
6289     if (DoXForm) {
6290       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6291                                            CI.getOpcode() == Instruction::SExt);
6292       assert(Res->getType() == DestTy);
6293       switch (CI.getOpcode()) {
6294       default: assert(0 && "Unknown cast type!");
6295       case Instruction::Trunc:
6296       case Instruction::BitCast:
6297         // Just replace this cast with the result.
6298         return ReplaceInstUsesWith(CI, Res);
6299       case Instruction::ZExt: {
6300         // We need to emit an AND to clear the high bits.
6301         assert(SrcBitSize < DestBitSize && "Not a zext?");
6302         Constant *C = ConstantInt::get(APInt::getAllOnesValue(SrcBitSize));
6303         C = ConstantExpr::getZExt(C, DestTy);
6304         return BinaryOperator::createAnd(Res, C);
6305       }
6306       case Instruction::SExt:
6307         // We need to emit a cast to truncate, then a cast to sext.
6308         return CastInst::create(Instruction::SExt,
6309             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6310                              CI), DestTy);
6311       }
6312     }
6313   }
6314   
6315   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6316   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6317
6318   switch (SrcI->getOpcode()) {
6319   case Instruction::Add:
6320   case Instruction::Mul:
6321   case Instruction::And:
6322   case Instruction::Or:
6323   case Instruction::Xor:
6324     // If we are discarding information, or just changing the sign, 
6325     // rewrite.
6326     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6327       // Don't insert two casts if they cannot be eliminated.  We allow 
6328       // two casts to be inserted if the sizes are the same.  This could 
6329       // only be converting signedness, which is a noop.
6330       if (DestBitSize == SrcBitSize || 
6331           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6332           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6333         Instruction::CastOps opcode = CI.getOpcode();
6334         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6335         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6336         return BinaryOperator::create(
6337             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6338       }
6339     }
6340
6341     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6342     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6343         SrcI->getOpcode() == Instruction::Xor &&
6344         Op1 == ConstantInt::getTrue() &&
6345         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6346       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6347       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6348     }
6349     break;
6350   case Instruction::SDiv:
6351   case Instruction::UDiv:
6352   case Instruction::SRem:
6353   case Instruction::URem:
6354     // If we are just changing the sign, rewrite.
6355     if (DestBitSize == SrcBitSize) {
6356       // Don't insert two casts if they cannot be eliminated.  We allow 
6357       // two casts to be inserted if the sizes are the same.  This could 
6358       // only be converting signedness, which is a noop.
6359       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6360           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6361         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6362                                               Op0, DestTy, SrcI);
6363         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6364                                               Op1, DestTy, SrcI);
6365         return BinaryOperator::create(
6366           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6367       }
6368     }
6369     break;
6370
6371   case Instruction::Shl:
6372     // Allow changing the sign of the source operand.  Do not allow 
6373     // changing the size of the shift, UNLESS the shift amount is a 
6374     // constant.  We must not change variable sized shifts to a smaller 
6375     // size, because it is undefined to shift more bits out than exist 
6376     // in the value.
6377     if (DestBitSize == SrcBitSize ||
6378         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6379       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6380           Instruction::BitCast : Instruction::Trunc);
6381       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6382       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6383       return BinaryOperator::createShl(Op0c, Op1c);
6384     }
6385     break;
6386   case Instruction::AShr:
6387     // If this is a signed shr, and if all bits shifted in are about to be
6388     // truncated off, turn it into an unsigned shr to allow greater
6389     // simplifications.
6390     if (DestBitSize < SrcBitSize &&
6391         isa<ConstantInt>(Op1)) {
6392       unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6393       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6394         // Insert the new logical shift right.
6395         return BinaryOperator::createLShr(Op0, Op1);
6396       }
6397     }
6398     break;
6399
6400   case Instruction::ICmp:
6401     // If we are just checking for a icmp eq of a single bit and casting it
6402     // to an integer, then shift the bit to the appropriate place and then
6403     // cast to integer to avoid the comparison.
6404     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6405       APInt Op1CV(Op1C->getValue());
6406       // cast (X == 0) to int --> X^1      iff X has only the low bit set.
6407       // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6408       // cast (X == 1) to int --> X        iff X has only the low bit set.
6409       // cast (X == 2) to int --> X>>1     iff X has only the 2nd bit set.
6410       // cast (X != 0) to int --> X        iff X has only the low bit set.
6411       // cast (X != 0) to int --> X>>1     iff X has only the 2nd bit set.
6412       // cast (X != 1) to int --> X^1      iff X has only the low bit set.
6413       // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6414       if (Op1CV == 0 || Op1CV.isPowerOf2()) {
6415         // If Op1C some other power of two, convert:
6416         uint32_t BitWidth = Op1C->getType()->getBitWidth();
6417         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6418         APInt TypeMask(APInt::getAllOnesValue(BitWidth));
6419         ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
6420
6421         // This only works for EQ and NE
6422         ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6423         if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6424           break;
6425         
6426         APInt KnownZeroMask(KnownZero ^ TypeMask);
6427         if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
6428           bool isNE = pred == ICmpInst::ICMP_NE;
6429           if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
6430             // (X&4) == 2 --> false
6431             // (X&4) != 2 --> true
6432             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6433             Res = ConstantExpr::getZExt(Res, CI.getType());
6434             return ReplaceInstUsesWith(CI, Res);
6435           }
6436           
6437           unsigned ShiftAmt = KnownZeroMask.logBase2();
6438           Value *In = Op0;
6439           if (ShiftAmt) {
6440             // Perform a logical shr by shiftamt.
6441             // Insert the shift to put the result in the low bit.
6442             In = InsertNewInstBefore(
6443               BinaryOperator::createLShr(In,
6444                                      ConstantInt::get(In->getType(), ShiftAmt),
6445                                      In->getName()+".lobit"), CI);
6446           }
6447           
6448           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6449             Constant *One = ConstantInt::get(In->getType(), 1);
6450             In = BinaryOperator::createXor(In, One, "tmp");
6451             InsertNewInstBefore(cast<Instruction>(In), CI);
6452           }
6453           
6454           if (CI.getType() == In->getType())
6455             return ReplaceInstUsesWith(CI, In);
6456           else
6457             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6458         }
6459       }
6460     }
6461     break;
6462   }
6463   return 0;
6464 }
6465
6466 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
6467   if (Instruction *Result = commonIntCastTransforms(CI))
6468     return Result;
6469   
6470   Value *Src = CI.getOperand(0);
6471   const Type *Ty = CI.getType();
6472   unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6473   unsigned SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
6474   
6475   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6476     switch (SrcI->getOpcode()) {
6477     default: break;
6478     case Instruction::LShr:
6479       // We can shrink lshr to something smaller if we know the bits shifted in
6480       // are already zeros.
6481       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6482         unsigned ShAmt = ShAmtV->getZExtValue();
6483         
6484         // Get a mask for the bits shifting in.
6485         APInt Mask(APInt::getAllOnesValue(SrcBitWidth).lshr(
6486                      SrcBitWidth-ShAmt).shl(DestBitWidth));
6487         Value* SrcIOp0 = SrcI->getOperand(0);
6488         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6489           if (ShAmt >= DestBitWidth)        // All zeros.
6490             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6491
6492           // Okay, we can shrink this.  Truncate the input, then return a new
6493           // shift.
6494           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6495           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6496                                        Ty, CI);
6497           return BinaryOperator::createLShr(V1, V2);
6498         }
6499       } else {     // This is a variable shr.
6500         
6501         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6502         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6503         // loop-invariant and CSE'd.
6504         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6505           Value *One = ConstantInt::get(SrcI->getType(), 1);
6506
6507           Value *V = InsertNewInstBefore(
6508               BinaryOperator::createShl(One, SrcI->getOperand(1),
6509                                      "tmp"), CI);
6510           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6511                                                             SrcI->getOperand(0),
6512                                                             "tmp"), CI);
6513           Value *Zero = Constant::getNullValue(V->getType());
6514           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6515         }
6516       }
6517       break;
6518     }
6519   }
6520   
6521   return 0;
6522 }
6523
6524 Instruction *InstCombiner::visitZExt(CastInst &CI) {
6525   // If one of the common conversion will work ..
6526   if (Instruction *Result = commonIntCastTransforms(CI))
6527     return Result;
6528
6529   Value *Src = CI.getOperand(0);
6530
6531   // If this is a cast of a cast
6532   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6533     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6534     // types and if the sizes are just right we can convert this into a logical
6535     // 'and' which will be much cheaper than the pair of casts.
6536     if (isa<TruncInst>(CSrc)) {
6537       // Get the sizes of the types involved
6538       Value *A = CSrc->getOperand(0);
6539       unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6540       unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6541       unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6542       // If we're actually extending zero bits and the trunc is a no-op
6543       if (MidSize < DstSize && SrcSize == DstSize) {
6544         // Replace both of the casts with an And of the type mask.
6545         APInt AndValue(APInt::getAllOnesValue(MidSize).zext(SrcSize));
6546         Constant *AndConst = ConstantInt::get(AndValue);
6547         Instruction *And = 
6548           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6549         // Unfortunately, if the type changed, we need to cast it back.
6550         if (And->getType() != CI.getType()) {
6551           And->setName(CSrc->getName()+".mask");
6552           InsertNewInstBefore(And, CI);
6553           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6554         }
6555         return And;
6556       }
6557     }
6558   }
6559
6560   return 0;
6561 }
6562
6563 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6564   return commonIntCastTransforms(CI);
6565 }
6566
6567 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6568   return commonCastTransforms(CI);
6569 }
6570
6571 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6572   return commonCastTransforms(CI);
6573 }
6574
6575 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6576   return commonCastTransforms(CI);
6577 }
6578
6579 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6580   return commonCastTransforms(CI);
6581 }
6582
6583 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6584   return commonCastTransforms(CI);
6585 }
6586
6587 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6588   return commonCastTransforms(CI);
6589 }
6590
6591 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6592   return commonCastTransforms(CI);
6593 }
6594
6595 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6596   return commonCastTransforms(CI);
6597 }
6598
6599 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6600
6601   // If the operands are integer typed then apply the integer transforms,
6602   // otherwise just apply the common ones.
6603   Value *Src = CI.getOperand(0);
6604   const Type *SrcTy = Src->getType();
6605   const Type *DestTy = CI.getType();
6606
6607   if (SrcTy->isInteger() && DestTy->isInteger()) {
6608     if (Instruction *Result = commonIntCastTransforms(CI))
6609       return Result;
6610   } else {
6611     if (Instruction *Result = commonCastTransforms(CI))
6612       return Result;
6613   }
6614
6615
6616   // Get rid of casts from one type to the same type. These are useless and can
6617   // be replaced by the operand.
6618   if (DestTy == Src->getType())
6619     return ReplaceInstUsesWith(CI, Src);
6620
6621   // If the source and destination are pointers, and this cast is equivalent to
6622   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
6623   // This can enhance SROA and other transforms that want type-safe pointers.
6624   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6625     if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6626       const Type *DstElTy = DstPTy->getElementType();
6627       const Type *SrcElTy = SrcPTy->getElementType();
6628       
6629       Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6630       unsigned NumZeros = 0;
6631       while (SrcElTy != DstElTy && 
6632              isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6633              SrcElTy->getNumContainedTypes() /* not "{}" */) {
6634         SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6635         ++NumZeros;
6636       }
6637
6638       // If we found a path from the src to dest, create the getelementptr now.
6639       if (SrcElTy == DstElTy) {
6640         SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6641         return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
6642       }
6643     }
6644   }
6645
6646   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6647     if (SVI->hasOneUse()) {
6648       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
6649       // a bitconvert to a vector with the same # elts.
6650       if (isa<VectorType>(DestTy) && 
6651           cast<VectorType>(DestTy)->getNumElements() == 
6652                 SVI->getType()->getNumElements()) {
6653         CastInst *Tmp;
6654         // If either of the operands is a cast from CI.getType(), then
6655         // evaluating the shuffle in the casted destination's type will allow
6656         // us to eliminate at least one cast.
6657         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
6658              Tmp->getOperand(0)->getType() == DestTy) ||
6659             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
6660              Tmp->getOperand(0)->getType() == DestTy)) {
6661           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6662                                                SVI->getOperand(0), DestTy, &CI);
6663           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6664                                                SVI->getOperand(1), DestTy, &CI);
6665           // Return a new shuffle vector.  Use the same element ID's, as we
6666           // know the vector types match #elts.
6667           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6668         }
6669       }
6670     }
6671   }
6672   return 0;
6673 }
6674
6675 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6676 ///   %C = or %A, %B
6677 ///   %D = select %cond, %C, %A
6678 /// into:
6679 ///   %C = select %cond, %B, 0
6680 ///   %D = or %A, %C
6681 ///
6682 /// Assuming that the specified instruction is an operand to the select, return
6683 /// a bitmask indicating which operands of this instruction are foldable if they
6684 /// equal the other incoming value of the select.
6685 ///
6686 static unsigned GetSelectFoldableOperands(Instruction *I) {
6687   switch (I->getOpcode()) {
6688   case Instruction::Add:
6689   case Instruction::Mul:
6690   case Instruction::And:
6691   case Instruction::Or:
6692   case Instruction::Xor:
6693     return 3;              // Can fold through either operand.
6694   case Instruction::Sub:   // Can only fold on the amount subtracted.
6695   case Instruction::Shl:   // Can only fold on the shift amount.
6696   case Instruction::LShr:
6697   case Instruction::AShr:
6698     return 1;
6699   default:
6700     return 0;              // Cannot fold
6701   }
6702 }
6703
6704 /// GetSelectFoldableConstant - For the same transformation as the previous
6705 /// function, return the identity constant that goes into the select.
6706 static Constant *GetSelectFoldableConstant(Instruction *I) {
6707   switch (I->getOpcode()) {
6708   default: assert(0 && "This cannot happen!"); abort();
6709   case Instruction::Add:
6710   case Instruction::Sub:
6711   case Instruction::Or:
6712   case Instruction::Xor:
6713   case Instruction::Shl:
6714   case Instruction::LShr:
6715   case Instruction::AShr:
6716     return Constant::getNullValue(I->getType());
6717   case Instruction::And:
6718     return ConstantInt::getAllOnesValue(I->getType());
6719   case Instruction::Mul:
6720     return ConstantInt::get(I->getType(), 1);
6721   }
6722 }
6723
6724 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6725 /// have the same opcode and only one use each.  Try to simplify this.
6726 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6727                                           Instruction *FI) {
6728   if (TI->getNumOperands() == 1) {
6729     // If this is a non-volatile load or a cast from the same type,
6730     // merge.
6731     if (TI->isCast()) {
6732       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6733         return 0;
6734     } else {
6735       return 0;  // unknown unary op.
6736     }
6737
6738     // Fold this by inserting a select from the input values.
6739     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6740                                        FI->getOperand(0), SI.getName()+".v");
6741     InsertNewInstBefore(NewSI, SI);
6742     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
6743                             TI->getType());
6744   }
6745
6746   // Only handle binary operators here.
6747   if (!isa<BinaryOperator>(TI))
6748     return 0;
6749
6750   // Figure out if the operations have any operands in common.
6751   Value *MatchOp, *OtherOpT, *OtherOpF;
6752   bool MatchIsOpZero;
6753   if (TI->getOperand(0) == FI->getOperand(0)) {
6754     MatchOp  = TI->getOperand(0);
6755     OtherOpT = TI->getOperand(1);
6756     OtherOpF = FI->getOperand(1);
6757     MatchIsOpZero = true;
6758   } else if (TI->getOperand(1) == FI->getOperand(1)) {
6759     MatchOp  = TI->getOperand(1);
6760     OtherOpT = TI->getOperand(0);
6761     OtherOpF = FI->getOperand(0);
6762     MatchIsOpZero = false;
6763   } else if (!TI->isCommutative()) {
6764     return 0;
6765   } else if (TI->getOperand(0) == FI->getOperand(1)) {
6766     MatchOp  = TI->getOperand(0);
6767     OtherOpT = TI->getOperand(1);
6768     OtherOpF = FI->getOperand(0);
6769     MatchIsOpZero = true;
6770   } else if (TI->getOperand(1) == FI->getOperand(0)) {
6771     MatchOp  = TI->getOperand(1);
6772     OtherOpT = TI->getOperand(0);
6773     OtherOpF = FI->getOperand(1);
6774     MatchIsOpZero = true;
6775   } else {
6776     return 0;
6777   }
6778
6779   // If we reach here, they do have operations in common.
6780   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6781                                      OtherOpF, SI.getName()+".v");
6782   InsertNewInstBefore(NewSI, SI);
6783
6784   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6785     if (MatchIsOpZero)
6786       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6787     else
6788       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6789   }
6790   assert(0 && "Shouldn't get here");
6791   return 0;
6792 }
6793
6794 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6795   Value *CondVal = SI.getCondition();
6796   Value *TrueVal = SI.getTrueValue();
6797   Value *FalseVal = SI.getFalseValue();
6798
6799   // select true, X, Y  -> X
6800   // select false, X, Y -> Y
6801   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
6802     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
6803
6804   // select C, X, X -> X
6805   if (TrueVal == FalseVal)
6806     return ReplaceInstUsesWith(SI, TrueVal);
6807
6808   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
6809     return ReplaceInstUsesWith(SI, FalseVal);
6810   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
6811     return ReplaceInstUsesWith(SI, TrueVal);
6812   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
6813     if (isa<Constant>(TrueVal))
6814       return ReplaceInstUsesWith(SI, TrueVal);
6815     else
6816       return ReplaceInstUsesWith(SI, FalseVal);
6817   }
6818
6819   if (SI.getType() == Type::Int1Ty) {
6820     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
6821       if (C->getZExtValue()) {
6822         // Change: A = select B, true, C --> A = or B, C
6823         return BinaryOperator::createOr(CondVal, FalseVal);
6824       } else {
6825         // Change: A = select B, false, C --> A = and !B, C
6826         Value *NotCond =
6827           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6828                                              "not."+CondVal->getName()), SI);
6829         return BinaryOperator::createAnd(NotCond, FalseVal);
6830       }
6831     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
6832       if (C->getZExtValue() == false) {
6833         // Change: A = select B, C, false --> A = and B, C
6834         return BinaryOperator::createAnd(CondVal, TrueVal);
6835       } else {
6836         // Change: A = select B, C, true --> A = or !B, C
6837         Value *NotCond =
6838           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6839                                              "not."+CondVal->getName()), SI);
6840         return BinaryOperator::createOr(NotCond, TrueVal);
6841       }
6842     }
6843   }
6844
6845   // Selecting between two integer constants?
6846   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6847     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6848       // select C, 1, 0 -> cast C to int
6849       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
6850         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6851       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
6852         // select C, 0, 1 -> cast !C to int
6853         Value *NotCond =
6854           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6855                                                "not."+CondVal->getName()), SI);
6856         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6857       }
6858
6859       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
6860
6861         // (x <s 0) ? -1 : 0 -> ashr x, 31
6862         // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
6863         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
6864           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6865             bool CanXForm = false;
6866             if (IC->isSignedPredicate())
6867               CanXForm = CmpCst->isZero() && 
6868                          IC->getPredicate() == ICmpInst::ICMP_SLT;
6869             else {
6870               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6871               CanXForm = CmpCst->getValue() == APInt::getSignedMaxValue(Bits) &&
6872                          IC->getPredicate() == ICmpInst::ICMP_UGT;
6873             }
6874             
6875             if (CanXForm) {
6876               // The comparison constant and the result are not neccessarily the
6877               // same width. Make an all-ones value by inserting a AShr.
6878               Value *X = IC->getOperand(0);
6879               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6880               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6881               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6882                                                         ShAmt, "ones");
6883               InsertNewInstBefore(SRA, SI);
6884               
6885               // Finally, convert to the type of the select RHS.  We figure out
6886               // if this requires a SExt, Trunc or BitCast based on the sizes.
6887               Instruction::CastOps opc = Instruction::BitCast;
6888               unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6889               unsigned SISize  = SI.getType()->getPrimitiveSizeInBits();
6890               if (SRASize < SISize)
6891                 opc = Instruction::SExt;
6892               else if (SRASize > SISize)
6893                 opc = Instruction::Trunc;
6894               return CastInst::create(opc, SRA, SI.getType());
6895             }
6896           }
6897
6898
6899         // If one of the constants is zero (we know they can't both be) and we
6900         // have a fcmp instruction with zero, and we have an 'and' with the
6901         // non-constant value, eliminate this whole mess.  This corresponds to
6902         // cases like this: ((X & 27) ? 27 : 0)
6903         if (TrueValC->isZero() || FalseValC->isZero())
6904           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6905               cast<Constant>(IC->getOperand(1))->isNullValue())
6906             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6907               if (ICA->getOpcode() == Instruction::And &&
6908                   isa<ConstantInt>(ICA->getOperand(1)) &&
6909                   (ICA->getOperand(1) == TrueValC ||
6910                    ICA->getOperand(1) == FalseValC) &&
6911                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6912                 // Okay, now we know that everything is set up, we just don't
6913                 // know whether we have a icmp_ne or icmp_eq and whether the 
6914                 // true or false val is the zero.
6915                 bool ShouldNotVal = !TrueValC->isZero();
6916                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
6917                 Value *V = ICA;
6918                 if (ShouldNotVal)
6919                   V = InsertNewInstBefore(BinaryOperator::create(
6920                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
6921                 return ReplaceInstUsesWith(SI, V);
6922               }
6923       }
6924     }
6925
6926   // See if we are selecting two values based on a comparison of the two values.
6927   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6928     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
6929       // Transform (X == Y) ? X : Y  -> Y
6930       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6931         return ReplaceInstUsesWith(SI, FalseVal);
6932       // Transform (X != Y) ? X : Y  -> X
6933       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6934         return ReplaceInstUsesWith(SI, TrueVal);
6935       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6936
6937     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
6938       // Transform (X == Y) ? Y : X  -> X
6939       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6940         return ReplaceInstUsesWith(SI, FalseVal);
6941       // Transform (X != Y) ? Y : X  -> Y
6942       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6943         return ReplaceInstUsesWith(SI, TrueVal);
6944       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6945     }
6946   }
6947
6948   // See if we are selecting two values based on a comparison of the two values.
6949   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6950     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6951       // Transform (X == Y) ? X : Y  -> Y
6952       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6953         return ReplaceInstUsesWith(SI, FalseVal);
6954       // Transform (X != Y) ? X : Y  -> X
6955       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6956         return ReplaceInstUsesWith(SI, TrueVal);
6957       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6958
6959     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6960       // Transform (X == Y) ? Y : X  -> X
6961       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6962         return ReplaceInstUsesWith(SI, FalseVal);
6963       // Transform (X != Y) ? Y : X  -> Y
6964       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6965         return ReplaceInstUsesWith(SI, TrueVal);
6966       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6967     }
6968   }
6969
6970   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6971     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6972       if (TI->hasOneUse() && FI->hasOneUse()) {
6973         Instruction *AddOp = 0, *SubOp = 0;
6974
6975         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6976         if (TI->getOpcode() == FI->getOpcode())
6977           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6978             return IV;
6979
6980         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
6981         // even legal for FP.
6982         if (TI->getOpcode() == Instruction::Sub &&
6983             FI->getOpcode() == Instruction::Add) {
6984           AddOp = FI; SubOp = TI;
6985         } else if (FI->getOpcode() == Instruction::Sub &&
6986                    TI->getOpcode() == Instruction::Add) {
6987           AddOp = TI; SubOp = FI;
6988         }
6989
6990         if (AddOp) {
6991           Value *OtherAddOp = 0;
6992           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6993             OtherAddOp = AddOp->getOperand(1);
6994           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6995             OtherAddOp = AddOp->getOperand(0);
6996           }
6997
6998           if (OtherAddOp) {
6999             // So at this point we know we have (Y -> OtherAddOp):
7000             //        select C, (add X, Y), (sub X, Z)
7001             Value *NegVal;  // Compute -Z
7002             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7003               NegVal = ConstantExpr::getNeg(C);
7004             } else {
7005               NegVal = InsertNewInstBefore(
7006                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7007             }
7008
7009             Value *NewTrueOp = OtherAddOp;
7010             Value *NewFalseOp = NegVal;
7011             if (AddOp != TI)
7012               std::swap(NewTrueOp, NewFalseOp);
7013             Instruction *NewSel =
7014               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7015
7016             NewSel = InsertNewInstBefore(NewSel, SI);
7017             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7018           }
7019         }
7020       }
7021
7022   // See if we can fold the select into one of our operands.
7023   if (SI.getType()->isInteger()) {
7024     // See the comment above GetSelectFoldableOperands for a description of the
7025     // transformation we are doing here.
7026     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7027       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7028           !isa<Constant>(FalseVal))
7029         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7030           unsigned OpToFold = 0;
7031           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7032             OpToFold = 1;
7033           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7034             OpToFold = 2;
7035           }
7036
7037           if (OpToFold) {
7038             Constant *C = GetSelectFoldableConstant(TVI);
7039             Instruction *NewSel =
7040               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7041             InsertNewInstBefore(NewSel, SI);
7042             NewSel->takeName(TVI);
7043             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7044               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7045             else {
7046               assert(0 && "Unknown instruction!!");
7047             }
7048           }
7049         }
7050
7051     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7052       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7053           !isa<Constant>(TrueVal))
7054         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7055           unsigned OpToFold = 0;
7056           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7057             OpToFold = 1;
7058           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7059             OpToFold = 2;
7060           }
7061
7062           if (OpToFold) {
7063             Constant *C = GetSelectFoldableConstant(FVI);
7064             Instruction *NewSel =
7065               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7066             InsertNewInstBefore(NewSel, SI);
7067             NewSel->takeName(FVI);
7068             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7069               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7070             else
7071               assert(0 && "Unknown instruction!!");
7072           }
7073         }
7074   }
7075
7076   if (BinaryOperator::isNot(CondVal)) {
7077     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7078     SI.setOperand(1, FalseVal);
7079     SI.setOperand(2, TrueVal);
7080     return &SI;
7081   }
7082
7083   return 0;
7084 }
7085
7086 /// GetKnownAlignment - If the specified pointer has an alignment that we can
7087 /// determine, return it, otherwise return 0.
7088 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7089   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7090     unsigned Align = GV->getAlignment();
7091     if (Align == 0 && TD) 
7092       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
7093     return Align;
7094   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7095     unsigned Align = AI->getAlignment();
7096     if (Align == 0 && TD) {
7097       if (isa<AllocaInst>(AI))
7098         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7099       else if (isa<MallocInst>(AI)) {
7100         // Malloc returns maximally aligned memory.
7101         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7102         Align =
7103           std::max(Align,
7104                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7105         Align =
7106           std::max(Align,
7107                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7108       }
7109     }
7110     return Align;
7111   } else if (isa<BitCastInst>(V) ||
7112              (isa<ConstantExpr>(V) && 
7113               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
7114     User *CI = cast<User>(V);
7115     if (isa<PointerType>(CI->getOperand(0)->getType()))
7116       return GetKnownAlignment(CI->getOperand(0), TD);
7117     return 0;
7118   } else if (isa<GetElementPtrInst>(V) ||
7119              (isa<ConstantExpr>(V) && 
7120               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7121     User *GEPI = cast<User>(V);
7122     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7123     if (BaseAlignment == 0) return 0;
7124     
7125     // If all indexes are zero, it is just the alignment of the base pointer.
7126     bool AllZeroOperands = true;
7127     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7128       if (!isa<Constant>(GEPI->getOperand(i)) ||
7129           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7130         AllZeroOperands = false;
7131         break;
7132       }
7133     if (AllZeroOperands)
7134       return BaseAlignment;
7135     
7136     // Otherwise, if the base alignment is >= the alignment we expect for the
7137     // base pointer type, then we know that the resultant pointer is aligned at
7138     // least as much as its type requires.
7139     if (!TD) return 0;
7140
7141     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7142     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
7143     if (TD->getABITypeAlignment(PtrTy->getElementType())
7144         <= BaseAlignment) {
7145       const Type *GEPTy = GEPI->getType();
7146       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
7147       return TD->getABITypeAlignment(GEPPtrTy->getElementType());
7148     }
7149     return 0;
7150   }
7151   return 0;
7152 }
7153
7154
7155 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
7156 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
7157 /// the heavy lifting.
7158 ///
7159 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
7160   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7161   if (!II) return visitCallSite(&CI);
7162   
7163   // Intrinsics cannot occur in an invoke, so handle them here instead of in
7164   // visitCallSite.
7165   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
7166     bool Changed = false;
7167
7168     // memmove/cpy/set of zero bytes is a noop.
7169     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7170       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7171
7172       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
7173         if (CI->getZExtValue() == 1) {
7174           // Replace the instruction with just byte operations.  We would
7175           // transform other cases to loads/stores, but we don't know if
7176           // alignment is sufficient.
7177         }
7178     }
7179
7180     // If we have a memmove and the source operation is a constant global,
7181     // then the source and dest pointers can't alias, so we can change this
7182     // into a call to memcpy.
7183     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
7184       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7185         if (GVSrc->isConstant()) {
7186           Module *M = CI.getParent()->getParent()->getParent();
7187           const char *Name;
7188           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
7189               Type::Int32Ty)
7190             Name = "llvm.memcpy.i32";
7191           else
7192             Name = "llvm.memcpy.i64";
7193           Constant *MemCpy = M->getOrInsertFunction(Name,
7194                                      CI.getCalledFunction()->getFunctionType());
7195           CI.setOperand(0, MemCpy);
7196           Changed = true;
7197         }
7198     }
7199
7200     // If we can determine a pointer alignment that is bigger than currently
7201     // set, update the alignment.
7202     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7203       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7204       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7205       unsigned Align = std::min(Alignment1, Alignment2);
7206       if (MI->getAlignment()->getZExtValue() < Align) {
7207         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7208         Changed = true;
7209       }
7210     } else if (isa<MemSetInst>(MI)) {
7211       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
7212       if (MI->getAlignment()->getZExtValue() < Alignment) {
7213         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7214         Changed = true;
7215       }
7216     }
7217           
7218     if (Changed) return II;
7219   } else {
7220     switch (II->getIntrinsicID()) {
7221     default: break;
7222     case Intrinsic::ppc_altivec_lvx:
7223     case Intrinsic::ppc_altivec_lvxl:
7224     case Intrinsic::x86_sse_loadu_ps:
7225     case Intrinsic::x86_sse2_loadu_pd:
7226     case Intrinsic::x86_sse2_loadu_dq:
7227       // Turn PPC lvx     -> load if the pointer is known aligned.
7228       // Turn X86 loadups -> load if the pointer is known aligned.
7229       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7230         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7231                                       PointerType::get(II->getType()), CI);
7232         return new LoadInst(Ptr);
7233       }
7234       break;
7235     case Intrinsic::ppc_altivec_stvx:
7236     case Intrinsic::ppc_altivec_stvxl:
7237       // Turn stvx -> store if the pointer is known aligned.
7238       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7239         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7240         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7241                                       OpPtrTy, CI);
7242         return new StoreInst(II->getOperand(1), Ptr);
7243       }
7244       break;
7245     case Intrinsic::x86_sse_storeu_ps:
7246     case Intrinsic::x86_sse2_storeu_pd:
7247     case Intrinsic::x86_sse2_storeu_dq:
7248     case Intrinsic::x86_sse2_storel_dq:
7249       // Turn X86 storeu -> store if the pointer is known aligned.
7250       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7251         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7252         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7253                                       OpPtrTy, CI);
7254         return new StoreInst(II->getOperand(2), Ptr);
7255       }
7256       break;
7257       
7258     case Intrinsic::x86_sse_cvttss2si: {
7259       // These intrinsics only demands the 0th element of its input vector.  If
7260       // we can simplify the input based on that, do so now.
7261       uint64_t UndefElts;
7262       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7263                                                 UndefElts)) {
7264         II->setOperand(1, V);
7265         return II;
7266       }
7267       break;
7268     }
7269       
7270     case Intrinsic::ppc_altivec_vperm:
7271       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7272       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
7273         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7274         
7275         // Check that all of the elements are integer constants or undefs.
7276         bool AllEltsOk = true;
7277         for (unsigned i = 0; i != 16; ++i) {
7278           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7279               !isa<UndefValue>(Mask->getOperand(i))) {
7280             AllEltsOk = false;
7281             break;
7282           }
7283         }
7284         
7285         if (AllEltsOk) {
7286           // Cast the input vectors to byte vectors.
7287           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7288                                         II->getOperand(1), Mask->getType(), CI);
7289           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7290                                         II->getOperand(2), Mask->getType(), CI);
7291           Value *Result = UndefValue::get(Op0->getType());
7292           
7293           // Only extract each element once.
7294           Value *ExtractedElts[32];
7295           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7296           
7297           for (unsigned i = 0; i != 16; ++i) {
7298             if (isa<UndefValue>(Mask->getOperand(i)))
7299               continue;
7300             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7301             Idx &= 31;  // Match the hardware behavior.
7302             
7303             if (ExtractedElts[Idx] == 0) {
7304               Instruction *Elt = 
7305                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7306               InsertNewInstBefore(Elt, CI);
7307               ExtractedElts[Idx] = Elt;
7308             }
7309           
7310             // Insert this value into the result vector.
7311             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7312             InsertNewInstBefore(cast<Instruction>(Result), CI);
7313           }
7314           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7315         }
7316       }
7317       break;
7318
7319     case Intrinsic::stackrestore: {
7320       // If the save is right next to the restore, remove the restore.  This can
7321       // happen when variable allocas are DCE'd.
7322       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7323         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7324           BasicBlock::iterator BI = SS;
7325           if (&*++BI == II)
7326             return EraseInstFromFunction(CI);
7327         }
7328       }
7329       
7330       // If the stack restore is in a return/unwind block and if there are no
7331       // allocas or calls between the restore and the return, nuke the restore.
7332       TerminatorInst *TI = II->getParent()->getTerminator();
7333       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7334         BasicBlock::iterator BI = II;
7335         bool CannotRemove = false;
7336         for (++BI; &*BI != TI; ++BI) {
7337           if (isa<AllocaInst>(BI) ||
7338               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7339             CannotRemove = true;
7340             break;
7341           }
7342         }
7343         if (!CannotRemove)
7344           return EraseInstFromFunction(CI);
7345       }
7346       break;
7347     }
7348     }
7349   }
7350
7351   return visitCallSite(II);
7352 }
7353
7354 // InvokeInst simplification
7355 //
7356 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7357   return visitCallSite(&II);
7358 }
7359
7360 // visitCallSite - Improvements for call and invoke instructions.
7361 //
7362 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7363   bool Changed = false;
7364
7365   // If the callee is a constexpr cast of a function, attempt to move the cast
7366   // to the arguments of the call/invoke.
7367   if (transformConstExprCastCall(CS)) return 0;
7368
7369   Value *Callee = CS.getCalledValue();
7370
7371   if (Function *CalleeF = dyn_cast<Function>(Callee))
7372     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7373       Instruction *OldCall = CS.getInstruction();
7374       // If the call and callee calling conventions don't match, this call must
7375       // be unreachable, as the call is undefined.
7376       new StoreInst(ConstantInt::getTrue(),
7377                     UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
7378       if (!OldCall->use_empty())
7379         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7380       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7381         return EraseInstFromFunction(*OldCall);
7382       return 0;
7383     }
7384
7385   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7386     // This instruction is not reachable, just remove it.  We insert a store to
7387     // undef so that we know that this code is not reachable, despite the fact
7388     // that we can't modify the CFG here.
7389     new StoreInst(ConstantInt::getTrue(),
7390                   UndefValue::get(PointerType::get(Type::Int1Ty)),
7391                   CS.getInstruction());
7392
7393     if (!CS.getInstruction()->use_empty())
7394       CS.getInstruction()->
7395         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7396
7397     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7398       // Don't break the CFG, insert a dummy cond branch.
7399       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7400                      ConstantInt::getTrue(), II);
7401     }
7402     return EraseInstFromFunction(*CS.getInstruction());
7403   }
7404
7405   const PointerType *PTy = cast<PointerType>(Callee->getType());
7406   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7407   if (FTy->isVarArg()) {
7408     // See if we can optimize any arguments passed through the varargs area of
7409     // the call.
7410     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7411            E = CS.arg_end(); I != E; ++I)
7412       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7413         // If this cast does not effect the value passed through the varargs
7414         // area, we can eliminate the use of the cast.
7415         Value *Op = CI->getOperand(0);
7416         if (CI->isLosslessCast()) {
7417           *I = Op;
7418           Changed = true;
7419         }
7420       }
7421   }
7422
7423   return Changed ? CS.getInstruction() : 0;
7424 }
7425
7426 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7427 // attempt to move the cast to the arguments of the call/invoke.
7428 //
7429 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7430   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7431   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7432   if (CE->getOpcode() != Instruction::BitCast || 
7433       !isa<Function>(CE->getOperand(0)))
7434     return false;
7435   Function *Callee = cast<Function>(CE->getOperand(0));
7436   Instruction *Caller = CS.getInstruction();
7437
7438   // Okay, this is a cast from a function to a different type.  Unless doing so
7439   // would cause a type conversion of one of our arguments, change this call to
7440   // be a direct call with arguments casted to the appropriate types.
7441   //
7442   const FunctionType *FT = Callee->getFunctionType();
7443   const Type *OldRetTy = Caller->getType();
7444
7445   // Check to see if we are changing the return type...
7446   if (OldRetTy != FT->getReturnType()) {
7447     if (Callee->isDeclaration() && !Caller->use_empty() && 
7448         // Conversion is ok if changing from pointer to int of same size.
7449         !(isa<PointerType>(FT->getReturnType()) &&
7450           TD->getIntPtrType() == OldRetTy))
7451       return false;   // Cannot transform this return value.
7452
7453     // If the callsite is an invoke instruction, and the return value is used by
7454     // a PHI node in a successor, we cannot change the return type of the call
7455     // because there is no place to put the cast instruction (without breaking
7456     // the critical edge).  Bail out in this case.
7457     if (!Caller->use_empty())
7458       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7459         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7460              UI != E; ++UI)
7461           if (PHINode *PN = dyn_cast<PHINode>(*UI))
7462             if (PN->getParent() == II->getNormalDest() ||
7463                 PN->getParent() == II->getUnwindDest())
7464               return false;
7465   }
7466
7467   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7468   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7469
7470   CallSite::arg_iterator AI = CS.arg_begin();
7471   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7472     const Type *ParamTy = FT->getParamType(i);
7473     const Type *ActTy = (*AI)->getType();
7474     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7475     //Either we can cast directly, or we can upconvert the argument
7476     bool isConvertible = ActTy == ParamTy ||
7477       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
7478       (ParamTy->isInteger() && ActTy->isInteger() &&
7479        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7480       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7481        && c->getValue().isStrictlyPositive());
7482     if (Callee->isDeclaration() && !isConvertible) return false;
7483   }
7484
7485   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7486       Callee->isDeclaration())
7487     return false;   // Do not delete arguments unless we have a function body...
7488
7489   // Okay, we decided that this is a safe thing to do: go ahead and start
7490   // inserting cast instructions as necessary...
7491   std::vector<Value*> Args;
7492   Args.reserve(NumActualArgs);
7493
7494   AI = CS.arg_begin();
7495   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7496     const Type *ParamTy = FT->getParamType(i);
7497     if ((*AI)->getType() == ParamTy) {
7498       Args.push_back(*AI);
7499     } else {
7500       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7501           false, ParamTy, false);
7502       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7503       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7504     }
7505   }
7506
7507   // If the function takes more arguments than the call was taking, add them
7508   // now...
7509   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7510     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7511
7512   // If we are removing arguments to the function, emit an obnoxious warning...
7513   if (FT->getNumParams() < NumActualArgs)
7514     if (!FT->isVarArg()) {
7515       cerr << "WARNING: While resolving call to function '"
7516            << Callee->getName() << "' arguments were dropped!\n";
7517     } else {
7518       // Add all of the arguments in their promoted form to the arg list...
7519       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7520         const Type *PTy = getPromotedType((*AI)->getType());
7521         if (PTy != (*AI)->getType()) {
7522           // Must promote to pass through va_arg area!
7523           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
7524                                                                 PTy, false);
7525           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7526           InsertNewInstBefore(Cast, *Caller);
7527           Args.push_back(Cast);
7528         } else {
7529           Args.push_back(*AI);
7530         }
7531       }
7532     }
7533
7534   if (FT->getReturnType() == Type::VoidTy)
7535     Caller->setName("");   // Void type should not have a name.
7536
7537   Instruction *NC;
7538   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7539     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7540                         &Args[0], Args.size(), Caller->getName(), Caller);
7541     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7542   } else {
7543     NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
7544     if (cast<CallInst>(Caller)->isTailCall())
7545       cast<CallInst>(NC)->setTailCall();
7546    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7547   }
7548
7549   // Insert a cast of the return type as necessary.
7550   Value *NV = NC;
7551   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7552     if (NV->getType() != Type::VoidTy) {
7553       const Type *CallerTy = Caller->getType();
7554       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
7555                                                             CallerTy, false);
7556       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7557
7558       // If this is an invoke instruction, we should insert it after the first
7559       // non-phi, instruction in the normal successor block.
7560       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7561         BasicBlock::iterator I = II->getNormalDest()->begin();
7562         while (isa<PHINode>(I)) ++I;
7563         InsertNewInstBefore(NC, *I);
7564       } else {
7565         // Otherwise, it's a call, just insert cast right after the call instr
7566         InsertNewInstBefore(NC, *Caller);
7567       }
7568       AddUsersToWorkList(*Caller);
7569     } else {
7570       NV = UndefValue::get(Caller->getType());
7571     }
7572   }
7573
7574   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7575     Caller->replaceAllUsesWith(NV);
7576   Caller->eraseFromParent();
7577   RemoveFromWorkList(Caller);
7578   return true;
7579 }
7580
7581 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7582 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7583 /// and a single binop.
7584 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7585   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7586   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7587          isa<CmpInst>(FirstInst));
7588   unsigned Opc = FirstInst->getOpcode();
7589   Value *LHSVal = FirstInst->getOperand(0);
7590   Value *RHSVal = FirstInst->getOperand(1);
7591     
7592   const Type *LHSType = LHSVal->getType();
7593   const Type *RHSType = RHSVal->getType();
7594   
7595   // Scan to see if all operands are the same opcode, all have one use, and all
7596   // kill their operands (i.e. the operands have one use).
7597   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7598     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7599     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7600         // Verify type of the LHS matches so we don't fold cmp's of different
7601         // types or GEP's with different index types.
7602         I->getOperand(0)->getType() != LHSType ||
7603         I->getOperand(1)->getType() != RHSType)
7604       return 0;
7605
7606     // If they are CmpInst instructions, check their predicates
7607     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7608       if (cast<CmpInst>(I)->getPredicate() !=
7609           cast<CmpInst>(FirstInst)->getPredicate())
7610         return 0;
7611     
7612     // Keep track of which operand needs a phi node.
7613     if (I->getOperand(0) != LHSVal) LHSVal = 0;
7614     if (I->getOperand(1) != RHSVal) RHSVal = 0;
7615   }
7616   
7617   // Otherwise, this is safe to transform, determine if it is profitable.
7618
7619   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7620   // Indexes are often folded into load/store instructions, so we don't want to
7621   // hide them behind a phi.
7622   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7623     return 0;
7624   
7625   Value *InLHS = FirstInst->getOperand(0);
7626   Value *InRHS = FirstInst->getOperand(1);
7627   PHINode *NewLHS = 0, *NewRHS = 0;
7628   if (LHSVal == 0) {
7629     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7630     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7631     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7632     InsertNewInstBefore(NewLHS, PN);
7633     LHSVal = NewLHS;
7634   }
7635   
7636   if (RHSVal == 0) {
7637     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7638     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7639     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7640     InsertNewInstBefore(NewRHS, PN);
7641     RHSVal = NewRHS;
7642   }
7643   
7644   // Add all operands to the new PHIs.
7645   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7646     if (NewLHS) {
7647       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7648       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7649     }
7650     if (NewRHS) {
7651       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7652       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7653     }
7654   }
7655     
7656   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7657     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7658   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7659     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
7660                            RHSVal);
7661   else {
7662     assert(isa<GetElementPtrInst>(FirstInst));
7663     return new GetElementPtrInst(LHSVal, RHSVal);
7664   }
7665 }
7666
7667 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7668 /// of the block that defines it.  This means that it must be obvious the value
7669 /// of the load is not changed from the point of the load to the end of the
7670 /// block it is in.
7671 ///
7672 /// Finally, it is safe, but not profitable, to sink a load targetting a
7673 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
7674 /// to a register.
7675 static bool isSafeToSinkLoad(LoadInst *L) {
7676   BasicBlock::iterator BBI = L, E = L->getParent()->end();
7677   
7678   for (++BBI; BBI != E; ++BBI)
7679     if (BBI->mayWriteToMemory())
7680       return false;
7681   
7682   // Check for non-address taken alloca.  If not address-taken already, it isn't
7683   // profitable to do this xform.
7684   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7685     bool isAddressTaken = false;
7686     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7687          UI != E; ++UI) {
7688       if (isa<LoadInst>(UI)) continue;
7689       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7690         // If storing TO the alloca, then the address isn't taken.
7691         if (SI->getOperand(1) == AI) continue;
7692       }
7693       isAddressTaken = true;
7694       break;
7695     }
7696     
7697     if (!isAddressTaken)
7698       return false;
7699   }
7700   
7701   return true;
7702 }
7703
7704
7705 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7706 // operator and they all are only used by the PHI, PHI together their
7707 // inputs, and do the operation once, to the result of the PHI.
7708 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7709   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7710
7711   // Scan the instruction, looking for input operations that can be folded away.
7712   // If all input operands to the phi are the same instruction (e.g. a cast from
7713   // the same type or "+42") we can pull the operation through the PHI, reducing
7714   // code size and simplifying code.
7715   Constant *ConstantOp = 0;
7716   const Type *CastSrcTy = 0;
7717   bool isVolatile = false;
7718   if (isa<CastInst>(FirstInst)) {
7719     CastSrcTy = FirstInst->getOperand(0)->getType();
7720   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
7721     // Can fold binop, compare or shift here if the RHS is a constant, 
7722     // otherwise call FoldPHIArgBinOpIntoPHI.
7723     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7724     if (ConstantOp == 0)
7725       return FoldPHIArgBinOpIntoPHI(PN);
7726   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7727     isVolatile = LI->isVolatile();
7728     // We can't sink the load if the loaded value could be modified between the
7729     // load and the PHI.
7730     if (LI->getParent() != PN.getIncomingBlock(0) ||
7731         !isSafeToSinkLoad(LI))
7732       return 0;
7733   } else if (isa<GetElementPtrInst>(FirstInst)) {
7734     if (FirstInst->getNumOperands() == 2)
7735       return FoldPHIArgBinOpIntoPHI(PN);
7736     // Can't handle general GEPs yet.
7737     return 0;
7738   } else {
7739     return 0;  // Cannot fold this operation.
7740   }
7741
7742   // Check to see if all arguments are the same operation.
7743   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7744     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7745     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7746     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
7747       return 0;
7748     if (CastSrcTy) {
7749       if (I->getOperand(0)->getType() != CastSrcTy)
7750         return 0;  // Cast operation must match.
7751     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7752       // We can't sink the load if the loaded value could be modified between 
7753       // the load and the PHI.
7754       if (LI->isVolatile() != isVolatile ||
7755           LI->getParent() != PN.getIncomingBlock(i) ||
7756           !isSafeToSinkLoad(LI))
7757         return 0;
7758     } else if (I->getOperand(1) != ConstantOp) {
7759       return 0;
7760     }
7761   }
7762
7763   // Okay, they are all the same operation.  Create a new PHI node of the
7764   // correct type, and PHI together all of the LHS's of the instructions.
7765   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7766                                PN.getName()+".in");
7767   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7768
7769   Value *InVal = FirstInst->getOperand(0);
7770   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7771
7772   // Add all operands to the new PHI.
7773   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7774     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7775     if (NewInVal != InVal)
7776       InVal = 0;
7777     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7778   }
7779
7780   Value *PhiVal;
7781   if (InVal) {
7782     // The new PHI unions all of the same values together.  This is really
7783     // common, so we handle it intelligently here for compile-time speed.
7784     PhiVal = InVal;
7785     delete NewPN;
7786   } else {
7787     InsertNewInstBefore(NewPN, PN);
7788     PhiVal = NewPN;
7789   }
7790
7791   // Insert and return the new operation.
7792   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7793     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7794   else if (isa<LoadInst>(FirstInst))
7795     return new LoadInst(PhiVal, "", isVolatile);
7796   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7797     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7798   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7799     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
7800                            PhiVal, ConstantOp);
7801   else
7802     assert(0 && "Unknown operation");
7803   return 0;
7804 }
7805
7806 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7807 /// that is dead.
7808 static bool DeadPHICycle(PHINode *PN,
7809                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
7810   if (PN->use_empty()) return true;
7811   if (!PN->hasOneUse()) return false;
7812
7813   // Remember this node, and if we find the cycle, return.
7814   if (!PotentiallyDeadPHIs.insert(PN))
7815     return true;
7816
7817   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7818     return DeadPHICycle(PU, PotentiallyDeadPHIs);
7819
7820   return false;
7821 }
7822
7823 // PHINode simplification
7824 //
7825 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7826   // If LCSSA is around, don't mess with Phi nodes
7827   if (MustPreserveLCSSA) return 0;
7828   
7829   if (Value *V = PN.hasConstantValue())
7830     return ReplaceInstUsesWith(PN, V);
7831
7832   // If all PHI operands are the same operation, pull them through the PHI,
7833   // reducing code size.
7834   if (isa<Instruction>(PN.getIncomingValue(0)) &&
7835       PN.getIncomingValue(0)->hasOneUse())
7836     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7837       return Result;
7838
7839   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
7840   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7841   // PHI)... break the cycle.
7842   if (PN.hasOneUse()) {
7843     Instruction *PHIUser = cast<Instruction>(PN.use_back());
7844     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
7845       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
7846       PotentiallyDeadPHIs.insert(&PN);
7847       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7848         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7849     }
7850    
7851     // If this phi has a single use, and if that use just computes a value for
7852     // the next iteration of a loop, delete the phi.  This occurs with unused
7853     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
7854     // common case here is good because the only other things that catch this
7855     // are induction variable analysis (sometimes) and ADCE, which is only run
7856     // late.
7857     if (PHIUser->hasOneUse() &&
7858         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7859         PHIUser->use_back() == &PN) {
7860       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7861     }
7862   }
7863
7864   return 0;
7865 }
7866
7867 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7868                                    Instruction *InsertPoint,
7869                                    InstCombiner *IC) {
7870   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7871   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
7872   // We must cast correctly to the pointer type. Ensure that we
7873   // sign extend the integer value if it is smaller as this is
7874   // used for address computation.
7875   Instruction::CastOps opcode = 
7876      (VTySize < PtrSize ? Instruction::SExt :
7877       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7878   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
7879 }
7880
7881
7882 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7883   Value *PtrOp = GEP.getOperand(0);
7884   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
7885   // If so, eliminate the noop.
7886   if (GEP.getNumOperands() == 1)
7887     return ReplaceInstUsesWith(GEP, PtrOp);
7888
7889   if (isa<UndefValue>(GEP.getOperand(0)))
7890     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7891
7892   bool HasZeroPointerIndex = false;
7893   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7894     HasZeroPointerIndex = C->isNullValue();
7895
7896   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7897     return ReplaceInstUsesWith(GEP, PtrOp);
7898
7899   // Keep track of whether all indices are zero constants integers.
7900   bool AllZeroIndices = true;
7901   
7902   // Eliminate unneeded casts for indices.
7903   bool MadeChange = false;
7904   
7905   gep_type_iterator GTI = gep_type_begin(GEP);
7906   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
7907     // Track whether this GEP has all zero indices, if so, it doesn't move the
7908     // input pointer, it just changes its type.
7909     if (AllZeroIndices) {
7910       if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(i)))
7911         AllZeroIndices = CI->isNullValue();
7912       else
7913         AllZeroIndices = false;
7914     }
7915     if (isa<SequentialType>(*GTI)) {
7916       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7917         if (CI->getOpcode() == Instruction::ZExt ||
7918             CI->getOpcode() == Instruction::SExt) {
7919           const Type *SrcTy = CI->getOperand(0)->getType();
7920           // We can eliminate a cast from i32 to i64 iff the target 
7921           // is a 32-bit pointer target.
7922           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7923             MadeChange = true;
7924             GEP.setOperand(i, CI->getOperand(0));
7925           }
7926         }
7927       }
7928       // If we are using a wider index than needed for this platform, shrink it
7929       // to what we need.  If the incoming value needs a cast instruction,
7930       // insert it.  This explicit cast can make subsequent optimizations more
7931       // obvious.
7932       Value *Op = GEP.getOperand(i);
7933       if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
7934         if (Constant *C = dyn_cast<Constant>(Op)) {
7935           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
7936           MadeChange = true;
7937         } else {
7938           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7939                                 GEP);
7940           GEP.setOperand(i, Op);
7941           MadeChange = true;
7942         }
7943     }
7944   }
7945   if (MadeChange) return &GEP;
7946
7947   // If this GEP instruction doesn't move the pointer, and if the input operand
7948   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
7949   // real input to the dest type.
7950   if (AllZeroIndices && isa<BitCastInst>(GEP.getOperand(0)))
7951     return new BitCastInst(cast<BitCastInst>(GEP.getOperand(0))->getOperand(0),
7952                            GEP.getType());
7953     
7954   // Combine Indices - If the source pointer to this getelementptr instruction
7955   // is a getelementptr instruction, combine the indices of the two
7956   // getelementptr instructions into a single instruction.
7957   //
7958   SmallVector<Value*, 8> SrcGEPOperands;
7959   if (User *Src = dyn_castGetElementPtr(PtrOp))
7960     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
7961
7962   if (!SrcGEPOperands.empty()) {
7963     // Note that if our source is a gep chain itself that we wait for that
7964     // chain to be resolved before we perform this transformation.  This
7965     // avoids us creating a TON of code in some cases.
7966     //
7967     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7968         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7969       return 0;   // Wait until our source is folded to completion.
7970
7971     SmallVector<Value*, 8> Indices;
7972
7973     // Find out whether the last index in the source GEP is a sequential idx.
7974     bool EndsWithSequential = false;
7975     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7976            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7977       EndsWithSequential = !isa<StructType>(*I);
7978
7979     // Can we combine the two pointer arithmetics offsets?
7980     if (EndsWithSequential) {
7981       // Replace: gep (gep %P, long B), long A, ...
7982       // With:    T = long A+B; gep %P, T, ...
7983       //
7984       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7985       if (SO1 == Constant::getNullValue(SO1->getType())) {
7986         Sum = GO1;
7987       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7988         Sum = SO1;
7989       } else {
7990         // If they aren't the same type, convert both to an integer of the
7991         // target's pointer size.
7992         if (SO1->getType() != GO1->getType()) {
7993           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7994             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
7995           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7996             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
7997           } else {
7998             unsigned PS = TD->getPointerSize();
7999             if (TD->getTypeSize(SO1->getType()) == PS) {
8000               // Convert GO1 to SO1's type.
8001               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
8002
8003             } else if (TD->getTypeSize(GO1->getType()) == PS) {
8004               // Convert SO1 to GO1's type.
8005               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
8006             } else {
8007               const Type *PT = TD->getIntPtrType();
8008               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8009               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
8010             }
8011           }
8012         }
8013         if (isa<Constant>(SO1) && isa<Constant>(GO1))
8014           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8015         else {
8016           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8017           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
8018         }
8019       }
8020
8021       // Recycle the GEP we already have if possible.
8022       if (SrcGEPOperands.size() == 2) {
8023         GEP.setOperand(0, SrcGEPOperands[0]);
8024         GEP.setOperand(1, Sum);
8025         return &GEP;
8026       } else {
8027         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8028                        SrcGEPOperands.end()-1);
8029         Indices.push_back(Sum);
8030         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8031       }
8032     } else if (isa<Constant>(*GEP.idx_begin()) &&
8033                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
8034                SrcGEPOperands.size() != 1) {
8035       // Otherwise we can do the fold if the first index of the GEP is a zero
8036       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8037                      SrcGEPOperands.end());
8038       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8039     }
8040
8041     if (!Indices.empty())
8042       return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8043                                    Indices.size(), GEP.getName());
8044
8045   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
8046     // GEP of global variable.  If all of the indices for this GEP are
8047     // constants, we can promote this to a constexpr instead of an instruction.
8048
8049     // Scan for nonconstants...
8050     SmallVector<Constant*, 8> Indices;
8051     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8052     for (; I != E && isa<Constant>(*I); ++I)
8053       Indices.push_back(cast<Constant>(*I));
8054
8055     if (I == E) {  // If they are all constants...
8056       Constant *CE = ConstantExpr::getGetElementPtr(GV,
8057                                                     &Indices[0],Indices.size());
8058
8059       // Replace all uses of the GEP with the new constexpr...
8060       return ReplaceInstUsesWith(GEP, CE);
8061     }
8062   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
8063     if (!isa<PointerType>(X->getType())) {
8064       // Not interesting.  Source pointer must be a cast from pointer.
8065     } else if (HasZeroPointerIndex) {
8066       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8067       // into     : GEP [10 x ubyte]* X, long 0, ...
8068       //
8069       // This occurs when the program declares an array extern like "int X[];"
8070       //
8071       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8072       const PointerType *XTy = cast<PointerType>(X->getType());
8073       if (const ArrayType *XATy =
8074           dyn_cast<ArrayType>(XTy->getElementType()))
8075         if (const ArrayType *CATy =
8076             dyn_cast<ArrayType>(CPTy->getElementType()))
8077           if (CATy->getElementType() == XATy->getElementType()) {
8078             // At this point, we know that the cast source type is a pointer
8079             // to an array of the same type as the destination pointer
8080             // array.  Because the array type is never stepped over (there
8081             // is a leading zero) we can fold the cast into this GEP.
8082             GEP.setOperand(0, X);
8083             return &GEP;
8084           }
8085     } else if (GEP.getNumOperands() == 2) {
8086       // Transform things like:
8087       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8088       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
8089       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8090       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8091       if (isa<ArrayType>(SrcElTy) &&
8092           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8093           TD->getTypeSize(ResElTy)) {
8094         Value *V = InsertNewInstBefore(
8095                new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
8096                                      GEP.getOperand(1), GEP.getName()), GEP);
8097         // V and GEP are both pointer types --> BitCast
8098         return new BitCastInst(V, GEP.getType());
8099       }
8100       
8101       // Transform things like:
8102       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8103       //   (where tmp = 8*tmp2) into:
8104       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8105       
8106       if (isa<ArrayType>(SrcElTy) &&
8107           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
8108         uint64_t ArrayEltSize =
8109             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8110         
8111         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
8112         // allow either a mul, shift, or constant here.
8113         Value *NewIdx = 0;
8114         ConstantInt *Scale = 0;
8115         if (ArrayEltSize == 1) {
8116           NewIdx = GEP.getOperand(1);
8117           Scale = ConstantInt::get(NewIdx->getType(), 1);
8118         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
8119           NewIdx = ConstantInt::get(CI->getType(), 1);
8120           Scale = CI;
8121         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8122           if (Inst->getOpcode() == Instruction::Shl &&
8123               isa<ConstantInt>(Inst->getOperand(1))) {
8124             unsigned ShAmt =
8125               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
8126             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
8127             NewIdx = Inst->getOperand(0);
8128           } else if (Inst->getOpcode() == Instruction::Mul &&
8129                      isa<ConstantInt>(Inst->getOperand(1))) {
8130             Scale = cast<ConstantInt>(Inst->getOperand(1));
8131             NewIdx = Inst->getOperand(0);
8132           }
8133         }
8134
8135         // If the index will be to exactly the right offset with the scale taken
8136         // out, perform the transformation.
8137         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
8138           if (isa<ConstantInt>(Scale))
8139             Scale = ConstantInt::get(Scale->getType(),
8140                                       Scale->getZExtValue() / ArrayEltSize);
8141           if (Scale->getZExtValue() != 1) {
8142             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8143                                                        true /*SExt*/);
8144             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8145             NewIdx = InsertNewInstBefore(Sc, GEP);
8146           }
8147
8148           // Insert the new GEP instruction.
8149           Instruction *NewGEP =
8150             new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
8151                                   NewIdx, GEP.getName());
8152           NewGEP = InsertNewInstBefore(NewGEP, GEP);
8153           // The NewGEP must be pointer typed, so must the old one -> BitCast
8154           return new BitCastInst(NewGEP, GEP.getType());
8155         }
8156       }
8157     }
8158   }
8159
8160   return 0;
8161 }
8162
8163 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8164   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8165   if (AI.isArrayAllocation())    // Check C != 1
8166     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8167       const Type *NewTy = 
8168         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
8169       AllocationInst *New = 0;
8170
8171       // Create and insert the replacement instruction...
8172       if (isa<MallocInst>(AI))
8173         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
8174       else {
8175         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
8176         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
8177       }
8178
8179       InsertNewInstBefore(New, AI);
8180
8181       // Scan to the end of the allocation instructions, to skip over a block of
8182       // allocas if possible...
8183       //
8184       BasicBlock::iterator It = New;
8185       while (isa<AllocationInst>(*It)) ++It;
8186
8187       // Now that I is pointing to the first non-allocation-inst in the block,
8188       // insert our getelementptr instruction...
8189       //
8190       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
8191       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8192                                        New->getName()+".sub", It);
8193
8194       // Now make everything use the getelementptr instead of the original
8195       // allocation.
8196       return ReplaceInstUsesWith(AI, V);
8197     } else if (isa<UndefValue>(AI.getArraySize())) {
8198       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8199     }
8200
8201   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8202   // Note that we only do this for alloca's, because malloc should allocate and
8203   // return a unique pointer, even for a zero byte allocation.
8204   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
8205       TD->getTypeSize(AI.getAllocatedType()) == 0)
8206     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8207
8208   return 0;
8209 }
8210
8211 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8212   Value *Op = FI.getOperand(0);
8213
8214   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8215   if (CastInst *CI = dyn_cast<CastInst>(Op))
8216     if (isa<PointerType>(CI->getOperand(0)->getType())) {
8217       FI.setOperand(0, CI->getOperand(0));
8218       return &FI;
8219     }
8220
8221   // free undef -> unreachable.
8222   if (isa<UndefValue>(Op)) {
8223     // Insert a new store to null because we cannot modify the CFG here.
8224     new StoreInst(ConstantInt::getTrue(),
8225                   UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
8226     return EraseInstFromFunction(FI);
8227   }
8228
8229   // If we have 'free null' delete the instruction.  This can happen in stl code
8230   // when lots of inlining happens.
8231   if (isa<ConstantPointerNull>(Op))
8232     return EraseInstFromFunction(FI);
8233
8234   return 0;
8235 }
8236
8237
8238 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
8239 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8240   User *CI = cast<User>(LI.getOperand(0));
8241   Value *CastOp = CI->getOperand(0);
8242
8243   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8244   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8245     const Type *SrcPTy = SrcTy->getElementType();
8246
8247     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
8248          isa<VectorType>(DestPTy)) {
8249       // If the source is an array, the code below will not succeed.  Check to
8250       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8251       // constants.
8252       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8253         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8254           if (ASrcTy->getNumElements() != 0) {
8255             Value *Idxs[2];
8256             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8257             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8258             SrcTy = cast<PointerType>(CastOp->getType());
8259             SrcPTy = SrcTy->getElementType();
8260           }
8261
8262       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
8263             isa<VectorType>(SrcPTy)) &&
8264           // Do not allow turning this into a load of an integer, which is then
8265           // casted to a pointer, this pessimizes pointer analysis a lot.
8266           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8267           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8268                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8269
8270         // Okay, we are casting from one integer or pointer type to another of
8271         // the same size.  Instead of casting the pointer before the load, cast
8272         // the result of the loaded value.
8273         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8274                                                              CI->getName(),
8275                                                          LI.isVolatile()),LI);
8276         // Now cast the result of the load.
8277         return new BitCastInst(NewLoad, LI.getType());
8278       }
8279     }
8280   }
8281   return 0;
8282 }
8283
8284 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8285 /// from this value cannot trap.  If it is not obviously safe to load from the
8286 /// specified pointer, we do a quick local scan of the basic block containing
8287 /// ScanFrom, to determine if the address is already accessed.
8288 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8289   // If it is an alloca or global variable, it is always safe to load from.
8290   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8291
8292   // Otherwise, be a little bit agressive by scanning the local block where we
8293   // want to check to see if the pointer is already being loaded or stored
8294   // from/to.  If so, the previous load or store would have already trapped,
8295   // so there is no harm doing an extra load (also, CSE will later eliminate
8296   // the load entirely).
8297   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8298
8299   while (BBI != E) {
8300     --BBI;
8301
8302     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8303       if (LI->getOperand(0) == V) return true;
8304     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8305       if (SI->getOperand(1) == V) return true;
8306
8307   }
8308   return false;
8309 }
8310
8311 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8312   Value *Op = LI.getOperand(0);
8313
8314   // load (cast X) --> cast (load X) iff safe
8315   if (isa<CastInst>(Op))
8316     if (Instruction *Res = InstCombineLoadCast(*this, LI))
8317       return Res;
8318
8319   // None of the following transforms are legal for volatile loads.
8320   if (LI.isVolatile()) return 0;
8321   
8322   if (&LI.getParent()->front() != &LI) {
8323     BasicBlock::iterator BBI = &LI; --BBI;
8324     // If the instruction immediately before this is a store to the same
8325     // address, do a simple form of store->load forwarding.
8326     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8327       if (SI->getOperand(1) == LI.getOperand(0))
8328         return ReplaceInstUsesWith(LI, SI->getOperand(0));
8329     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8330       if (LIB->getOperand(0) == LI.getOperand(0))
8331         return ReplaceInstUsesWith(LI, LIB);
8332   }
8333
8334   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8335     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8336         isa<UndefValue>(GEPI->getOperand(0))) {
8337       // Insert a new store to null instruction before the load to indicate
8338       // that this code is not reachable.  We do this instead of inserting
8339       // an unreachable instruction directly because we cannot modify the
8340       // CFG.
8341       new StoreInst(UndefValue::get(LI.getType()),
8342                     Constant::getNullValue(Op->getType()), &LI);
8343       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8344     }
8345
8346   if (Constant *C = dyn_cast<Constant>(Op)) {
8347     // load null/undef -> undef
8348     if ((C->isNullValue() || isa<UndefValue>(C))) {
8349       // Insert a new store to null instruction before the load to indicate that
8350       // this code is not reachable.  We do this instead of inserting an
8351       // unreachable instruction directly because we cannot modify the CFG.
8352       new StoreInst(UndefValue::get(LI.getType()),
8353                     Constant::getNullValue(Op->getType()), &LI);
8354       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8355     }
8356
8357     // Instcombine load (constant global) into the value loaded.
8358     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8359       if (GV->isConstant() && !GV->isDeclaration())
8360         return ReplaceInstUsesWith(LI, GV->getInitializer());
8361
8362     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8363     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8364       if (CE->getOpcode() == Instruction::GetElementPtr) {
8365         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8366           if (GV->isConstant() && !GV->isDeclaration())
8367             if (Constant *V = 
8368                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8369               return ReplaceInstUsesWith(LI, V);
8370         if (CE->getOperand(0)->isNullValue()) {
8371           // Insert a new store to null instruction before the load to indicate
8372           // that this code is not reachable.  We do this instead of inserting
8373           // an unreachable instruction directly because we cannot modify the
8374           // CFG.
8375           new StoreInst(UndefValue::get(LI.getType()),
8376                         Constant::getNullValue(Op->getType()), &LI);
8377           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8378         }
8379
8380       } else if (CE->isCast()) {
8381         if (Instruction *Res = InstCombineLoadCast(*this, LI))
8382           return Res;
8383       }
8384   }
8385
8386   if (Op->hasOneUse()) {
8387     // Change select and PHI nodes to select values instead of addresses: this
8388     // helps alias analysis out a lot, allows many others simplifications, and
8389     // exposes redundancy in the code.
8390     //
8391     // Note that we cannot do the transformation unless we know that the
8392     // introduced loads cannot trap!  Something like this is valid as long as
8393     // the condition is always false: load (select bool %C, int* null, int* %G),
8394     // but it would not be valid if we transformed it to load from null
8395     // unconditionally.
8396     //
8397     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8398       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
8399       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8400           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8401         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8402                                      SI->getOperand(1)->getName()+".val"), LI);
8403         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8404                                      SI->getOperand(2)->getName()+".val"), LI);
8405         return new SelectInst(SI->getCondition(), V1, V2);
8406       }
8407
8408       // load (select (cond, null, P)) -> load P
8409       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8410         if (C->isNullValue()) {
8411           LI.setOperand(0, SI->getOperand(2));
8412           return &LI;
8413         }
8414
8415       // load (select (cond, P, null)) -> load P
8416       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8417         if (C->isNullValue()) {
8418           LI.setOperand(0, SI->getOperand(1));
8419           return &LI;
8420         }
8421     }
8422   }
8423   return 0;
8424 }
8425
8426 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
8427 /// when possible.
8428 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8429   User *CI = cast<User>(SI.getOperand(1));
8430   Value *CastOp = CI->getOperand(0);
8431
8432   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8433   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8434     const Type *SrcPTy = SrcTy->getElementType();
8435
8436     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8437       // If the source is an array, the code below will not succeed.  Check to
8438       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8439       // constants.
8440       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8441         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8442           if (ASrcTy->getNumElements() != 0) {
8443             Value* Idxs[2];
8444             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8445             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8446             SrcTy = cast<PointerType>(CastOp->getType());
8447             SrcPTy = SrcTy->getElementType();
8448           }
8449
8450       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8451           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8452                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8453
8454         // Okay, we are casting from one integer or pointer type to another of
8455         // the same size.  Instead of casting the pointer before 
8456         // the store, cast the value to be stored.
8457         Value *NewCast;
8458         Value *SIOp0 = SI.getOperand(0);
8459         Instruction::CastOps opcode = Instruction::BitCast;
8460         const Type* CastSrcTy = SIOp0->getType();
8461         const Type* CastDstTy = SrcPTy;
8462         if (isa<PointerType>(CastDstTy)) {
8463           if (CastSrcTy->isInteger())
8464             opcode = Instruction::IntToPtr;
8465         } else if (isa<IntegerType>(CastDstTy)) {
8466           if (isa<PointerType>(SIOp0->getType()))
8467             opcode = Instruction::PtrToInt;
8468         }
8469         if (Constant *C = dyn_cast<Constant>(SIOp0))
8470           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
8471         else
8472           NewCast = IC.InsertNewInstBefore(
8473             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
8474             SI);
8475         return new StoreInst(NewCast, CastOp);
8476       }
8477     }
8478   }
8479   return 0;
8480 }
8481
8482 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8483   Value *Val = SI.getOperand(0);
8484   Value *Ptr = SI.getOperand(1);
8485
8486   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
8487     EraseInstFromFunction(SI);
8488     ++NumCombined;
8489     return 0;
8490   }
8491   
8492   // If the RHS is an alloca with a single use, zapify the store, making the
8493   // alloca dead.
8494   if (Ptr->hasOneUse()) {
8495     if (isa<AllocaInst>(Ptr)) {
8496       EraseInstFromFunction(SI);
8497       ++NumCombined;
8498       return 0;
8499     }
8500     
8501     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8502       if (isa<AllocaInst>(GEP->getOperand(0)) &&
8503           GEP->getOperand(0)->hasOneUse()) {
8504         EraseInstFromFunction(SI);
8505         ++NumCombined;
8506         return 0;
8507       }
8508   }
8509
8510   // Do really simple DSE, to catch cases where there are several consequtive
8511   // stores to the same location, separated by a few arithmetic operations. This
8512   // situation often occurs with bitfield accesses.
8513   BasicBlock::iterator BBI = &SI;
8514   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8515        --ScanInsts) {
8516     --BBI;
8517     
8518     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8519       // Prev store isn't volatile, and stores to the same location?
8520       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8521         ++NumDeadStore;
8522         ++BBI;
8523         EraseInstFromFunction(*PrevSI);
8524         continue;
8525       }
8526       break;
8527     }
8528     
8529     // If this is a load, we have to stop.  However, if the loaded value is from
8530     // the pointer we're loading and is producing the pointer we're storing,
8531     // then *this* store is dead (X = load P; store X -> P).
8532     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8533       if (LI == Val && LI->getOperand(0) == Ptr) {
8534         EraseInstFromFunction(SI);
8535         ++NumCombined;
8536         return 0;
8537       }
8538       // Otherwise, this is a load from some other location.  Stores before it
8539       // may not be dead.
8540       break;
8541     }
8542     
8543     // Don't skip over loads or things that can modify memory.
8544     if (BBI->mayWriteToMemory())
8545       break;
8546   }
8547   
8548   
8549   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
8550
8551   // store X, null    -> turns into 'unreachable' in SimplifyCFG
8552   if (isa<ConstantPointerNull>(Ptr)) {
8553     if (!isa<UndefValue>(Val)) {
8554       SI.setOperand(0, UndefValue::get(Val->getType()));
8555       if (Instruction *U = dyn_cast<Instruction>(Val))
8556         AddToWorkList(U);  // Dropped a use.
8557       ++NumCombined;
8558     }
8559     return 0;  // Do not modify these!
8560   }
8561
8562   // store undef, Ptr -> noop
8563   if (isa<UndefValue>(Val)) {
8564     EraseInstFromFunction(SI);
8565     ++NumCombined;
8566     return 0;
8567   }
8568
8569   // If the pointer destination is a cast, see if we can fold the cast into the
8570   // source instead.
8571   if (isa<CastInst>(Ptr))
8572     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8573       return Res;
8574   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8575     if (CE->isCast())
8576       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8577         return Res;
8578
8579   
8580   // If this store is the last instruction in the basic block, and if the block
8581   // ends with an unconditional branch, try to move it to the successor block.
8582   BBI = &SI; ++BBI;
8583   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8584     if (BI->isUnconditional()) {
8585       // Check to see if the successor block has exactly two incoming edges.  If
8586       // so, see if the other predecessor contains a store to the same location.
8587       // if so, insert a PHI node (if needed) and move the stores down.
8588       BasicBlock *Dest = BI->getSuccessor(0);
8589
8590       pred_iterator PI = pred_begin(Dest);
8591       BasicBlock *Other = 0;
8592       if (*PI != BI->getParent())
8593         Other = *PI;
8594       ++PI;
8595       if (PI != pred_end(Dest)) {
8596         if (*PI != BI->getParent())
8597           if (Other)
8598             Other = 0;
8599           else
8600             Other = *PI;
8601         if (++PI != pred_end(Dest))
8602           Other = 0;
8603       }
8604       if (Other) {  // If only one other pred...
8605         BBI = Other->getTerminator();
8606         // Make sure this other block ends in an unconditional branch and that
8607         // there is an instruction before the branch.
8608         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8609             BBI != Other->begin()) {
8610           --BBI;
8611           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8612           
8613           // If this instruction is a store to the same location.
8614           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8615             // Okay, we know we can perform this transformation.  Insert a PHI
8616             // node now if we need it.
8617             Value *MergedVal = OtherStore->getOperand(0);
8618             if (MergedVal != SI.getOperand(0)) {
8619               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8620               PN->reserveOperandSpace(2);
8621               PN->addIncoming(SI.getOperand(0), SI.getParent());
8622               PN->addIncoming(OtherStore->getOperand(0), Other);
8623               MergedVal = InsertNewInstBefore(PN, Dest->front());
8624             }
8625             
8626             // Advance to a place where it is safe to insert the new store and
8627             // insert it.
8628             BBI = Dest->begin();
8629             while (isa<PHINode>(BBI)) ++BBI;
8630             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8631                                               OtherStore->isVolatile()), *BBI);
8632
8633             // Nuke the old stores.
8634             EraseInstFromFunction(SI);
8635             EraseInstFromFunction(*OtherStore);
8636             ++NumCombined;
8637             return 0;
8638           }
8639         }
8640       }
8641     }
8642   
8643   return 0;
8644 }
8645
8646
8647 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8648   // Change br (not X), label True, label False to: br X, label False, True
8649   Value *X = 0;
8650   BasicBlock *TrueDest;
8651   BasicBlock *FalseDest;
8652   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8653       !isa<Constant>(X)) {
8654     // Swap Destinations and condition...
8655     BI.setCondition(X);
8656     BI.setSuccessor(0, FalseDest);
8657     BI.setSuccessor(1, TrueDest);
8658     return &BI;
8659   }
8660
8661   // Cannonicalize fcmp_one -> fcmp_oeq
8662   FCmpInst::Predicate FPred; Value *Y;
8663   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
8664                              TrueDest, FalseDest)))
8665     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8666          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8667       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
8668       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8669       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8670       NewSCC->takeName(I);
8671       // Swap Destinations and condition...
8672       BI.setCondition(NewSCC);
8673       BI.setSuccessor(0, FalseDest);
8674       BI.setSuccessor(1, TrueDest);
8675       RemoveFromWorkList(I);
8676       I->eraseFromParent();
8677       AddToWorkList(NewSCC);
8678       return &BI;
8679     }
8680
8681   // Cannonicalize icmp_ne -> icmp_eq
8682   ICmpInst::Predicate IPred;
8683   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8684                       TrueDest, FalseDest)))
8685     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
8686          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8687          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8688       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8689       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8690       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8691       NewSCC->takeName(I);
8692       // Swap Destinations and condition...
8693       BI.setCondition(NewSCC);
8694       BI.setSuccessor(0, FalseDest);
8695       BI.setSuccessor(1, TrueDest);
8696       RemoveFromWorkList(I);
8697       I->eraseFromParent();;
8698       AddToWorkList(NewSCC);
8699       return &BI;
8700     }
8701
8702   return 0;
8703 }
8704
8705 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8706   Value *Cond = SI.getCondition();
8707   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8708     if (I->getOpcode() == Instruction::Add)
8709       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8710         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8711         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8712           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8713                                                 AddRHS));
8714         SI.setOperand(0, I->getOperand(0));
8715         AddToWorkList(I);
8716         return &SI;
8717       }
8718   }
8719   return 0;
8720 }
8721
8722 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8723 /// is to leave as a vector operation.
8724 static bool CheapToScalarize(Value *V, bool isConstant) {
8725   if (isa<ConstantAggregateZero>(V)) 
8726     return true;
8727   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
8728     if (isConstant) return true;
8729     // If all elts are the same, we can extract.
8730     Constant *Op0 = C->getOperand(0);
8731     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8732       if (C->getOperand(i) != Op0)
8733         return false;
8734     return true;
8735   }
8736   Instruction *I = dyn_cast<Instruction>(V);
8737   if (!I) return false;
8738   
8739   // Insert element gets simplified to the inserted element or is deleted if
8740   // this is constant idx extract element and its a constant idx insertelt.
8741   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8742       isa<ConstantInt>(I->getOperand(2)))
8743     return true;
8744   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8745     return true;
8746   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8747     if (BO->hasOneUse() &&
8748         (CheapToScalarize(BO->getOperand(0), isConstant) ||
8749          CheapToScalarize(BO->getOperand(1), isConstant)))
8750       return true;
8751   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8752     if (CI->hasOneUse() &&
8753         (CheapToScalarize(CI->getOperand(0), isConstant) ||
8754          CheapToScalarize(CI->getOperand(1), isConstant)))
8755       return true;
8756   
8757   return false;
8758 }
8759
8760 /// Read and decode a shufflevector mask.
8761 ///
8762 /// It turns undef elements into values that are larger than the number of
8763 /// elements in the input.
8764 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8765   unsigned NElts = SVI->getType()->getNumElements();
8766   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8767     return std::vector<unsigned>(NElts, 0);
8768   if (isa<UndefValue>(SVI->getOperand(2)))
8769     return std::vector<unsigned>(NElts, 2*NElts);
8770
8771   std::vector<unsigned> Result;
8772   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
8773   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8774     if (isa<UndefValue>(CP->getOperand(i)))
8775       Result.push_back(NElts*2);  // undef -> 8
8776     else
8777       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8778   return Result;
8779 }
8780
8781 /// FindScalarElement - Given a vector and an element number, see if the scalar
8782 /// value is already around as a register, for example if it were inserted then
8783 /// extracted from the vector.
8784 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8785   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8786   const VectorType *PTy = cast<VectorType>(V->getType());
8787   unsigned Width = PTy->getNumElements();
8788   if (EltNo >= Width)  // Out of range access.
8789     return UndefValue::get(PTy->getElementType());
8790   
8791   if (isa<UndefValue>(V))
8792     return UndefValue::get(PTy->getElementType());
8793   else if (isa<ConstantAggregateZero>(V))
8794     return Constant::getNullValue(PTy->getElementType());
8795   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
8796     return CP->getOperand(EltNo);
8797   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8798     // If this is an insert to a variable element, we don't know what it is.
8799     if (!isa<ConstantInt>(III->getOperand(2))) 
8800       return 0;
8801     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8802     
8803     // If this is an insert to the element we are looking for, return the
8804     // inserted value.
8805     if (EltNo == IIElt) 
8806       return III->getOperand(1);
8807     
8808     // Otherwise, the insertelement doesn't modify the value, recurse on its
8809     // vector input.
8810     return FindScalarElement(III->getOperand(0), EltNo);
8811   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8812     unsigned InEl = getShuffleMask(SVI)[EltNo];
8813     if (InEl < Width)
8814       return FindScalarElement(SVI->getOperand(0), InEl);
8815     else if (InEl < Width*2)
8816       return FindScalarElement(SVI->getOperand(1), InEl - Width);
8817     else
8818       return UndefValue::get(PTy->getElementType());
8819   }
8820   
8821   // Otherwise, we don't know.
8822   return 0;
8823 }
8824
8825 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8826
8827   // If packed val is undef, replace extract with scalar undef.
8828   if (isa<UndefValue>(EI.getOperand(0)))
8829     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8830
8831   // If packed val is constant 0, replace extract with scalar 0.
8832   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8833     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8834   
8835   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
8836     // If packed val is constant with uniform operands, replace EI
8837     // with that operand
8838     Constant *op0 = C->getOperand(0);
8839     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8840       if (C->getOperand(i) != op0) {
8841         op0 = 0; 
8842         break;
8843       }
8844     if (op0)
8845       return ReplaceInstUsesWith(EI, op0);
8846   }
8847   
8848   // If extracting a specified index from the vector, see if we can recursively
8849   // find a previously computed scalar that was inserted into the vector.
8850   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8851     // This instruction only demands the single element from the input vector.
8852     // If the input vector has a single use, simplify it based on this use
8853     // property.
8854     uint64_t IndexVal = IdxC->getZExtValue();
8855     if (EI.getOperand(0)->hasOneUse()) {
8856       uint64_t UndefElts;
8857       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8858                                                 1 << IndexVal,
8859                                                 UndefElts)) {
8860         EI.setOperand(0, V);
8861         return &EI;
8862       }
8863     }
8864     
8865     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8866       return ReplaceInstUsesWith(EI, Elt);
8867   }
8868   
8869   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8870     if (I->hasOneUse()) {
8871       // Push extractelement into predecessor operation if legal and
8872       // profitable to do so
8873       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8874         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8875         if (CheapToScalarize(BO, isConstantElt)) {
8876           ExtractElementInst *newEI0 = 
8877             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8878                                    EI.getName()+".lhs");
8879           ExtractElementInst *newEI1 =
8880             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8881                                    EI.getName()+".rhs");
8882           InsertNewInstBefore(newEI0, EI);
8883           InsertNewInstBefore(newEI1, EI);
8884           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8885         }
8886       } else if (isa<LoadInst>(I)) {
8887         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
8888                                       PointerType::get(EI.getType()), EI);
8889         GetElementPtrInst *GEP = 
8890           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8891         InsertNewInstBefore(GEP, EI);
8892         return new LoadInst(GEP);
8893       }
8894     }
8895     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8896       // Extracting the inserted element?
8897       if (IE->getOperand(2) == EI.getOperand(1))
8898         return ReplaceInstUsesWith(EI, IE->getOperand(1));
8899       // If the inserted and extracted elements are constants, they must not
8900       // be the same value, extract from the pre-inserted value instead.
8901       if (isa<Constant>(IE->getOperand(2)) &&
8902           isa<Constant>(EI.getOperand(1))) {
8903         AddUsesToWorkList(EI);
8904         EI.setOperand(0, IE->getOperand(0));
8905         return &EI;
8906       }
8907     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8908       // If this is extracting an element from a shufflevector, figure out where
8909       // it came from and extract from the appropriate input element instead.
8910       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8911         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8912         Value *Src;
8913         if (SrcIdx < SVI->getType()->getNumElements())
8914           Src = SVI->getOperand(0);
8915         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8916           SrcIdx -= SVI->getType()->getNumElements();
8917           Src = SVI->getOperand(1);
8918         } else {
8919           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8920         }
8921         return new ExtractElementInst(Src, SrcIdx);
8922       }
8923     }
8924   }
8925   return 0;
8926 }
8927
8928 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8929 /// elements from either LHS or RHS, return the shuffle mask and true. 
8930 /// Otherwise, return false.
8931 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8932                                          std::vector<Constant*> &Mask) {
8933   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8934          "Invalid CollectSingleShuffleElements");
8935   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
8936
8937   if (isa<UndefValue>(V)) {
8938     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8939     return true;
8940   } else if (V == LHS) {
8941     for (unsigned i = 0; i != NumElts; ++i)
8942       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8943     return true;
8944   } else if (V == RHS) {
8945     for (unsigned i = 0; i != NumElts; ++i)
8946       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
8947     return true;
8948   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8949     // If this is an insert of an extract from some other vector, include it.
8950     Value *VecOp    = IEI->getOperand(0);
8951     Value *ScalarOp = IEI->getOperand(1);
8952     Value *IdxOp    = IEI->getOperand(2);
8953     
8954     if (!isa<ConstantInt>(IdxOp))
8955       return false;
8956     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8957     
8958     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
8959       // Okay, we can handle this if the vector we are insertinting into is
8960       // transitively ok.
8961       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8962         // If so, update the mask to reflect the inserted undef.
8963         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
8964         return true;
8965       }      
8966     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8967       if (isa<ConstantInt>(EI->getOperand(1)) &&
8968           EI->getOperand(0)->getType() == V->getType()) {
8969         unsigned ExtractedIdx =
8970           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8971         
8972         // This must be extracting from either LHS or RHS.
8973         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8974           // Okay, we can handle this if the vector we are insertinting into is
8975           // transitively ok.
8976           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8977             // If so, update the mask to reflect the inserted value.
8978             if (EI->getOperand(0) == LHS) {
8979               Mask[InsertedIdx & (NumElts-1)] = 
8980                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8981             } else {
8982               assert(EI->getOperand(0) == RHS);
8983               Mask[InsertedIdx & (NumElts-1)] = 
8984                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
8985               
8986             }
8987             return true;
8988           }
8989         }
8990       }
8991     }
8992   }
8993   // TODO: Handle shufflevector here!
8994   
8995   return false;
8996 }
8997
8998 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8999 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
9000 /// that computes V and the LHS value of the shuffle.
9001 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
9002                                      Value *&RHS) {
9003   assert(isa<VectorType>(V->getType()) && 
9004          (RHS == 0 || V->getType() == RHS->getType()) &&
9005          "Invalid shuffle!");
9006   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9007
9008   if (isa<UndefValue>(V)) {
9009     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9010     return V;
9011   } else if (isa<ConstantAggregateZero>(V)) {
9012     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
9013     return V;
9014   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9015     // If this is an insert of an extract from some other vector, include it.
9016     Value *VecOp    = IEI->getOperand(0);
9017     Value *ScalarOp = IEI->getOperand(1);
9018     Value *IdxOp    = IEI->getOperand(2);
9019     
9020     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9021       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9022           EI->getOperand(0)->getType() == V->getType()) {
9023         unsigned ExtractedIdx =
9024           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9025         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9026         
9027         // Either the extracted from or inserted into vector must be RHSVec,
9028         // otherwise we'd end up with a shuffle of three inputs.
9029         if (EI->getOperand(0) == RHS || RHS == 0) {
9030           RHS = EI->getOperand(0);
9031           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
9032           Mask[InsertedIdx & (NumElts-1)] = 
9033             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
9034           return V;
9035         }
9036         
9037         if (VecOp == RHS) {
9038           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
9039           // Everything but the extracted element is replaced with the RHS.
9040           for (unsigned i = 0; i != NumElts; ++i) {
9041             if (i != InsertedIdx)
9042               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
9043           }
9044           return V;
9045         }
9046         
9047         // If this insertelement is a chain that comes from exactly these two
9048         // vectors, return the vector and the effective shuffle.
9049         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9050           return EI->getOperand(0);
9051         
9052       }
9053     }
9054   }
9055   // TODO: Handle shufflevector here!
9056   
9057   // Otherwise, can't do anything fancy.  Return an identity vector.
9058   for (unsigned i = 0; i != NumElts; ++i)
9059     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9060   return V;
9061 }
9062
9063 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9064   Value *VecOp    = IE.getOperand(0);
9065   Value *ScalarOp = IE.getOperand(1);
9066   Value *IdxOp    = IE.getOperand(2);
9067   
9068   // If the inserted element was extracted from some other vector, and if the 
9069   // indexes are constant, try to turn this into a shufflevector operation.
9070   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9071     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9072         EI->getOperand(0)->getType() == IE.getType()) {
9073       unsigned NumVectorElts = IE.getType()->getNumElements();
9074       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9075       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9076       
9077       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9078         return ReplaceInstUsesWith(IE, VecOp);
9079       
9080       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
9081         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9082       
9083       // If we are extracting a value from a vector, then inserting it right
9084       // back into the same place, just use the input vector.
9085       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9086         return ReplaceInstUsesWith(IE, VecOp);      
9087       
9088       // We could theoretically do this for ANY input.  However, doing so could
9089       // turn chains of insertelement instructions into a chain of shufflevector
9090       // instructions, and right now we do not merge shufflevectors.  As such,
9091       // only do this in a situation where it is clear that there is benefit.
9092       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9093         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
9094         // the values of VecOp, except then one read from EIOp0.
9095         // Build a new shuffle mask.
9096         std::vector<Constant*> Mask;
9097         if (isa<UndefValue>(VecOp))
9098           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
9099         else {
9100           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
9101           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
9102                                                        NumVectorElts));
9103         } 
9104         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9105         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
9106                                      ConstantVector::get(Mask));
9107       }
9108       
9109       // If this insertelement isn't used by some other insertelement, turn it
9110       // (and any insertelements it points to), into one big shuffle.
9111       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9112         std::vector<Constant*> Mask;
9113         Value *RHS = 0;
9114         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9115         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9116         // We now have a shuffle of LHS, RHS, Mask.
9117         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
9118       }
9119     }
9120   }
9121
9122   return 0;
9123 }
9124
9125
9126 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9127   Value *LHS = SVI.getOperand(0);
9128   Value *RHS = SVI.getOperand(1);
9129   std::vector<unsigned> Mask = getShuffleMask(&SVI);
9130
9131   bool MadeChange = false;
9132   
9133   // Undefined shuffle mask -> undefined value.
9134   if (isa<UndefValue>(SVI.getOperand(2)))
9135     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9136   
9137   // If we have shuffle(x, undef, mask) and any elements of mask refer to
9138   // the undef, change them to undefs.
9139   if (isa<UndefValue>(SVI.getOperand(1))) {
9140     // Scan to see if there are any references to the RHS.  If so, replace them
9141     // with undef element refs and set MadeChange to true.
9142     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9143       if (Mask[i] >= e && Mask[i] != 2*e) {
9144         Mask[i] = 2*e;
9145         MadeChange = true;
9146       }
9147     }
9148     
9149     if (MadeChange) {
9150       // Remap any references to RHS to use LHS.
9151       std::vector<Constant*> Elts;
9152       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9153         if (Mask[i] == 2*e)
9154           Elts.push_back(UndefValue::get(Type::Int32Ty));
9155         else
9156           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9157       }
9158       SVI.setOperand(2, ConstantVector::get(Elts));
9159     }
9160   }
9161   
9162   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
9163   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9164   if (LHS == RHS || isa<UndefValue>(LHS)) {
9165     if (isa<UndefValue>(LHS) && LHS == RHS) {
9166       // shuffle(undef,undef,mask) -> undef.
9167       return ReplaceInstUsesWith(SVI, LHS);
9168     }
9169     
9170     // Remap any references to RHS to use LHS.
9171     std::vector<Constant*> Elts;
9172     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9173       if (Mask[i] >= 2*e)
9174         Elts.push_back(UndefValue::get(Type::Int32Ty));
9175       else {
9176         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9177             (Mask[i] <  e && isa<UndefValue>(LHS)))
9178           Mask[i] = 2*e;     // Turn into undef.
9179         else
9180           Mask[i] &= (e-1);  // Force to LHS.
9181         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9182       }
9183     }
9184     SVI.setOperand(0, SVI.getOperand(1));
9185     SVI.setOperand(1, UndefValue::get(RHS->getType()));
9186     SVI.setOperand(2, ConstantVector::get(Elts));
9187     LHS = SVI.getOperand(0);
9188     RHS = SVI.getOperand(1);
9189     MadeChange = true;
9190   }
9191   
9192   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
9193   bool isLHSID = true, isRHSID = true;
9194     
9195   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9196     if (Mask[i] >= e*2) continue;  // Ignore undef values.
9197     // Is this an identity shuffle of the LHS value?
9198     isLHSID &= (Mask[i] == i);
9199       
9200     // Is this an identity shuffle of the RHS value?
9201     isRHSID &= (Mask[i]-e == i);
9202   }
9203
9204   // Eliminate identity shuffles.
9205   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9206   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
9207   
9208   // If the LHS is a shufflevector itself, see if we can combine it with this
9209   // one without producing an unusual shuffle.  Here we are really conservative:
9210   // we are absolutely afraid of producing a shuffle mask not in the input
9211   // program, because the code gen may not be smart enough to turn a merged
9212   // shuffle into two specific shuffles: it may produce worse code.  As such,
9213   // we only merge two shuffles if the result is one of the two input shuffle
9214   // masks.  In this case, merging the shuffles just removes one instruction,
9215   // which we know is safe.  This is good for things like turning:
9216   // (splat(splat)) -> splat.
9217   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9218     if (isa<UndefValue>(RHS)) {
9219       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9220
9221       std::vector<unsigned> NewMask;
9222       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9223         if (Mask[i] >= 2*e)
9224           NewMask.push_back(2*e);
9225         else
9226           NewMask.push_back(LHSMask[Mask[i]]);
9227       
9228       // If the result mask is equal to the src shuffle or this shuffle mask, do
9229       // the replacement.
9230       if (NewMask == LHSMask || NewMask == Mask) {
9231         std::vector<Constant*> Elts;
9232         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9233           if (NewMask[i] >= e*2) {
9234             Elts.push_back(UndefValue::get(Type::Int32Ty));
9235           } else {
9236             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
9237           }
9238         }
9239         return new ShuffleVectorInst(LHSSVI->getOperand(0),
9240                                      LHSSVI->getOperand(1),
9241                                      ConstantVector::get(Elts));
9242       }
9243     }
9244   }
9245
9246   return MadeChange ? &SVI : 0;
9247 }
9248
9249
9250
9251
9252 /// TryToSinkInstruction - Try to move the specified instruction from its
9253 /// current block into the beginning of DestBlock, which can only happen if it's
9254 /// safe to move the instruction past all of the instructions between it and the
9255 /// end of its block.
9256 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9257   assert(I->hasOneUse() && "Invariants didn't hold!");
9258
9259   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9260   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
9261
9262   // Do not sink alloca instructions out of the entry block.
9263   if (isa<AllocaInst>(I) && I->getParent() ==
9264         &DestBlock->getParent()->getEntryBlock())
9265     return false;
9266
9267   // We can only sink load instructions if there is nothing between the load and
9268   // the end of block that could change the value.
9269   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9270     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9271          Scan != E; ++Scan)
9272       if (Scan->mayWriteToMemory())
9273         return false;
9274   }
9275
9276   BasicBlock::iterator InsertPos = DestBlock->begin();
9277   while (isa<PHINode>(InsertPos)) ++InsertPos;
9278
9279   I->moveBefore(InsertPos);
9280   ++NumSunkInst;
9281   return true;
9282 }
9283
9284
9285 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9286 /// all reachable code to the worklist.
9287 ///
9288 /// This has a couple of tricks to make the code faster and more powerful.  In
9289 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9290 /// them to the worklist (this significantly speeds up instcombine on code where
9291 /// many instructions are dead or constant).  Additionally, if we find a branch
9292 /// whose condition is a known constant, we only visit the reachable successors.
9293 ///
9294 static void AddReachableCodeToWorklist(BasicBlock *BB, 
9295                                        SmallPtrSet<BasicBlock*, 64> &Visited,
9296                                        InstCombiner &IC,
9297                                        const TargetData *TD) {
9298   std::vector<BasicBlock*> Worklist;
9299   Worklist.push_back(BB);
9300
9301   while (!Worklist.empty()) {
9302     BB = Worklist.back();
9303     Worklist.pop_back();
9304     
9305     // We have now visited this block!  If we've already been here, ignore it.
9306     if (!Visited.insert(BB)) continue;
9307     
9308     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9309       Instruction *Inst = BBI++;
9310       
9311       // DCE instruction if trivially dead.
9312       if (isInstructionTriviallyDead(Inst)) {
9313         ++NumDeadInst;
9314         DOUT << "IC: DCE: " << *Inst;
9315         Inst->eraseFromParent();
9316         continue;
9317       }
9318       
9319       // ConstantProp instruction if trivially constant.
9320       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9321         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9322         Inst->replaceAllUsesWith(C);
9323         ++NumConstProp;
9324         Inst->eraseFromParent();
9325         continue;
9326       }
9327       
9328       IC.AddToWorkList(Inst);
9329     }
9330
9331     // Recursively visit successors.  If this is a branch or switch on a
9332     // constant, only visit the reachable successor.
9333     TerminatorInst *TI = BB->getTerminator();
9334     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9335       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9336         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9337         Worklist.push_back(BI->getSuccessor(!CondVal));
9338         continue;
9339       }
9340     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9341       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9342         // See if this is an explicit destination.
9343         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9344           if (SI->getCaseValue(i) == Cond) {
9345             Worklist.push_back(SI->getSuccessor(i));
9346             continue;
9347           }
9348         
9349         // Otherwise it is the default destination.
9350         Worklist.push_back(SI->getSuccessor(0));
9351         continue;
9352       }
9353     }
9354     
9355     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9356       Worklist.push_back(TI->getSuccessor(i));
9357   }
9358 }
9359
9360 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
9361   bool Changed = false;
9362   TD = &getAnalysis<TargetData>();
9363   
9364   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9365              << F.getNameStr() << "\n");
9366
9367   {
9368     // Do a depth-first traversal of the function, populate the worklist with
9369     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
9370     // track of which blocks we visit.
9371     SmallPtrSet<BasicBlock*, 64> Visited;
9372     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
9373
9374     // Do a quick scan over the function.  If we find any blocks that are
9375     // unreachable, remove any instructions inside of them.  This prevents
9376     // the instcombine code from having to deal with some bad special cases.
9377     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9378       if (!Visited.count(BB)) {
9379         Instruction *Term = BB->getTerminator();
9380         while (Term != BB->begin()) {   // Remove instrs bottom-up
9381           BasicBlock::iterator I = Term; --I;
9382
9383           DOUT << "IC: DCE: " << *I;
9384           ++NumDeadInst;
9385
9386           if (!I->use_empty())
9387             I->replaceAllUsesWith(UndefValue::get(I->getType()));
9388           I->eraseFromParent();
9389         }
9390       }
9391   }
9392
9393   while (!Worklist.empty()) {
9394     Instruction *I = RemoveOneFromWorkList();
9395     if (I == 0) continue;  // skip null values.
9396
9397     // Check to see if we can DCE the instruction.
9398     if (isInstructionTriviallyDead(I)) {
9399       // Add operands to the worklist.
9400       if (I->getNumOperands() < 4)
9401         AddUsesToWorkList(*I);
9402       ++NumDeadInst;
9403
9404       DOUT << "IC: DCE: " << *I;
9405
9406       I->eraseFromParent();
9407       RemoveFromWorkList(I);
9408       continue;
9409     }
9410
9411     // Instruction isn't dead, see if we can constant propagate it.
9412     if (Constant *C = ConstantFoldInstruction(I, TD)) {
9413       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9414
9415       // Add operands to the worklist.
9416       AddUsesToWorkList(*I);
9417       ReplaceInstUsesWith(*I, C);
9418
9419       ++NumConstProp;
9420       I->eraseFromParent();
9421       RemoveFromWorkList(I);
9422       continue;
9423     }
9424
9425     // See if we can trivially sink this instruction to a successor basic block.
9426     if (I->hasOneUse()) {
9427       BasicBlock *BB = I->getParent();
9428       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9429       if (UserParent != BB) {
9430         bool UserIsSuccessor = false;
9431         // See if the user is one of our successors.
9432         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9433           if (*SI == UserParent) {
9434             UserIsSuccessor = true;
9435             break;
9436           }
9437
9438         // If the user is one of our immediate successors, and if that successor
9439         // only has us as a predecessors (we'd have to split the critical edge
9440         // otherwise), we can keep going.
9441         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9442             next(pred_begin(UserParent)) == pred_end(UserParent))
9443           // Okay, the CFG is simple enough, try to sink this instruction.
9444           Changed |= TryToSinkInstruction(I, UserParent);
9445       }
9446     }
9447
9448     // Now that we have an instruction, try combining it to simplify it...
9449 #ifndef NDEBUG
9450     std::string OrigI;
9451 #endif
9452     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
9453     if (Instruction *Result = visit(*I)) {
9454       ++NumCombined;
9455       // Should we replace the old instruction with a new one?
9456       if (Result != I) {
9457         DOUT << "IC: Old = " << *I
9458              << "    New = " << *Result;
9459
9460         // Everything uses the new instruction now.
9461         I->replaceAllUsesWith(Result);
9462
9463         // Push the new instruction and any users onto the worklist.
9464         AddToWorkList(Result);
9465         AddUsersToWorkList(*Result);
9466
9467         // Move the name to the new instruction first.
9468         Result->takeName(I);
9469
9470         // Insert the new instruction into the basic block...
9471         BasicBlock *InstParent = I->getParent();
9472         BasicBlock::iterator InsertPos = I;
9473
9474         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
9475           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9476             ++InsertPos;
9477
9478         InstParent->getInstList().insert(InsertPos, Result);
9479
9480         // Make sure that we reprocess all operands now that we reduced their
9481         // use counts.
9482         AddUsesToWorkList(*I);
9483
9484         // Instructions can end up on the worklist more than once.  Make sure
9485         // we do not process an instruction that has been deleted.
9486         RemoveFromWorkList(I);
9487
9488         // Erase the old instruction.
9489         InstParent->getInstList().erase(I);
9490       } else {
9491         DOUT << "IC: Mod = " << OrigI
9492              << "    New = " << *I;
9493
9494         // If the instruction was modified, it's possible that it is now dead.
9495         // if so, remove it.
9496         if (isInstructionTriviallyDead(I)) {
9497           // Make sure we process all operands now that we are reducing their
9498           // use counts.
9499           AddUsesToWorkList(*I);
9500
9501           // Instructions may end up in the worklist more than once.  Erase all
9502           // occurrences of this instruction.
9503           RemoveFromWorkList(I);
9504           I->eraseFromParent();
9505         } else {
9506           AddToWorkList(I);
9507           AddUsersToWorkList(*I);
9508         }
9509       }
9510       Changed = true;
9511     }
9512   }
9513
9514   assert(WorklistMap.empty() && "Worklist empty, but map not?");
9515   return Changed;
9516 }
9517
9518
9519 bool InstCombiner::runOnFunction(Function &F) {
9520   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9521   
9522   bool EverMadeChange = false;
9523
9524   // Iterate while there is work to do.
9525   unsigned Iteration = 0;
9526   while (DoOneIteration(F, Iteration++)) 
9527     EverMadeChange = true;
9528   return EverMadeChange;
9529 }
9530
9531 FunctionPass *llvm::createInstructionCombiningPass() {
9532   return new InstCombiner();
9533 }
9534