simplify/clarify control flow and improve comments, no functionality change.
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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
12 // algebraic 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/Analysis/ValueTracking.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include <algorithm>
61 #include <climits>
62 #include <sstream>
63 using namespace llvm;
64 using namespace llvm::PatternMatch;
65
66 STATISTIC(NumCombined , "Number of insts combined");
67 STATISTIC(NumConstProp, "Number of constant folds");
68 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72 namespace {
73   class VISIBILITY_HIDDEN InstCombiner
74     : public FunctionPass,
75       public InstVisitor<InstCombiner, Instruction*> {
76     // Worklist of all of the instructions that need to be simplified.
77     SmallVector<Instruction*, 256> Worklist;
78     DenseMap<Instruction*, unsigned> WorklistMap;
79     TargetData *TD;
80     bool MustPreserveLCSSA;
81   public:
82     static char ID; // Pass identification, replacement for typeid
83     InstCombiner() : FunctionPass(&ID) {}
84
85     /// AddToWorkList - Add the specified instruction to the worklist if it
86     /// isn't already in it.
87     void AddToWorkList(Instruction *I) {
88       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
89         Worklist.push_back(I);
90     }
91     
92     // RemoveFromWorkList - remove I from the worklist if it exists.
93     void RemoveFromWorkList(Instruction *I) {
94       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95       if (It == WorklistMap.end()) return; // Not in worklist.
96       
97       // Don't bother moving everything down, just null out the slot.
98       Worklist[It->second] = 0;
99       
100       WorklistMap.erase(It);
101     }
102     
103     Instruction *RemoveOneFromWorkList() {
104       Instruction *I = Worklist.back();
105       Worklist.pop_back();
106       WorklistMap.erase(I);
107       return I;
108     }
109
110     
111     /// AddUsersToWorkList - When an instruction is simplified, add all users of
112     /// the instruction to the work lists because they might get more simplified
113     /// now.
114     ///
115     void AddUsersToWorkList(Value &I) {
116       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117            UI != UE; ++UI)
118         AddToWorkList(cast<Instruction>(*UI));
119     }
120
121     /// AddUsesToWorkList - When an instruction is simplified, add operands to
122     /// the work lists because they might get more simplified now.
123     ///
124     void AddUsesToWorkList(Instruction &I) {
125       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126         if (Instruction *Op = dyn_cast<Instruction>(*i))
127           AddToWorkList(Op);
128     }
129     
130     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131     /// dead.  Add all of its operands to the worklist, turning them into
132     /// undef's to reduce the number of uses of those instructions.
133     ///
134     /// Return the specified operand before it is turned into an undef.
135     ///
136     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137       Value *R = I.getOperand(op);
138       
139       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
141           AddToWorkList(Op);
142           // Set the operand to undef to drop the use.
143           *i = UndefValue::get(Op->getType());
144         }
145       
146       return R;
147     }
148
149   public:
150     virtual bool runOnFunction(Function &F);
151     
152     bool DoOneIteration(Function &F, unsigned ItNum);
153
154     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155       AU.addRequired<TargetData>();
156       AU.addPreservedID(LCSSAID);
157       AU.setPreservesCFG();
158     }
159
160     TargetData &getTargetData() const { return *TD; }
161
162     // Visitation implementation - Implement instruction combining for different
163     // instruction types.  The semantics are as follows:
164     // Return Value:
165     //    null        - No change was made
166     //     I          - Change was made, I is still valid, I may be dead though
167     //   otherwise    - Change was made, replace I with returned instruction
168     //
169     Instruction *visitAdd(BinaryOperator &I);
170     Instruction *visitSub(BinaryOperator &I);
171     Instruction *visitMul(BinaryOperator &I);
172     Instruction *visitURem(BinaryOperator &I);
173     Instruction *visitSRem(BinaryOperator &I);
174     Instruction *visitFRem(BinaryOperator &I);
175     bool SimplifyDivRemOfSelect(BinaryOperator &I);
176     Instruction *commonRemTransforms(BinaryOperator &I);
177     Instruction *commonIRemTransforms(BinaryOperator &I);
178     Instruction *commonDivTransforms(BinaryOperator &I);
179     Instruction *commonIDivTransforms(BinaryOperator &I);
180     Instruction *visitUDiv(BinaryOperator &I);
181     Instruction *visitSDiv(BinaryOperator &I);
182     Instruction *visitFDiv(BinaryOperator &I);
183     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
184     Instruction *visitAnd(BinaryOperator &I);
185     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
186     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
187                                      Value *A, Value *B, Value *C);
188     Instruction *visitOr (BinaryOperator &I);
189     Instruction *visitXor(BinaryOperator &I);
190     Instruction *visitShl(BinaryOperator &I);
191     Instruction *visitAShr(BinaryOperator &I);
192     Instruction *visitLShr(BinaryOperator &I);
193     Instruction *commonShiftTransforms(BinaryOperator &I);
194     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
195                                       Constant *RHSC);
196     Instruction *visitFCmpInst(FCmpInst &I);
197     Instruction *visitICmpInst(ICmpInst &I);
198     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
199     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
200                                                 Instruction *LHS,
201                                                 ConstantInt *RHS);
202     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
203                                 ConstantInt *DivRHS);
204
205     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
206                              ICmpInst::Predicate Cond, Instruction &I);
207     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
208                                      BinaryOperator &I);
209     Instruction *commonCastTransforms(CastInst &CI);
210     Instruction *commonIntCastTransforms(CastInst &CI);
211     Instruction *commonPointerCastTransforms(CastInst &CI);
212     Instruction *visitTrunc(TruncInst &CI);
213     Instruction *visitZExt(ZExtInst &CI);
214     Instruction *visitSExt(SExtInst &CI);
215     Instruction *visitFPTrunc(FPTruncInst &CI);
216     Instruction *visitFPExt(CastInst &CI);
217     Instruction *visitFPToUI(FPToUIInst &FI);
218     Instruction *visitFPToSI(FPToSIInst &FI);
219     Instruction *visitUIToFP(CastInst &CI);
220     Instruction *visitSIToFP(CastInst &CI);
221     Instruction *visitPtrToInt(CastInst &CI);
222     Instruction *visitIntToPtr(IntToPtrInst &CI);
223     Instruction *visitBitCast(BitCastInst &CI);
224     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
225                                 Instruction *FI);
226     Instruction *visitSelectInst(SelectInst &SI);
227     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
228     Instruction *visitCallInst(CallInst &CI);
229     Instruction *visitInvokeInst(InvokeInst &II);
230     Instruction *visitPHINode(PHINode &PN);
231     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
232     Instruction *visitAllocationInst(AllocationInst &AI);
233     Instruction *visitFreeInst(FreeInst &FI);
234     Instruction *visitLoadInst(LoadInst &LI);
235     Instruction *visitStoreInst(StoreInst &SI);
236     Instruction *visitBranchInst(BranchInst &BI);
237     Instruction *visitSwitchInst(SwitchInst &SI);
238     Instruction *visitInsertElementInst(InsertElementInst &IE);
239     Instruction *visitExtractElementInst(ExtractElementInst &EI);
240     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
241     Instruction *visitExtractValueInst(ExtractValueInst &EV);
242
243     // visitInstruction - Specify what to return for unhandled instructions...
244     Instruction *visitInstruction(Instruction &I) { return 0; }
245
246   private:
247     Instruction *visitCallSite(CallSite CS);
248     bool transformConstExprCastCall(CallSite CS);
249     Instruction *transformCallThroughTrampoline(CallSite CS);
250     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
251                                    bool DoXform = true);
252     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
253
254   public:
255     // InsertNewInstBefore - insert an instruction New before instruction Old
256     // in the program.  Add the new instruction to the worklist.
257     //
258     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
259       assert(New && New->getParent() == 0 &&
260              "New instruction already inserted into a basic block!");
261       BasicBlock *BB = Old.getParent();
262       BB->getInstList().insert(&Old, New);  // Insert inst
263       AddToWorkList(New);
264       return New;
265     }
266
267     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
268     /// This also adds the cast to the worklist.  Finally, this returns the
269     /// cast.
270     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
271                             Instruction &Pos) {
272       if (V->getType() == Ty) return V;
273
274       if (Constant *CV = dyn_cast<Constant>(V))
275         return ConstantExpr::getCast(opc, CV, Ty);
276       
277       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
278       AddToWorkList(C);
279       return C;
280     }
281         
282     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
283       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
284     }
285
286
287     // ReplaceInstUsesWith - This method is to be used when an instruction is
288     // found to be dead, replacable with another preexisting expression.  Here
289     // we add all uses of I to the worklist, replace all uses of I with the new
290     // value, then return I, so that the inst combiner will know that I was
291     // modified.
292     //
293     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
294       AddUsersToWorkList(I);         // Add all modified instrs to worklist
295       if (&I != V) {
296         I.replaceAllUsesWith(V);
297         return &I;
298       } else {
299         // If we are replacing the instruction with itself, this must be in a
300         // segment of unreachable code, so just clobber the instruction.
301         I.replaceAllUsesWith(UndefValue::get(I.getType()));
302         return &I;
303       }
304     }
305
306     // EraseInstFromFunction - When dealing with an instruction that has side
307     // effects or produces a void value, we can't rely on DCE to delete the
308     // instruction.  Instead, visit methods should return the value returned by
309     // this function.
310     Instruction *EraseInstFromFunction(Instruction &I) {
311       assert(I.use_empty() && "Cannot erase instruction that is used!");
312       AddUsesToWorkList(I);
313       RemoveFromWorkList(&I);
314       I.eraseFromParent();
315       return 0;  // Don't do anything with FI
316     }
317         
318     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
319                            APInt &KnownOne, unsigned Depth = 0) const {
320       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
321     }
322     
323     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
324                            unsigned Depth = 0) const {
325       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
326     }
327     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
328       return llvm::ComputeNumSignBits(Op, TD, Depth);
329     }
330
331   private:
332
333     /// SimplifyCommutative - This performs a few simplifications for 
334     /// commutative operators.
335     bool SimplifyCommutative(BinaryOperator &I);
336
337     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
338     /// most-complex to least-complex order.
339     bool SimplifyCompare(CmpInst &I);
340
341     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
342     /// based on the demanded bits.
343     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
344                                    APInt& KnownZero, APInt& KnownOne,
345                                    unsigned Depth);
346     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
347                               APInt& KnownZero, APInt& KnownOne,
348                               unsigned Depth=0);
349         
350     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
351     /// SimplifyDemandedBits knows about.  See if the instruction has any
352     /// properties that allow us to simplify its operands.
353     bool SimplifyDemandedInstructionBits(Instruction &Inst);
354         
355     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
356                                       uint64_t &UndefElts, unsigned Depth = 0);
357       
358     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
359     // PHI node as operand #0, see if we can fold the instruction into the PHI
360     // (which is only possible if all operands to the PHI are constants).
361     Instruction *FoldOpIntoPhi(Instruction &I);
362
363     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
364     // operator and they all are only used by the PHI, PHI together their
365     // inputs, and do the operation once, to the result of the PHI.
366     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
367     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
368     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
369
370     
371     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
372                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
373     
374     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
375                               bool isSub, Instruction &I);
376     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
377                                  bool isSigned, bool Inside, Instruction &IB);
378     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
379     Instruction *MatchBSwap(BinaryOperator &I);
380     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
381     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
382     Instruction *SimplifyMemSet(MemSetInst *MI);
383
384
385     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
386
387     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
388                                     unsigned CastOpc, int &NumCastsRemoved);
389     unsigned GetOrEnforceKnownAlignment(Value *V,
390                                         unsigned PrefAlign = 0);
391
392   };
393 }
394
395 char InstCombiner::ID = 0;
396 static RegisterPass<InstCombiner>
397 X("instcombine", "Combine redundant instructions");
398
399 // getComplexity:  Assign a complexity or rank value to LLVM Values...
400 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
401 static unsigned getComplexity(Value *V) {
402   if (isa<Instruction>(V)) {
403     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
404       return 3;
405     return 4;
406   }
407   if (isa<Argument>(V)) return 3;
408   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
409 }
410
411 // isOnlyUse - Return true if this instruction will be deleted if we stop using
412 // it.
413 static bool isOnlyUse(Value *V) {
414   return V->hasOneUse() || isa<Constant>(V);
415 }
416
417 // getPromotedType - Return the specified type promoted as it would be to pass
418 // though a va_arg area...
419 static const Type *getPromotedType(const Type *Ty) {
420   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
421     if (ITy->getBitWidth() < 32)
422       return Type::Int32Ty;
423   }
424   return Ty;
425 }
426
427 /// getBitCastOperand - If the specified operand is a CastInst, a constant
428 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
429 /// operand value, otherwise return null.
430 static Value *getBitCastOperand(Value *V) {
431   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
432     // BitCastInst?
433     return I->getOperand(0);
434   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
435     // GetElementPtrInst?
436     if (GEP->hasAllZeroIndices())
437       return GEP->getOperand(0);
438   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
439     if (CE->getOpcode() == Instruction::BitCast)
440       // BitCast ConstantExp?
441       return CE->getOperand(0);
442     else if (CE->getOpcode() == Instruction::GetElementPtr) {
443       // GetElementPtr ConstantExp?
444       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
445            I != E; ++I) {
446         ConstantInt *CI = dyn_cast<ConstantInt>(I);
447         if (!CI || !CI->isZero())
448           // Any non-zero indices? Not cast-like.
449           return 0;
450       }
451       // All-zero indices? This is just like casting.
452       return CE->getOperand(0);
453     }
454   }
455   return 0;
456 }
457
458 /// This function is a wrapper around CastInst::isEliminableCastPair. It
459 /// simply extracts arguments and returns what that function returns.
460 static Instruction::CastOps 
461 isEliminableCastPair(
462   const CastInst *CI, ///< The first cast instruction
463   unsigned opcode,       ///< The opcode of the second cast instruction
464   const Type *DstTy,     ///< The target type for the second cast instruction
465   TargetData *TD         ///< The target data for pointer size
466 ) {
467   
468   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
469   const Type *MidTy = CI->getType();                  // B from above
470
471   // Get the opcodes of the two Cast instructions
472   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
473   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
474
475   return Instruction::CastOps(
476       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
477                                      DstTy, TD->getIntPtrType()));
478 }
479
480 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
481 /// in any code being generated.  It does not require codegen if V is simple
482 /// enough or if the cast can be folded into other casts.
483 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
484                               const Type *Ty, TargetData *TD) {
485   if (V->getType() == Ty || isa<Constant>(V)) return false;
486   
487   // If this is another cast that can be eliminated, it isn't codegen either.
488   if (const CastInst *CI = dyn_cast<CastInst>(V))
489     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
490       return false;
491   return true;
492 }
493
494 // SimplifyCommutative - This performs a few simplifications for commutative
495 // operators:
496 //
497 //  1. Order operands such that they are listed from right (least complex) to
498 //     left (most complex).  This puts constants before unary operators before
499 //     binary operators.
500 //
501 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
502 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
503 //
504 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
505   bool Changed = false;
506   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
507     Changed = !I.swapOperands();
508
509   if (!I.isAssociative()) return Changed;
510   Instruction::BinaryOps Opcode = I.getOpcode();
511   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
512     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
513       if (isa<Constant>(I.getOperand(1))) {
514         Constant *Folded = ConstantExpr::get(I.getOpcode(),
515                                              cast<Constant>(I.getOperand(1)),
516                                              cast<Constant>(Op->getOperand(1)));
517         I.setOperand(0, Op->getOperand(0));
518         I.setOperand(1, Folded);
519         return true;
520       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
521         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
522             isOnlyUse(Op) && isOnlyUse(Op1)) {
523           Constant *C1 = cast<Constant>(Op->getOperand(1));
524           Constant *C2 = cast<Constant>(Op1->getOperand(1));
525
526           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
527           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
528           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
529                                                     Op1->getOperand(0),
530                                                     Op1->getName(), &I);
531           AddToWorkList(New);
532           I.setOperand(0, New);
533           I.setOperand(1, Folded);
534           return true;
535         }
536     }
537   return Changed;
538 }
539
540 /// SimplifyCompare - For a CmpInst this function just orders the operands
541 /// so that theyare listed from right (least complex) to left (most complex).
542 /// This puts constants before unary operators before binary operators.
543 bool InstCombiner::SimplifyCompare(CmpInst &I) {
544   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
545     return false;
546   I.swapOperands();
547   // Compare instructions are not associative so there's nothing else we can do.
548   return true;
549 }
550
551 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
552 // if the LHS is a constant zero (which is the 'negate' form).
553 //
554 static inline Value *dyn_castNegVal(Value *V) {
555   if (BinaryOperator::isNeg(V))
556     return BinaryOperator::getNegArgument(V);
557
558   // Constants can be considered to be negated values if they can be folded.
559   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
560     return ConstantExpr::getNeg(C);
561
562   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
563     if (C->getType()->getElementType()->isInteger())
564       return ConstantExpr::getNeg(C);
565
566   return 0;
567 }
568
569 static inline Value *dyn_castNotVal(Value *V) {
570   if (BinaryOperator::isNot(V))
571     return BinaryOperator::getNotArgument(V);
572
573   // Constants can be considered to be not'ed values...
574   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
575     return ConstantInt::get(~C->getValue());
576   return 0;
577 }
578
579 // dyn_castFoldableMul - If this value is a multiply that can be folded into
580 // other computations (because it has a constant operand), return the
581 // non-constant operand of the multiply, and set CST to point to the multiplier.
582 // Otherwise, return null.
583 //
584 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
585   if (V->hasOneUse() && V->getType()->isInteger())
586     if (Instruction *I = dyn_cast<Instruction>(V)) {
587       if (I->getOpcode() == Instruction::Mul)
588         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
589           return I->getOperand(0);
590       if (I->getOpcode() == Instruction::Shl)
591         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
592           // The multiplier is really 1 << CST.
593           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
594           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
595           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
596           return I->getOperand(0);
597         }
598     }
599   return 0;
600 }
601
602 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
603 /// expression, return it.
604 static User *dyn_castGetElementPtr(Value *V) {
605   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
606   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
607     if (CE->getOpcode() == Instruction::GetElementPtr)
608       return cast<User>(V);
609   return false;
610 }
611
612 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
613 /// opcode value. Otherwise return UserOp1.
614 static unsigned getOpcode(const Value *V) {
615   if (const Instruction *I = dyn_cast<Instruction>(V))
616     return I->getOpcode();
617   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
618     return CE->getOpcode();
619   // Use UserOp1 to mean there's no opcode.
620   return Instruction::UserOp1;
621 }
622
623 /// AddOne - Add one to a ConstantInt
624 static ConstantInt *AddOne(ConstantInt *C) {
625   APInt Val(C->getValue());
626   return ConstantInt::get(++Val);
627 }
628 /// SubOne - Subtract one from a ConstantInt
629 static ConstantInt *SubOne(ConstantInt *C) {
630   APInt Val(C->getValue());
631   return ConstantInt::get(--Val);
632 }
633 /// Add - Add two ConstantInts together
634 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
635   return ConstantInt::get(C1->getValue() + C2->getValue());
636 }
637 /// And - Bitwise AND two ConstantInts together
638 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
639   return ConstantInt::get(C1->getValue() & C2->getValue());
640 }
641 /// Subtract - Subtract one ConstantInt from another
642 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
643   return ConstantInt::get(C1->getValue() - C2->getValue());
644 }
645 /// Multiply - Multiply two ConstantInts together
646 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
647   return ConstantInt::get(C1->getValue() * C2->getValue());
648 }
649 /// MultiplyOverflows - True if the multiply can not be expressed in an int
650 /// this size.
651 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
652   uint32_t W = C1->getBitWidth();
653   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
654   if (sign) {
655     LHSExt.sext(W * 2);
656     RHSExt.sext(W * 2);
657   } else {
658     LHSExt.zext(W * 2);
659     RHSExt.zext(W * 2);
660   }
661
662   APInt MulExt = LHSExt * RHSExt;
663
664   if (sign) {
665     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
666     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
667     return MulExt.slt(Min) || MulExt.sgt(Max);
668   } else 
669     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
670 }
671
672
673 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
674 /// specified instruction is a constant integer.  If so, check to see if there
675 /// are any bits set in the constant that are not demanded.  If so, shrink the
676 /// constant and return true.
677 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
678                                    APInt Demanded) {
679   assert(I && "No instruction?");
680   assert(OpNo < I->getNumOperands() && "Operand index too large");
681
682   // If the operand is not a constant integer, nothing to do.
683   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
684   if (!OpC) return false;
685
686   // If there are no bits set that aren't demanded, nothing to do.
687   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
688   if ((~Demanded & OpC->getValue()) == 0)
689     return false;
690
691   // This instruction is producing bits that are not demanded. Shrink the RHS.
692   Demanded &= OpC->getValue();
693   I->setOperand(OpNo, ConstantInt::get(Demanded));
694   return true;
695 }
696
697 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
698 // set of known zero and one bits, compute the maximum and minimum values that
699 // could have the specified known zero and known one bits, returning them in
700 // min/max.
701 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
702                                                    const APInt& KnownZero,
703                                                    const APInt& KnownOne,
704                                                    APInt& Min, APInt& Max) {
705   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
706   assert(KnownZero.getBitWidth() == BitWidth && 
707          KnownOne.getBitWidth() == BitWidth &&
708          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
709          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
710   APInt UnknownBits = ~(KnownZero|KnownOne);
711
712   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
713   // bit if it is unknown.
714   Min = KnownOne;
715   Max = KnownOne|UnknownBits;
716   
717   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
718     Min.set(BitWidth-1);
719     Max.clear(BitWidth-1);
720   }
721 }
722
723 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
724 // a set of known zero and one bits, compute the maximum and minimum values that
725 // could have the specified known zero and known one bits, returning them in
726 // min/max.
727 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
728                                                      const APInt &KnownZero,
729                                                      const APInt &KnownOne,
730                                                      APInt &Min, APInt &Max) {
731   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
732   assert(KnownZero.getBitWidth() == BitWidth && 
733          KnownOne.getBitWidth() == BitWidth &&
734          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
735          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
736   APInt UnknownBits = ~(KnownZero|KnownOne);
737   
738   // The minimum value is when the unknown bits are all zeros.
739   Min = KnownOne;
740   // The maximum value is when the unknown bits are all ones.
741   Max = KnownOne|UnknownBits;
742 }
743
744 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
745 /// SimplifyDemandedBits knows about.  See if the instruction has any
746 /// properties that allow us to simplify its operands.
747 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
748   unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
749   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
750   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
751   
752   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
753                                      KnownZero, KnownOne, 0);
754   if (V == 0) return false;
755   if (V == &Inst) return true;
756   ReplaceInstUsesWith(Inst, V);
757   return true;
758 }
759
760 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
761 /// specified instruction operand if possible, updating it in place.  It returns
762 /// true if it made any change and false otherwise.
763 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
764                                         APInt &KnownZero, APInt &KnownOne,
765                                         unsigned Depth) {
766   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
767                                           KnownZero, KnownOne, Depth);
768   if (NewVal == 0) return false;
769   U.set(NewVal);
770   return true;
771 }
772
773
774 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
775 /// value based on the demanded bits.  When this function is called, it is known
776 /// that only the bits set in DemandedMask of the result of V are ever used
777 /// downstream. Consequently, depending on the mask and V, it may be possible
778 /// to replace V with a constant or one of its operands. In such cases, this
779 /// function does the replacement and returns true. In all other cases, it
780 /// returns false after analyzing the expression and setting KnownOne and known
781 /// to be one in the expression.  KnownZero contains all the bits that are known
782 /// to be zero in the expression. These are provided to potentially allow the
783 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
784 /// the expression. KnownOne and KnownZero always follow the invariant that 
785 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
786 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
787 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
788 /// and KnownOne must all be the same.
789 ///
790 /// This returns null if it did not change anything and it permits no
791 /// simplification.  This returns V itself if it did some simplification of V's
792 /// operands based on the information about what bits are demanded. This returns
793 /// some other non-null value if it found out that V is equal to another value
794 /// in the context where the specified bits are demanded, but not for all users.
795 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
796                                              APInt &KnownZero, APInt &KnownOne,
797                                              unsigned Depth) {
798   assert(V != 0 && "Null pointer of Value???");
799   assert(Depth <= 6 && "Limit Search Depth");
800   uint32_t BitWidth = DemandedMask.getBitWidth();
801   const IntegerType *VTy = cast<IntegerType>(V->getType());
802   assert(VTy->getBitWidth() == BitWidth && 
803          KnownZero.getBitWidth() == BitWidth && 
804          KnownOne.getBitWidth() == BitWidth &&
805          "Value *V, DemandedMask, KnownZero and KnownOne \
806           must have same BitWidth");
807   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
808     // We know all of the bits for a constant!
809     KnownOne = CI->getValue() & DemandedMask;
810     KnownZero = ~KnownOne & DemandedMask;
811     return 0;
812   }
813   
814   KnownZero.clear();
815   KnownOne.clear();
816   if (DemandedMask == 0) {   // Not demanding any bits from V.
817     if (isa<UndefValue>(V))
818       return 0;
819     return UndefValue::get(VTy);
820   }
821   
822   if (Depth == 6)        // Limit search depth.
823     return 0;
824   
825   Instruction *I = dyn_cast<Instruction>(V);
826   if (!I) return 0;        // Only analyze instructions.
827   
828   // If there are multiple uses of this value and we aren't at the root, then
829   // we can't do any simplifications of the operands, because DemandedMask
830   // only reflects the bits demanded by *one* of the users.
831   if (Depth != 0 && !I->hasOneUse()) {
832     // Compute the KnownZero/KnownOne bits to simplify things downstream.
833     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
834     return 0;
835   }
836   
837   // If this is the root being simplified, allow it to have multiple uses,
838   // just set the DemandedMask to all bits so that we can try to simplify the
839   // operands.  This allows visitTruncInst (for example) to simplify the
840   // operand of a trunc without duplicating all the logic below.
841   if (Depth == 0 && !V->hasOneUse())
842     DemandedMask = APInt::getAllOnesValue(BitWidth);
843   
844   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
845   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
846   switch (I->getOpcode()) {
847   default:
848     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
849     break;
850   case Instruction::And:
851     // If either the LHS or the RHS are Zero, the result is zero.
852     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
853                              RHSKnownZero, RHSKnownOne, Depth+1) ||
854         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
855                              LHSKnownZero, LHSKnownOne, Depth+1))
856       return I;
857     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
858     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
859
860     // If all of the demanded bits are known 1 on one side, return the other.
861     // These bits cannot contribute to the result of the 'and'.
862     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
863         (DemandedMask & ~LHSKnownZero))
864       return I->getOperand(0);
865     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
866         (DemandedMask & ~RHSKnownZero))
867       return I->getOperand(1);
868     
869     // If all of the demanded bits in the inputs are known zeros, return zero.
870     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
871       return Constant::getNullValue(VTy);
872       
873     // If the RHS is a constant, see if we can simplify it.
874     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
875       return I;
876       
877     // Output known-1 bits are only known if set in both the LHS & RHS.
878     RHSKnownOne &= LHSKnownOne;
879     // Output known-0 are known to be clear if zero in either the LHS | RHS.
880     RHSKnownZero |= LHSKnownZero;
881     break;
882   case Instruction::Or:
883     // If either the LHS or the RHS are One, the result is One.
884     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
885                              RHSKnownZero, RHSKnownOne, Depth+1) ||
886         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
887                              LHSKnownZero, LHSKnownOne, Depth+1))
888       return I;
889     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
890     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
891     
892     // If all of the demanded bits are known zero on one side, return the other.
893     // These bits cannot contribute to the result of the 'or'.
894     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
895         (DemandedMask & ~LHSKnownOne))
896       return I->getOperand(0);
897     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
898         (DemandedMask & ~RHSKnownOne))
899       return I->getOperand(1);
900
901     // If all of the potentially set bits on one side are known to be set on
902     // the other side, just use the 'other' side.
903     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
904         (DemandedMask & (~RHSKnownZero)))
905       return I->getOperand(0);
906     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
907         (DemandedMask & (~LHSKnownZero)))
908       return I->getOperand(1);
909         
910     // If the RHS is a constant, see if we can simplify it.
911     if (ShrinkDemandedConstant(I, 1, DemandedMask))
912       return I;
913           
914     // Output known-0 bits are only known if clear in both the LHS & RHS.
915     RHSKnownZero &= LHSKnownZero;
916     // Output known-1 are known to be set if set in either the LHS | RHS.
917     RHSKnownOne |= LHSKnownOne;
918     break;
919   case Instruction::Xor: {
920     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
921                              RHSKnownZero, RHSKnownOne, Depth+1) ||
922         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
923                              LHSKnownZero, LHSKnownOne, Depth+1))
924       return I;
925     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
926     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
927     
928     // If all of the demanded bits are known zero on one side, return the other.
929     // These bits cannot contribute to the result of the 'xor'.
930     if ((DemandedMask & RHSKnownZero) == DemandedMask)
931       return I->getOperand(0);
932     if ((DemandedMask & LHSKnownZero) == DemandedMask)
933       return I->getOperand(1);
934     
935     // Output known-0 bits are known if clear or set in both the LHS & RHS.
936     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
937                          (RHSKnownOne & LHSKnownOne);
938     // Output known-1 are known to be set if set in only one of the LHS, RHS.
939     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
940                         (RHSKnownOne & LHSKnownZero);
941     
942     // If all of the demanded bits are known to be zero on one side or the
943     // other, turn this into an *inclusive* or.
944     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
945     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
946       Instruction *Or =
947         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
948                                  I->getName());
949       return InsertNewInstBefore(Or, *I);
950     }
951     
952     // If all of the demanded bits on one side are known, and all of the set
953     // bits on that side are also known to be set on the other side, turn this
954     // into an AND, as we know the bits will be cleared.
955     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
956     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
957       // all known
958       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
959         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
960         Instruction *And = 
961           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
962         return InsertNewInstBefore(And, *I);
963       }
964     }
965     
966     // If the RHS is a constant, see if we can simplify it.
967     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
968     if (ShrinkDemandedConstant(I, 1, DemandedMask))
969       return I;
970     
971     RHSKnownZero = KnownZeroOut;
972     RHSKnownOne  = KnownOneOut;
973     break;
974   }
975   case Instruction::Select:
976     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
977                              RHSKnownZero, RHSKnownOne, Depth+1) ||
978         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
979                              LHSKnownZero, LHSKnownOne, Depth+1))
980       return I;
981     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
982     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
983     
984     // If the operands are constants, see if we can simplify them.
985     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
986         ShrinkDemandedConstant(I, 2, DemandedMask))
987       return I;
988     
989     // Only known if known in both the LHS and RHS.
990     RHSKnownOne &= LHSKnownOne;
991     RHSKnownZero &= LHSKnownZero;
992     break;
993   case Instruction::Trunc: {
994     unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
995     DemandedMask.zext(truncBf);
996     RHSKnownZero.zext(truncBf);
997     RHSKnownOne.zext(truncBf);
998     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
999                              RHSKnownZero, RHSKnownOne, Depth+1))
1000       return I;
1001     DemandedMask.trunc(BitWidth);
1002     RHSKnownZero.trunc(BitWidth);
1003     RHSKnownOne.trunc(BitWidth);
1004     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1005     break;
1006   }
1007   case Instruction::BitCast:
1008     if (!I->getOperand(0)->getType()->isInteger())
1009       return false;  // vector->int or fp->int?
1010     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1011                              RHSKnownZero, RHSKnownOne, Depth+1))
1012       return I;
1013     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1014     break;
1015   case Instruction::ZExt: {
1016     // Compute the bits in the result that are not present in the input.
1017     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1018     
1019     DemandedMask.trunc(SrcBitWidth);
1020     RHSKnownZero.trunc(SrcBitWidth);
1021     RHSKnownOne.trunc(SrcBitWidth);
1022     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1023                              RHSKnownZero, RHSKnownOne, Depth+1))
1024       return I;
1025     DemandedMask.zext(BitWidth);
1026     RHSKnownZero.zext(BitWidth);
1027     RHSKnownOne.zext(BitWidth);
1028     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1029     // The top bits are known to be zero.
1030     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1031     break;
1032   }
1033   case Instruction::SExt: {
1034     // Compute the bits in the result that are not present in the input.
1035     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1036     
1037     APInt InputDemandedBits = DemandedMask & 
1038                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1039
1040     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1041     // If any of the sign extended bits are demanded, we know that the sign
1042     // bit is demanded.
1043     if ((NewBits & DemandedMask) != 0)
1044       InputDemandedBits.set(SrcBitWidth-1);
1045       
1046     InputDemandedBits.trunc(SrcBitWidth);
1047     RHSKnownZero.trunc(SrcBitWidth);
1048     RHSKnownOne.trunc(SrcBitWidth);
1049     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1050                              RHSKnownZero, RHSKnownOne, Depth+1))
1051       return I;
1052     InputDemandedBits.zext(BitWidth);
1053     RHSKnownZero.zext(BitWidth);
1054     RHSKnownOne.zext(BitWidth);
1055     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1056       
1057     // If the sign bit of the input is known set or clear, then we know the
1058     // top bits of the result.
1059
1060     // If the input sign bit is known zero, or if the NewBits are not demanded
1061     // convert this into a zero extension.
1062     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1063       // Convert to ZExt cast
1064       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1065       return InsertNewInstBefore(NewCast, *I);
1066     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1067       RHSKnownOne |= NewBits;
1068     }
1069     break;
1070   }
1071   case Instruction::Add: {
1072     // Figure out what the input bits are.  If the top bits of the and result
1073     // are not demanded, then the add doesn't demand them from its input
1074     // either.
1075     unsigned NLZ = DemandedMask.countLeadingZeros();
1076       
1077     // If there is a constant on the RHS, there are a variety of xformations
1078     // we can do.
1079     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1080       // If null, this should be simplified elsewhere.  Some of the xforms here
1081       // won't work if the RHS is zero.
1082       if (RHS->isZero())
1083         break;
1084       
1085       // If the top bit of the output is demanded, demand everything from the
1086       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1087       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1088
1089       // Find information about known zero/one bits in the input.
1090       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1091                                LHSKnownZero, LHSKnownOne, Depth+1))
1092         return I;
1093
1094       // If the RHS of the add has bits set that can't affect the input, reduce
1095       // the constant.
1096       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1097         return I;
1098       
1099       // Avoid excess work.
1100       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1101         break;
1102       
1103       // Turn it into OR if input bits are zero.
1104       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1105         Instruction *Or =
1106           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1107                                    I->getName());
1108         return InsertNewInstBefore(Or, *I);
1109       }
1110       
1111       // We can say something about the output known-zero and known-one bits,
1112       // depending on potential carries from the input constant and the
1113       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1114       // bits set and the RHS constant is 0x01001, then we know we have a known
1115       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1116       
1117       // To compute this, we first compute the potential carry bits.  These are
1118       // the bits which may be modified.  I'm not aware of a better way to do
1119       // this scan.
1120       const APInt &RHSVal = RHS->getValue();
1121       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1122       
1123       // Now that we know which bits have carries, compute the known-1/0 sets.
1124       
1125       // Bits are known one if they are known zero in one operand and one in the
1126       // other, and there is no input carry.
1127       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1128                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1129       
1130       // Bits are known zero if they are known zero in both operands and there
1131       // is no input carry.
1132       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1133     } else {
1134       // If the high-bits of this ADD are not demanded, then it does not demand
1135       // the high bits of its LHS or RHS.
1136       if (DemandedMask[BitWidth-1] == 0) {
1137         // Right fill the mask of bits for this ADD to demand the most
1138         // significant bit and all those below it.
1139         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1140         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1141                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1142             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1143                                  LHSKnownZero, LHSKnownOne, Depth+1))
1144           return I;
1145       }
1146     }
1147     break;
1148   }
1149   case Instruction::Sub:
1150     // If the high-bits of this SUB are not demanded, then it does not demand
1151     // the high bits of its LHS or RHS.
1152     if (DemandedMask[BitWidth-1] == 0) {
1153       // Right fill the mask of bits for this SUB to demand the most
1154       // significant bit and all those below it.
1155       uint32_t NLZ = DemandedMask.countLeadingZeros();
1156       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1157       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1158                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1159           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1160                                LHSKnownZero, LHSKnownOne, Depth+1))
1161         return I;
1162     }
1163     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1164     // the known zeros and ones.
1165     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1166     break;
1167   case Instruction::Shl:
1168     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1169       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1170       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1171       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1172                                RHSKnownZero, RHSKnownOne, Depth+1))
1173         return I;
1174       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1175       RHSKnownZero <<= ShiftAmt;
1176       RHSKnownOne  <<= ShiftAmt;
1177       // low bits known zero.
1178       if (ShiftAmt)
1179         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1180     }
1181     break;
1182   case Instruction::LShr:
1183     // For a logical shift right
1184     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1185       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1186       
1187       // Unsigned shift right.
1188       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1189       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1190                                RHSKnownZero, RHSKnownOne, Depth+1))
1191         return I;
1192       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1193       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1194       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1195       if (ShiftAmt) {
1196         // Compute the new bits that are at the top now.
1197         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1198         RHSKnownZero |= HighBits;  // high bits known zero.
1199       }
1200     }
1201     break;
1202   case Instruction::AShr:
1203     // If this is an arithmetic shift right and only the low-bit is set, we can
1204     // always convert this into a logical shr, even if the shift amount is
1205     // variable.  The low bit of the shift cannot be an input sign bit unless
1206     // the shift amount is >= the size of the datatype, which is undefined.
1207     if (DemandedMask == 1) {
1208       // Perform the logical shift right.
1209       Instruction *NewVal = BinaryOperator::CreateLShr(
1210                         I->getOperand(0), I->getOperand(1), I->getName());
1211       return InsertNewInstBefore(NewVal, *I);
1212     }    
1213
1214     // If the sign bit is the only bit demanded by this ashr, then there is no
1215     // need to do it, the shift doesn't change the high bit.
1216     if (DemandedMask.isSignBit())
1217       return I->getOperand(0);
1218     
1219     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1220       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1221       
1222       // Signed shift right.
1223       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1224       // If any of the "high bits" are demanded, we should set the sign bit as
1225       // demanded.
1226       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1227         DemandedMaskIn.set(BitWidth-1);
1228       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1229                                RHSKnownZero, RHSKnownOne, Depth+1))
1230         return I;
1231       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1232       // Compute the new bits that are at the top now.
1233       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1234       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1235       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1236         
1237       // Handle the sign bits.
1238       APInt SignBit(APInt::getSignBit(BitWidth));
1239       // Adjust to where it is now in the mask.
1240       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1241         
1242       // If the input sign bit is known to be zero, or if none of the top bits
1243       // are demanded, turn this into an unsigned shift right.
1244       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1245           (HighBits & ~DemandedMask) == HighBits) {
1246         // Perform the logical shift right.
1247         Instruction *NewVal = BinaryOperator::CreateLShr(
1248                           I->getOperand(0), SA, I->getName());
1249         return InsertNewInstBefore(NewVal, *I);
1250       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1251         RHSKnownOne |= HighBits;
1252       }
1253     }
1254     break;
1255   case Instruction::SRem:
1256     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1257       APInt RA = Rem->getValue().abs();
1258       if (RA.isPowerOf2()) {
1259         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1260           return I->getOperand(0);
1261
1262         APInt LowBits = RA - 1;
1263         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1264         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1265                                  LHSKnownZero, LHSKnownOne, Depth+1))
1266           return I;
1267
1268         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1269           LHSKnownZero |= ~LowBits;
1270
1271         KnownZero |= LHSKnownZero & DemandedMask;
1272
1273         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1274       }
1275     }
1276     break;
1277   case Instruction::URem: {
1278     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1279     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1280     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1281                              KnownZero2, KnownOne2, Depth+1) ||
1282         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1283                              KnownZero2, KnownOne2, Depth+1))
1284       return I;
1285
1286     unsigned Leaders = KnownZero2.countLeadingOnes();
1287     Leaders = std::max(Leaders,
1288                        KnownZero2.countLeadingOnes());
1289     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1290     break;
1291   }
1292   case Instruction::Call:
1293     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1294       switch (II->getIntrinsicID()) {
1295       default: break;
1296       case Intrinsic::bswap: {
1297         // If the only bits demanded come from one byte of the bswap result,
1298         // just shift the input byte into position to eliminate the bswap.
1299         unsigned NLZ = DemandedMask.countLeadingZeros();
1300         unsigned NTZ = DemandedMask.countTrailingZeros();
1301           
1302         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1303         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1304         // have 14 leading zeros, round to 8.
1305         NLZ &= ~7;
1306         NTZ &= ~7;
1307         // If we need exactly one byte, we can do this transformation.
1308         if (BitWidth-NLZ-NTZ == 8) {
1309           unsigned ResultBit = NTZ;
1310           unsigned InputBit = BitWidth-NTZ-8;
1311           
1312           // Replace this with either a left or right shift to get the byte into
1313           // the right place.
1314           Instruction *NewVal;
1315           if (InputBit > ResultBit)
1316             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1317                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1318           else
1319             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1320                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1321           NewVal->takeName(I);
1322           return InsertNewInstBefore(NewVal, *I);
1323         }
1324           
1325         // TODO: Could compute known zero/one bits based on the input.
1326         break;
1327       }
1328       }
1329     }
1330     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1331     break;
1332   }
1333   
1334   // If the client is only demanding bits that we know, return the known
1335   // constant.
1336   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1337     return ConstantInt::get(RHSKnownOne);
1338   return false;
1339 }
1340
1341
1342 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1343 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1344 /// actually used by the caller.  This method analyzes which elements of the
1345 /// operand are undef and returns that information in UndefElts.
1346 ///
1347 /// If the information about demanded elements can be used to simplify the
1348 /// operation, the operation is simplified, then the resultant value is
1349 /// returned.  This returns null if no change was made.
1350 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1351                                                 uint64_t &UndefElts,
1352                                                 unsigned Depth) {
1353   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1354   assert(VWidth <= 64 && "Vector too wide to analyze!");
1355   uint64_t EltMask = ~0ULL >> (64-VWidth);
1356   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1357
1358   if (isa<UndefValue>(V)) {
1359     // If the entire vector is undefined, just return this info.
1360     UndefElts = EltMask;
1361     return 0;
1362   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1363     UndefElts = EltMask;
1364     return UndefValue::get(V->getType());
1365   }
1366
1367   UndefElts = 0;
1368   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1369     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1370     Constant *Undef = UndefValue::get(EltTy);
1371
1372     std::vector<Constant*> Elts;
1373     for (unsigned i = 0; i != VWidth; ++i)
1374       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1375         Elts.push_back(Undef);
1376         UndefElts |= (1ULL << i);
1377       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1378         Elts.push_back(Undef);
1379         UndefElts |= (1ULL << i);
1380       } else {                               // Otherwise, defined.
1381         Elts.push_back(CP->getOperand(i));
1382       }
1383
1384     // If we changed the constant, return it.
1385     Constant *NewCP = ConstantVector::get(Elts);
1386     return NewCP != CP ? NewCP : 0;
1387   } else if (isa<ConstantAggregateZero>(V)) {
1388     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1389     // set to undef.
1390     
1391     // Check if this is identity. If so, return 0 since we are not simplifying
1392     // anything.
1393     if (DemandedElts == ((1ULL << VWidth) -1))
1394       return 0;
1395     
1396     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1397     Constant *Zero = Constant::getNullValue(EltTy);
1398     Constant *Undef = UndefValue::get(EltTy);
1399     std::vector<Constant*> Elts;
1400     for (unsigned i = 0; i != VWidth; ++i)
1401       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1402     UndefElts = DemandedElts ^ EltMask;
1403     return ConstantVector::get(Elts);
1404   }
1405   
1406   // Limit search depth.
1407   if (Depth == 10)
1408     return false;
1409
1410   // If multiple users are using the root value, procede with
1411   // simplification conservatively assuming that all elements
1412   // are needed.
1413   if (!V->hasOneUse()) {
1414     // Quit if we find multiple users of a non-root value though.
1415     // They'll be handled when it's their turn to be visited by
1416     // the main instcombine process.
1417     if (Depth != 0)
1418       // TODO: Just compute the UndefElts information recursively.
1419       return false;
1420
1421     // Conservatively assume that all elements are needed.
1422     DemandedElts = EltMask;
1423   }
1424   
1425   Instruction *I = dyn_cast<Instruction>(V);
1426   if (!I) return false;        // Only analyze instructions.
1427   
1428   bool MadeChange = false;
1429   uint64_t UndefElts2;
1430   Value *TmpV;
1431   switch (I->getOpcode()) {
1432   default: break;
1433     
1434   case Instruction::InsertElement: {
1435     // If this is a variable index, we don't know which element it overwrites.
1436     // demand exactly the same input as we produce.
1437     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1438     if (Idx == 0) {
1439       // Note that we can't propagate undef elt info, because we don't know
1440       // which elt is getting updated.
1441       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1442                                         UndefElts2, Depth+1);
1443       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1444       break;
1445     }
1446     
1447     // If this is inserting an element that isn't demanded, remove this
1448     // insertelement.
1449     unsigned IdxNo = Idx->getZExtValue();
1450     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1451       return AddSoonDeadInstToWorklist(*I, 0);
1452     
1453     // Otherwise, the element inserted overwrites whatever was there, so the
1454     // input demanded set is simpler than the output set.
1455     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1456                                       DemandedElts & ~(1ULL << IdxNo),
1457                                       UndefElts, Depth+1);
1458     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1459
1460     // The inserted element is defined.
1461     UndefElts &= ~(1ULL << IdxNo);
1462     break;
1463   }
1464   case Instruction::ShuffleVector: {
1465     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1466     uint64_t LHSVWidth =
1467       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1468     uint64_t LeftDemanded = 0, RightDemanded = 0;
1469     for (unsigned i = 0; i < VWidth; i++) {
1470       if (DemandedElts & (1ULL << i)) {
1471         unsigned MaskVal = Shuffle->getMaskValue(i);
1472         if (MaskVal != -1u) {
1473           assert(MaskVal < LHSVWidth * 2 &&
1474                  "shufflevector mask index out of range!");
1475           if (MaskVal < LHSVWidth)
1476             LeftDemanded |= 1ULL << MaskVal;
1477           else
1478             RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
1479         }
1480       }
1481     }
1482
1483     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1484                                       UndefElts2, Depth+1);
1485     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1486
1487     uint64_t UndefElts3;
1488     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1489                                       UndefElts3, Depth+1);
1490     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1491
1492     bool NewUndefElts = false;
1493     for (unsigned i = 0; i < VWidth; i++) {
1494       unsigned MaskVal = Shuffle->getMaskValue(i);
1495       if (MaskVal == -1u) {
1496         uint64_t NewBit = 1ULL << i;
1497         UndefElts |= NewBit;
1498       } else if (MaskVal < LHSVWidth) {
1499         uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1500         NewUndefElts |= NewBit;
1501         UndefElts |= NewBit;
1502       } else {
1503         uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
1504         NewUndefElts |= NewBit;
1505         UndefElts |= NewBit;
1506       }
1507     }
1508
1509     if (NewUndefElts) {
1510       // Add additional discovered undefs.
1511       std::vector<Constant*> Elts;
1512       for (unsigned i = 0; i < VWidth; ++i) {
1513         if (UndefElts & (1ULL << i))
1514           Elts.push_back(UndefValue::get(Type::Int32Ty));
1515         else
1516           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1517                                           Shuffle->getMaskValue(i)));
1518       }
1519       I->setOperand(2, ConstantVector::get(Elts));
1520       MadeChange = true;
1521     }
1522     break;
1523   }
1524   case Instruction::BitCast: {
1525     // Vector->vector casts only.
1526     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1527     if (!VTy) break;
1528     unsigned InVWidth = VTy->getNumElements();
1529     uint64_t InputDemandedElts = 0;
1530     unsigned Ratio;
1531
1532     if (VWidth == InVWidth) {
1533       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1534       // elements as are demanded of us.
1535       Ratio = 1;
1536       InputDemandedElts = DemandedElts;
1537     } else if (VWidth > InVWidth) {
1538       // Untested so far.
1539       break;
1540       
1541       // If there are more elements in the result than there are in the source,
1542       // then an input element is live if any of the corresponding output
1543       // elements are live.
1544       Ratio = VWidth/InVWidth;
1545       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1546         if (DemandedElts & (1ULL << OutIdx))
1547           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1548       }
1549     } else {
1550       // Untested so far.
1551       break;
1552       
1553       // If there are more elements in the source than there are in the result,
1554       // then an input element is live if the corresponding output element is
1555       // live.
1556       Ratio = InVWidth/VWidth;
1557       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1558         if (DemandedElts & (1ULL << InIdx/Ratio))
1559           InputDemandedElts |= 1ULL << InIdx;
1560     }
1561     
1562     // div/rem demand all inputs, because they don't want divide by zero.
1563     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1564                                       UndefElts2, Depth+1);
1565     if (TmpV) {
1566       I->setOperand(0, TmpV);
1567       MadeChange = true;
1568     }
1569     
1570     UndefElts = UndefElts2;
1571     if (VWidth > InVWidth) {
1572       assert(0 && "Unimp");
1573       // If there are more elements in the result than there are in the source,
1574       // then an output element is undef if the corresponding input element is
1575       // undef.
1576       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1577         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1578           UndefElts |= 1ULL << OutIdx;
1579     } else if (VWidth < InVWidth) {
1580       assert(0 && "Unimp");
1581       // If there are more elements in the source than there are in the result,
1582       // then a result element is undef if all of the corresponding input
1583       // elements are undef.
1584       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1585       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1586         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1587           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1588     }
1589     break;
1590   }
1591   case Instruction::And:
1592   case Instruction::Or:
1593   case Instruction::Xor:
1594   case Instruction::Add:
1595   case Instruction::Sub:
1596   case Instruction::Mul:
1597     // div/rem demand all inputs, because they don't want divide by zero.
1598     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1599                                       UndefElts, Depth+1);
1600     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1601     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1602                                       UndefElts2, Depth+1);
1603     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1604       
1605     // Output elements are undefined if both are undefined.  Consider things
1606     // like undef&0.  The result is known zero, not undef.
1607     UndefElts &= UndefElts2;
1608     break;
1609     
1610   case Instruction::Call: {
1611     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1612     if (!II) break;
1613     switch (II->getIntrinsicID()) {
1614     default: break;
1615       
1616     // Binary vector operations that work column-wise.  A dest element is a
1617     // function of the corresponding input elements from the two inputs.
1618     case Intrinsic::x86_sse_sub_ss:
1619     case Intrinsic::x86_sse_mul_ss:
1620     case Intrinsic::x86_sse_min_ss:
1621     case Intrinsic::x86_sse_max_ss:
1622     case Intrinsic::x86_sse2_sub_sd:
1623     case Intrinsic::x86_sse2_mul_sd:
1624     case Intrinsic::x86_sse2_min_sd:
1625     case Intrinsic::x86_sse2_max_sd:
1626       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1627                                         UndefElts, Depth+1);
1628       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1629       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1630                                         UndefElts2, Depth+1);
1631       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1632
1633       // If only the low elt is demanded and this is a scalarizable intrinsic,
1634       // scalarize it now.
1635       if (DemandedElts == 1) {
1636         switch (II->getIntrinsicID()) {
1637         default: break;
1638         case Intrinsic::x86_sse_sub_ss:
1639         case Intrinsic::x86_sse_mul_ss:
1640         case Intrinsic::x86_sse2_sub_sd:
1641         case Intrinsic::x86_sse2_mul_sd:
1642           // TODO: Lower MIN/MAX/ABS/etc
1643           Value *LHS = II->getOperand(1);
1644           Value *RHS = II->getOperand(2);
1645           // Extract the element as scalars.
1646           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1647           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1648           
1649           switch (II->getIntrinsicID()) {
1650           default: assert(0 && "Case stmts out of sync!");
1651           case Intrinsic::x86_sse_sub_ss:
1652           case Intrinsic::x86_sse2_sub_sd:
1653             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1654                                                         II->getName()), *II);
1655             break;
1656           case Intrinsic::x86_sse_mul_ss:
1657           case Intrinsic::x86_sse2_mul_sd:
1658             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1659                                                          II->getName()), *II);
1660             break;
1661           }
1662           
1663           Instruction *New =
1664             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1665                                       II->getName());
1666           InsertNewInstBefore(New, *II);
1667           AddSoonDeadInstToWorklist(*II, 0);
1668           return New;
1669         }            
1670       }
1671         
1672       // Output elements are undefined if both are undefined.  Consider things
1673       // like undef&0.  The result is known zero, not undef.
1674       UndefElts &= UndefElts2;
1675       break;
1676     }
1677     break;
1678   }
1679   }
1680   return MadeChange ? I : 0;
1681 }
1682
1683
1684 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1685 /// function is designed to check a chain of associative operators for a
1686 /// potential to apply a certain optimization.  Since the optimization may be
1687 /// applicable if the expression was reassociated, this checks the chain, then
1688 /// reassociates the expression as necessary to expose the optimization
1689 /// opportunity.  This makes use of a special Functor, which must define
1690 /// 'shouldApply' and 'apply' methods.
1691 ///
1692 template<typename Functor>
1693 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1694   unsigned Opcode = Root.getOpcode();
1695   Value *LHS = Root.getOperand(0);
1696
1697   // Quick check, see if the immediate LHS matches...
1698   if (F.shouldApply(LHS))
1699     return F.apply(Root);
1700
1701   // Otherwise, if the LHS is not of the same opcode as the root, return.
1702   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1703   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1704     // Should we apply this transform to the RHS?
1705     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1706
1707     // If not to the RHS, check to see if we should apply to the LHS...
1708     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1709       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1710       ShouldApply = true;
1711     }
1712
1713     // If the functor wants to apply the optimization to the RHS of LHSI,
1714     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1715     if (ShouldApply) {
1716       // Now all of the instructions are in the current basic block, go ahead
1717       // and perform the reassociation.
1718       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1719
1720       // First move the selected RHS to the LHS of the root...
1721       Root.setOperand(0, LHSI->getOperand(1));
1722
1723       // Make what used to be the LHS of the root be the user of the root...
1724       Value *ExtraOperand = TmpLHSI->getOperand(1);
1725       if (&Root == TmpLHSI) {
1726         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1727         return 0;
1728       }
1729       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1730       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1731       BasicBlock::iterator ARI = &Root; ++ARI;
1732       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1733       ARI = Root;
1734
1735       // Now propagate the ExtraOperand down the chain of instructions until we
1736       // get to LHSI.
1737       while (TmpLHSI != LHSI) {
1738         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1739         // Move the instruction to immediately before the chain we are
1740         // constructing to avoid breaking dominance properties.
1741         NextLHSI->moveBefore(ARI);
1742         ARI = NextLHSI;
1743
1744         Value *NextOp = NextLHSI->getOperand(1);
1745         NextLHSI->setOperand(1, ExtraOperand);
1746         TmpLHSI = NextLHSI;
1747         ExtraOperand = NextOp;
1748       }
1749
1750       // Now that the instructions are reassociated, have the functor perform
1751       // the transformation...
1752       return F.apply(Root);
1753     }
1754
1755     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1756   }
1757   return 0;
1758 }
1759
1760 namespace {
1761
1762 // AddRHS - Implements: X + X --> X << 1
1763 struct AddRHS {
1764   Value *RHS;
1765   AddRHS(Value *rhs) : RHS(rhs) {}
1766   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1767   Instruction *apply(BinaryOperator &Add) const {
1768     return BinaryOperator::CreateShl(Add.getOperand(0),
1769                                      ConstantInt::get(Add.getType(), 1));
1770   }
1771 };
1772
1773 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1774 //                 iff C1&C2 == 0
1775 struct AddMaskingAnd {
1776   Constant *C2;
1777   AddMaskingAnd(Constant *c) : C2(c) {}
1778   bool shouldApply(Value *LHS) const {
1779     ConstantInt *C1;
1780     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1781            ConstantExpr::getAnd(C1, C2)->isNullValue();
1782   }
1783   Instruction *apply(BinaryOperator &Add) const {
1784     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1785   }
1786 };
1787
1788 }
1789
1790 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1791                                              InstCombiner *IC) {
1792   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1793     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1794   }
1795
1796   // Figure out if the constant is the left or the right argument.
1797   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1798   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1799
1800   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1801     if (ConstIsRHS)
1802       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1803     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1804   }
1805
1806   Value *Op0 = SO, *Op1 = ConstOperand;
1807   if (!ConstIsRHS)
1808     std::swap(Op0, Op1);
1809   Instruction *New;
1810   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1811     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1812   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1813     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1814                           SO->getName()+".cmp");
1815   else {
1816     assert(0 && "Unknown binary instruction type!");
1817     abort();
1818   }
1819   return IC->InsertNewInstBefore(New, I);
1820 }
1821
1822 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1823 // constant as the other operand, try to fold the binary operator into the
1824 // select arguments.  This also works for Cast instructions, which obviously do
1825 // not have a second operand.
1826 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1827                                      InstCombiner *IC) {
1828   // Don't modify shared select instructions
1829   if (!SI->hasOneUse()) return 0;
1830   Value *TV = SI->getOperand(1);
1831   Value *FV = SI->getOperand(2);
1832
1833   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1834     // Bool selects with constant operands can be folded to logical ops.
1835     if (SI->getType() == Type::Int1Ty) return 0;
1836
1837     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1838     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1839
1840     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1841                               SelectFalseVal);
1842   }
1843   return 0;
1844 }
1845
1846
1847 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1848 /// node as operand #0, see if we can fold the instruction into the PHI (which
1849 /// is only possible if all operands to the PHI are constants).
1850 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1851   PHINode *PN = cast<PHINode>(I.getOperand(0));
1852   unsigned NumPHIValues = PN->getNumIncomingValues();
1853   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1854
1855   // Check to see if all of the operands of the PHI are constants.  If there is
1856   // one non-constant value, remember the BB it is.  If there is more than one
1857   // or if *it* is a PHI, bail out.
1858   BasicBlock *NonConstBB = 0;
1859   for (unsigned i = 0; i != NumPHIValues; ++i)
1860     if (!isa<Constant>(PN->getIncomingValue(i))) {
1861       if (NonConstBB) return 0;  // More than one non-const value.
1862       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1863       NonConstBB = PN->getIncomingBlock(i);
1864       
1865       // If the incoming non-constant value is in I's block, we have an infinite
1866       // loop.
1867       if (NonConstBB == I.getParent())
1868         return 0;
1869     }
1870   
1871   // If there is exactly one non-constant value, we can insert a copy of the
1872   // operation in that block.  However, if this is a critical edge, we would be
1873   // inserting the computation one some other paths (e.g. inside a loop).  Only
1874   // do this if the pred block is unconditionally branching into the phi block.
1875   if (NonConstBB) {
1876     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1877     if (!BI || !BI->isUnconditional()) return 0;
1878   }
1879
1880   // Okay, we can do the transformation: create the new PHI node.
1881   PHINode *NewPN = PHINode::Create(I.getType(), "");
1882   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1883   InsertNewInstBefore(NewPN, *PN);
1884   NewPN->takeName(PN);
1885
1886   // Next, add all of the operands to the PHI.
1887   if (I.getNumOperands() == 2) {
1888     Constant *C = cast<Constant>(I.getOperand(1));
1889     for (unsigned i = 0; i != NumPHIValues; ++i) {
1890       Value *InV = 0;
1891       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1892         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1893           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1894         else
1895           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1896       } else {
1897         assert(PN->getIncomingBlock(i) == NonConstBB);
1898         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1899           InV = BinaryOperator::Create(BO->getOpcode(),
1900                                        PN->getIncomingValue(i), C, "phitmp",
1901                                        NonConstBB->getTerminator());
1902         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1903           InV = CmpInst::Create(CI->getOpcode(), 
1904                                 CI->getPredicate(),
1905                                 PN->getIncomingValue(i), C, "phitmp",
1906                                 NonConstBB->getTerminator());
1907         else
1908           assert(0 && "Unknown binop!");
1909         
1910         AddToWorkList(cast<Instruction>(InV));
1911       }
1912       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1913     }
1914   } else { 
1915     CastInst *CI = cast<CastInst>(&I);
1916     const Type *RetTy = CI->getType();
1917     for (unsigned i = 0; i != NumPHIValues; ++i) {
1918       Value *InV;
1919       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1920         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1921       } else {
1922         assert(PN->getIncomingBlock(i) == NonConstBB);
1923         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1924                                I.getType(), "phitmp", 
1925                                NonConstBB->getTerminator());
1926         AddToWorkList(cast<Instruction>(InV));
1927       }
1928       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1929     }
1930   }
1931   return ReplaceInstUsesWith(I, NewPN);
1932 }
1933
1934
1935 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1936 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1937 /// This basically requires proving that the add in the original type would not
1938 /// overflow to change the sign bit or have a carry out.
1939 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1940   // There are different heuristics we can use for this.  Here are some simple
1941   // ones.
1942   
1943   // Add has the property that adding any two 2's complement numbers can only 
1944   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1945   // have at least two sign bits, we know that the addition of the two values will
1946   // sign extend fine.
1947   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1948     return true;
1949   
1950   
1951   // If one of the operands only has one non-zero bit, and if the other operand
1952   // has a known-zero bit in a more significant place than it (not including the
1953   // sign bit) the ripple may go up to and fill the zero, but won't change the
1954   // sign.  For example, (X & ~4) + 1.
1955   
1956   // TODO: Implement.
1957   
1958   return false;
1959 }
1960
1961
1962 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1963   bool Changed = SimplifyCommutative(I);
1964   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1965
1966   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1967     // X + undef -> undef
1968     if (isa<UndefValue>(RHS))
1969       return ReplaceInstUsesWith(I, RHS);
1970
1971     // X + 0 --> X
1972     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1973       if (RHSC->isNullValue())
1974         return ReplaceInstUsesWith(I, LHS);
1975     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1976       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1977                               (I.getType())->getValueAPF()))
1978         return ReplaceInstUsesWith(I, LHS);
1979     }
1980
1981     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1982       // X + (signbit) --> X ^ signbit
1983       const APInt& Val = CI->getValue();
1984       uint32_t BitWidth = Val.getBitWidth();
1985       if (Val == APInt::getSignBit(BitWidth))
1986         return BinaryOperator::CreateXor(LHS, RHS);
1987       
1988       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1989       // (X & 254)+1 -> (X&254)|1
1990       if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
1991         return &I;
1992
1993       // zext(i1) - 1  ->  select i1, 0, -1
1994       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
1995         if (CI->isAllOnesValue() &&
1996             ZI->getOperand(0)->getType() == Type::Int1Ty)
1997           return SelectInst::Create(ZI->getOperand(0),
1998                                     Constant::getNullValue(I.getType()),
1999                                     ConstantInt::getAllOnesValue(I.getType()));
2000     }
2001
2002     if (isa<PHINode>(LHS))
2003       if (Instruction *NV = FoldOpIntoPhi(I))
2004         return NV;
2005     
2006     ConstantInt *XorRHS = 0;
2007     Value *XorLHS = 0;
2008     if (isa<ConstantInt>(RHSC) &&
2009         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2010       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2011       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2012       
2013       uint32_t Size = TySizeBits / 2;
2014       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2015       APInt CFF80Val(-C0080Val);
2016       do {
2017         if (TySizeBits > Size) {
2018           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2019           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2020           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2021               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2022             // This is a sign extend if the top bits are known zero.
2023             if (!MaskedValueIsZero(XorLHS, 
2024                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2025               Size = 0;  // Not a sign ext, but can't be any others either.
2026             break;
2027           }
2028         }
2029         Size >>= 1;
2030         C0080Val = APIntOps::lshr(C0080Val, Size);
2031         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2032       } while (Size >= 1);
2033       
2034       // FIXME: This shouldn't be necessary. When the backends can handle types
2035       // with funny bit widths then this switch statement should be removed. It
2036       // is just here to get the size of the "middle" type back up to something
2037       // that the back ends can handle.
2038       const Type *MiddleType = 0;
2039       switch (Size) {
2040         default: break;
2041         case 32: MiddleType = Type::Int32Ty; break;
2042         case 16: MiddleType = Type::Int16Ty; break;
2043         case  8: MiddleType = Type::Int8Ty; break;
2044       }
2045       if (MiddleType) {
2046         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2047         InsertNewInstBefore(NewTrunc, I);
2048         return new SExtInst(NewTrunc, I.getType(), I.getName());
2049       }
2050     }
2051   }
2052
2053   if (I.getType() == Type::Int1Ty)
2054     return BinaryOperator::CreateXor(LHS, RHS);
2055
2056   // X + X --> X << 1
2057   if (I.getType()->isInteger()) {
2058     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2059
2060     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2061       if (RHSI->getOpcode() == Instruction::Sub)
2062         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2063           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2064     }
2065     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2066       if (LHSI->getOpcode() == Instruction::Sub)
2067         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2068           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2069     }
2070   }
2071
2072   // -A + B  -->  B - A
2073   // -A + -B  -->  -(A + B)
2074   if (Value *LHSV = dyn_castNegVal(LHS)) {
2075     if (LHS->getType()->isIntOrIntVector()) {
2076       if (Value *RHSV = dyn_castNegVal(RHS)) {
2077         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2078         InsertNewInstBefore(NewAdd, I);
2079         return BinaryOperator::CreateNeg(NewAdd);
2080       }
2081     }
2082     
2083     return BinaryOperator::CreateSub(RHS, LHSV);
2084   }
2085
2086   // A + -B  -->  A - B
2087   if (!isa<Constant>(RHS))
2088     if (Value *V = dyn_castNegVal(RHS))
2089       return BinaryOperator::CreateSub(LHS, V);
2090
2091
2092   ConstantInt *C2;
2093   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2094     if (X == RHS)   // X*C + X --> X * (C+1)
2095       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2096
2097     // X*C1 + X*C2 --> X * (C1+C2)
2098     ConstantInt *C1;
2099     if (X == dyn_castFoldableMul(RHS, C1))
2100       return BinaryOperator::CreateMul(X, Add(C1, C2));
2101   }
2102
2103   // X + X*C --> X * (C+1)
2104   if (dyn_castFoldableMul(RHS, C2) == LHS)
2105     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2106
2107   // X + ~X --> -1   since   ~X = -X-1
2108   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2109     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2110   
2111
2112   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2113   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2114     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2115       return R;
2116   
2117   // A+B --> A|B iff A and B have no bits set in common.
2118   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2119     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2120     APInt LHSKnownOne(IT->getBitWidth(), 0);
2121     APInt LHSKnownZero(IT->getBitWidth(), 0);
2122     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2123     if (LHSKnownZero != 0) {
2124       APInt RHSKnownOne(IT->getBitWidth(), 0);
2125       APInt RHSKnownZero(IT->getBitWidth(), 0);
2126       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2127       
2128       // No bits in common -> bitwise or.
2129       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2130         return BinaryOperator::CreateOr(LHS, RHS);
2131     }
2132   }
2133
2134   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2135   if (I.getType()->isIntOrIntVector()) {
2136     Value *W, *X, *Y, *Z;
2137     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2138         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2139       if (W != Y) {
2140         if (W == Z) {
2141           std::swap(Y, Z);
2142         } else if (Y == X) {
2143           std::swap(W, X);
2144         } else if (X == Z) {
2145           std::swap(Y, Z);
2146           std::swap(W, X);
2147         }
2148       }
2149
2150       if (W == Y) {
2151         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2152                                                             LHS->getName()), I);
2153         return BinaryOperator::CreateMul(W, NewAdd);
2154       }
2155     }
2156   }
2157
2158   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2159     Value *X = 0;
2160     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2161       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2162
2163     // (X & FF00) + xx00  -> (X+xx00) & FF00
2164     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2165       Constant *Anded = And(CRHS, C2);
2166       if (Anded == CRHS) {
2167         // See if all bits from the first bit set in the Add RHS up are included
2168         // in the mask.  First, get the rightmost bit.
2169         const APInt& AddRHSV = CRHS->getValue();
2170
2171         // Form a mask of all bits from the lowest bit added through the top.
2172         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2173
2174         // See if the and mask includes all of these bits.
2175         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2176
2177         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2178           // Okay, the xform is safe.  Insert the new add pronto.
2179           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2180                                                             LHS->getName()), I);
2181           return BinaryOperator::CreateAnd(NewAdd, C2);
2182         }
2183       }
2184     }
2185
2186     // Try to fold constant add into select arguments.
2187     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2188       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2189         return R;
2190   }
2191
2192   // add (cast *A to intptrtype) B -> 
2193   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2194   {
2195     CastInst *CI = dyn_cast<CastInst>(LHS);
2196     Value *Other = RHS;
2197     if (!CI) {
2198       CI = dyn_cast<CastInst>(RHS);
2199       Other = LHS;
2200     }
2201     if (CI && CI->getType()->isSized() && 
2202         (CI->getType()->getPrimitiveSizeInBits() == 
2203          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2204         && isa<PointerType>(CI->getOperand(0)->getType())) {
2205       unsigned AS =
2206         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2207       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2208                                       PointerType::get(Type::Int8Ty, AS), I);
2209       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2210       return new PtrToIntInst(I2, CI->getType());
2211     }
2212   }
2213   
2214   // add (select X 0 (sub n A)) A  -->  select X A n
2215   {
2216     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2217     Value *A = RHS;
2218     if (!SI) {
2219       SI = dyn_cast<SelectInst>(RHS);
2220       A = LHS;
2221     }
2222     if (SI && SI->hasOneUse()) {
2223       Value *TV = SI->getTrueValue();
2224       Value *FV = SI->getFalseValue();
2225       Value *N;
2226
2227       // Can we fold the add into the argument of the select?
2228       // We check both true and false select arguments for a matching subtract.
2229       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2230         // Fold the add into the true select value.
2231         return SelectInst::Create(SI->getCondition(), N, A);
2232       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2233         // Fold the add into the false select value.
2234         return SelectInst::Create(SI->getCondition(), A, N);
2235     }
2236   }
2237   
2238   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2239   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2240     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2241       return ReplaceInstUsesWith(I, LHS);
2242
2243   // Check for (add (sext x), y), see if we can merge this into an
2244   // integer add followed by a sext.
2245   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2246     // (add (sext x), cst) --> (sext (add x, cst'))
2247     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2248       Constant *CI = 
2249         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2250       if (LHSConv->hasOneUse() &&
2251           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2252           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2253         // Insert the new, smaller add.
2254         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2255                                                         CI, "addconv");
2256         InsertNewInstBefore(NewAdd, I);
2257         return new SExtInst(NewAdd, I.getType());
2258       }
2259     }
2260     
2261     // (add (sext x), (sext y)) --> (sext (add int x, y))
2262     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2263       // Only do this if x/y have the same type, if at last one of them has a
2264       // single use (so we don't increase the number of sexts), and if the
2265       // integer add will not overflow.
2266       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2267           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2268           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2269                                    RHSConv->getOperand(0))) {
2270         // Insert the new integer add.
2271         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2272                                                         RHSConv->getOperand(0),
2273                                                         "addconv");
2274         InsertNewInstBefore(NewAdd, I);
2275         return new SExtInst(NewAdd, I.getType());
2276       }
2277     }
2278   }
2279   
2280   // Check for (add double (sitofp x), y), see if we can merge this into an
2281   // integer add followed by a promotion.
2282   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2283     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2284     // ... if the constant fits in the integer value.  This is useful for things
2285     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2286     // requires a constant pool load, and generally allows the add to be better
2287     // instcombined.
2288     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2289       Constant *CI = 
2290       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2291       if (LHSConv->hasOneUse() &&
2292           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2293           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2294         // Insert the new integer add.
2295         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2296                                                         CI, "addconv");
2297         InsertNewInstBefore(NewAdd, I);
2298         return new SIToFPInst(NewAdd, I.getType());
2299       }
2300     }
2301     
2302     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2303     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2304       // Only do this if x/y have the same type, if at last one of them has a
2305       // single use (so we don't increase the number of int->fp conversions),
2306       // and if the integer add will not overflow.
2307       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2308           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2309           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2310                                    RHSConv->getOperand(0))) {
2311         // Insert the new integer add.
2312         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2313                                                         RHSConv->getOperand(0),
2314                                                         "addconv");
2315         InsertNewInstBefore(NewAdd, I);
2316         return new SIToFPInst(NewAdd, I.getType());
2317       }
2318     }
2319   }
2320   
2321   return Changed ? &I : 0;
2322 }
2323
2324 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2325   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2326
2327   if (Op0 == Op1 &&                        // sub X, X  -> 0
2328       !I.getType()->isFPOrFPVector())
2329     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2330
2331   // If this is a 'B = x-(-A)', change to B = x+A...
2332   if (Value *V = dyn_castNegVal(Op1))
2333     return BinaryOperator::CreateAdd(Op0, V);
2334
2335   if (isa<UndefValue>(Op0))
2336     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2337   if (isa<UndefValue>(Op1))
2338     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2339
2340   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2341     // Replace (-1 - A) with (~A)...
2342     if (C->isAllOnesValue())
2343       return BinaryOperator::CreateNot(Op1);
2344
2345     // C - ~X == X + (1+C)
2346     Value *X = 0;
2347     if (match(Op1, m_Not(m_Value(X))))
2348       return BinaryOperator::CreateAdd(X, AddOne(C));
2349
2350     // -(X >>u 31) -> (X >>s 31)
2351     // -(X >>s 31) -> (X >>u 31)
2352     if (C->isZero()) {
2353       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2354         if (SI->getOpcode() == Instruction::LShr) {
2355           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2356             // Check to see if we are shifting out everything but the sign bit.
2357             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2358                 SI->getType()->getPrimitiveSizeInBits()-1) {
2359               // Ok, the transformation is safe.  Insert AShr.
2360               return BinaryOperator::Create(Instruction::AShr, 
2361                                           SI->getOperand(0), CU, SI->getName());
2362             }
2363           }
2364         }
2365         else if (SI->getOpcode() == Instruction::AShr) {
2366           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2367             // Check to see if we are shifting out everything but the sign bit.
2368             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2369                 SI->getType()->getPrimitiveSizeInBits()-1) {
2370               // Ok, the transformation is safe.  Insert LShr. 
2371               return BinaryOperator::CreateLShr(
2372                                           SI->getOperand(0), CU, SI->getName());
2373             }
2374           }
2375         }
2376       }
2377     }
2378
2379     // Try to fold constant sub into select arguments.
2380     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2381       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2382         return R;
2383   }
2384
2385   if (I.getType() == Type::Int1Ty)
2386     return BinaryOperator::CreateXor(Op0, Op1);
2387
2388   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2389     if (Op1I->getOpcode() == Instruction::Add &&
2390         !Op0->getType()->isFPOrFPVector()) {
2391       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2392         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2393       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2394         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2395       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2396         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2397           // C1-(X+C2) --> (C1-C2)-X
2398           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2399                                            Op1I->getOperand(0));
2400       }
2401     }
2402
2403     if (Op1I->hasOneUse()) {
2404       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2405       // is not used by anyone else...
2406       //
2407       if (Op1I->getOpcode() == Instruction::Sub &&
2408           !Op1I->getType()->isFPOrFPVector()) {
2409         // Swap the two operands of the subexpr...
2410         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2411         Op1I->setOperand(0, IIOp1);
2412         Op1I->setOperand(1, IIOp0);
2413
2414         // Create the new top level add instruction...
2415         return BinaryOperator::CreateAdd(Op0, Op1);
2416       }
2417
2418       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2419       //
2420       if (Op1I->getOpcode() == Instruction::And &&
2421           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2422         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2423
2424         Value *NewNot =
2425           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2426         return BinaryOperator::CreateAnd(Op0, NewNot);
2427       }
2428
2429       // 0 - (X sdiv C)  -> (X sdiv -C)
2430       if (Op1I->getOpcode() == Instruction::SDiv)
2431         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2432           if (CSI->isZero())
2433             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2434               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2435                                                ConstantExpr::getNeg(DivRHS));
2436
2437       // X - X*C --> X * (1-C)
2438       ConstantInt *C2 = 0;
2439       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2440         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2441         return BinaryOperator::CreateMul(Op0, CP1);
2442       }
2443     }
2444   }
2445
2446   if (!Op0->getType()->isFPOrFPVector())
2447     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2448       if (Op0I->getOpcode() == Instruction::Add) {
2449         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2450           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2451         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2452           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2453       } else if (Op0I->getOpcode() == Instruction::Sub) {
2454         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2455           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2456       }
2457     }
2458
2459   ConstantInt *C1;
2460   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2461     if (X == Op1)  // X*C - X --> X * (C-1)
2462       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2463
2464     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2465     if (X == dyn_castFoldableMul(Op1, C2))
2466       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2467   }
2468   return 0;
2469 }
2470
2471 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2472 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2473 /// TrueIfSigned if the result of the comparison is true when the input value is
2474 /// signed.
2475 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2476                            bool &TrueIfSigned) {
2477   switch (pred) {
2478   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2479     TrueIfSigned = true;
2480     return RHS->isZero();
2481   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2482     TrueIfSigned = true;
2483     return RHS->isAllOnesValue();
2484   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2485     TrueIfSigned = false;
2486     return RHS->isAllOnesValue();
2487   case ICmpInst::ICMP_UGT:
2488     // True if LHS u> RHS and RHS == high-bit-mask - 1
2489     TrueIfSigned = true;
2490     return RHS->getValue() ==
2491       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2492   case ICmpInst::ICMP_UGE: 
2493     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2494     TrueIfSigned = true;
2495     return RHS->getValue().isSignBit();
2496   default:
2497     return false;
2498   }
2499 }
2500
2501 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2502   bool Changed = SimplifyCommutative(I);
2503   Value *Op0 = I.getOperand(0);
2504
2505   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2506     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2507
2508   // Simplify mul instructions with a constant RHS...
2509   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2510     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2511
2512       // ((X << C1)*C2) == (X * (C2 << C1))
2513       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2514         if (SI->getOpcode() == Instruction::Shl)
2515           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2516             return BinaryOperator::CreateMul(SI->getOperand(0),
2517                                              ConstantExpr::getShl(CI, ShOp));
2518
2519       if (CI->isZero())
2520         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2521       if (CI->equalsInt(1))                  // X * 1  == X
2522         return ReplaceInstUsesWith(I, Op0);
2523       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2524         return BinaryOperator::CreateNeg(Op0, I.getName());
2525
2526       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2527       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2528         return BinaryOperator::CreateShl(Op0,
2529                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2530       }
2531     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2532       if (Op1F->isNullValue())
2533         return ReplaceInstUsesWith(I, Op1);
2534
2535       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2536       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2537       if (Op1F->isExactlyValue(1.0))
2538         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2539     } else if (isa<VectorType>(Op1->getType())) {
2540       if (isa<ConstantAggregateZero>(Op1))
2541         return ReplaceInstUsesWith(I, Op1);
2542
2543       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2544         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2545           return BinaryOperator::CreateNeg(Op0, I.getName());
2546
2547         // As above, vector X*splat(1.0) -> X in all defined cases.
2548         if (Constant *Splat = Op1V->getSplatValue()) {
2549           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2550             if (F->isExactlyValue(1.0))
2551               return ReplaceInstUsesWith(I, Op0);
2552           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2553             if (CI->equalsInt(1))
2554               return ReplaceInstUsesWith(I, Op0);
2555         }
2556       }
2557     }
2558     
2559     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2560       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2561           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2562         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2563         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2564                                                      Op1, "tmp");
2565         InsertNewInstBefore(Add, I);
2566         Value *C1C2 = ConstantExpr::getMul(Op1, 
2567                                            cast<Constant>(Op0I->getOperand(1)));
2568         return BinaryOperator::CreateAdd(Add, C1C2);
2569         
2570       }
2571
2572     // Try to fold constant mul into select arguments.
2573     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2574       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2575         return R;
2576
2577     if (isa<PHINode>(Op0))
2578       if (Instruction *NV = FoldOpIntoPhi(I))
2579         return NV;
2580   }
2581
2582   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2583     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2584       return BinaryOperator::CreateMul(Op0v, Op1v);
2585
2586   // (X / Y) *  Y = X - (X % Y)
2587   // (X / Y) * -Y = (X % Y) - X
2588   {
2589     Value *Op1 = I.getOperand(1);
2590     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2591     if (!BO ||
2592         (BO->getOpcode() != Instruction::UDiv && 
2593          BO->getOpcode() != Instruction::SDiv)) {
2594       Op1 = Op0;
2595       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2596     }
2597     Value *Neg = dyn_castNegVal(Op1);
2598     if (BO && BO->hasOneUse() &&
2599         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2600         (BO->getOpcode() == Instruction::UDiv ||
2601          BO->getOpcode() == Instruction::SDiv)) {
2602       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2603
2604       Instruction *Rem;
2605       if (BO->getOpcode() == Instruction::UDiv)
2606         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2607       else
2608         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2609
2610       InsertNewInstBefore(Rem, I);
2611       Rem->takeName(BO);
2612
2613       if (Op1BO == Op1)
2614         return BinaryOperator::CreateSub(Op0BO, Rem);
2615       else
2616         return BinaryOperator::CreateSub(Rem, Op0BO);
2617     }
2618   }
2619
2620   if (I.getType() == Type::Int1Ty)
2621     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2622
2623   // If one of the operands of the multiply is a cast from a boolean value, then
2624   // we know the bool is either zero or one, so this is a 'masking' multiply.
2625   // See if we can simplify things based on how the boolean was originally
2626   // formed.
2627   CastInst *BoolCast = 0;
2628   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2629     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2630       BoolCast = CI;
2631   if (!BoolCast)
2632     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2633       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2634         BoolCast = CI;
2635   if (BoolCast) {
2636     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2637       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2638       const Type *SCOpTy = SCIOp0->getType();
2639       bool TIS = false;
2640       
2641       // If the icmp is true iff the sign bit of X is set, then convert this
2642       // multiply into a shift/and combination.
2643       if (isa<ConstantInt>(SCIOp1) &&
2644           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2645           TIS) {
2646         // Shift the X value right to turn it into "all signbits".
2647         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2648                                           SCOpTy->getPrimitiveSizeInBits()-1);
2649         Value *V =
2650           InsertNewInstBefore(
2651             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2652                                             BoolCast->getOperand(0)->getName()+
2653                                             ".mask"), I);
2654
2655         // If the multiply type is not the same as the source type, sign extend
2656         // or truncate to the multiply type.
2657         if (I.getType() != V->getType()) {
2658           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2659           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2660           Instruction::CastOps opcode = 
2661             (SrcBits == DstBits ? Instruction::BitCast : 
2662              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2663           V = InsertCastBefore(opcode, V, I.getType(), I);
2664         }
2665
2666         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2667         return BinaryOperator::CreateAnd(V, OtherOp);
2668       }
2669     }
2670   }
2671
2672   return Changed ? &I : 0;
2673 }
2674
2675 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2676 /// instruction.
2677 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2678   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2679   
2680   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2681   int NonNullOperand = -1;
2682   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2683     if (ST->isNullValue())
2684       NonNullOperand = 2;
2685   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2686   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2687     if (ST->isNullValue())
2688       NonNullOperand = 1;
2689   
2690   if (NonNullOperand == -1)
2691     return false;
2692   
2693   Value *SelectCond = SI->getOperand(0);
2694   
2695   // Change the div/rem to use 'Y' instead of the select.
2696   I.setOperand(1, SI->getOperand(NonNullOperand));
2697   
2698   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2699   // problem.  However, the select, or the condition of the select may have
2700   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2701   // propagate the known value for the select into other uses of it, and
2702   // propagate a known value of the condition into its other users.
2703   
2704   // If the select and condition only have a single use, don't bother with this,
2705   // early exit.
2706   if (SI->use_empty() && SelectCond->hasOneUse())
2707     return true;
2708   
2709   // Scan the current block backward, looking for other uses of SI.
2710   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2711   
2712   while (BBI != BBFront) {
2713     --BBI;
2714     // If we found a call to a function, we can't assume it will return, so
2715     // information from below it cannot be propagated above it.
2716     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2717       break;
2718     
2719     // Replace uses of the select or its condition with the known values.
2720     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2721          I != E; ++I) {
2722       if (*I == SI) {
2723         *I = SI->getOperand(NonNullOperand);
2724         AddToWorkList(BBI);
2725       } else if (*I == SelectCond) {
2726         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2727                                    ConstantInt::getFalse();
2728         AddToWorkList(BBI);
2729       }
2730     }
2731     
2732     // If we past the instruction, quit looking for it.
2733     if (&*BBI == SI)
2734       SI = 0;
2735     if (&*BBI == SelectCond)
2736       SelectCond = 0;
2737     
2738     // If we ran out of things to eliminate, break out of the loop.
2739     if (SelectCond == 0 && SI == 0)
2740       break;
2741     
2742   }
2743   return true;
2744 }
2745
2746
2747 /// This function implements the transforms on div instructions that work
2748 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2749 /// used by the visitors to those instructions.
2750 /// @brief Transforms common to all three div instructions
2751 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2752   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2753
2754   // undef / X -> 0        for integer.
2755   // undef / X -> undef    for FP (the undef could be a snan).
2756   if (isa<UndefValue>(Op0)) {
2757     if (Op0->getType()->isFPOrFPVector())
2758       return ReplaceInstUsesWith(I, Op0);
2759     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2760   }
2761
2762   // X / undef -> undef
2763   if (isa<UndefValue>(Op1))
2764     return ReplaceInstUsesWith(I, Op1);
2765
2766   return 0;
2767 }
2768
2769 /// This function implements the transforms common to both integer division
2770 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2771 /// division instructions.
2772 /// @brief Common integer divide transforms
2773 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2774   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2775
2776   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2777   if (Op0 == Op1) {
2778     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2779       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2780       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2781       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2782     }
2783
2784     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2785     return ReplaceInstUsesWith(I, CI);
2786   }
2787   
2788   if (Instruction *Common = commonDivTransforms(I))
2789     return Common;
2790   
2791   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2792   // This does not apply for fdiv.
2793   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2794     return &I;
2795
2796   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2797     // div X, 1 == X
2798     if (RHS->equalsInt(1))
2799       return ReplaceInstUsesWith(I, Op0);
2800
2801     // (X / C1) / C2  -> X / (C1*C2)
2802     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2803       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2804         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2805           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2806             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2807           else 
2808             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2809                                           Multiply(RHS, LHSRHS));
2810         }
2811
2812     if (!RHS->isZero()) { // avoid X udiv 0
2813       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2814         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2815           return R;
2816       if (isa<PHINode>(Op0))
2817         if (Instruction *NV = FoldOpIntoPhi(I))
2818           return NV;
2819     }
2820   }
2821
2822   // 0 / X == 0, we don't need to preserve faults!
2823   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2824     if (LHS->equalsInt(0))
2825       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2826
2827   // It can't be division by zero, hence it must be division by one.
2828   if (I.getType() == Type::Int1Ty)
2829     return ReplaceInstUsesWith(I, Op0);
2830
2831   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2832     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2833       // div X, 1 == X
2834       if (X->isOne())
2835         return ReplaceInstUsesWith(I, Op0);
2836   }
2837
2838   return 0;
2839 }
2840
2841 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2842   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2843
2844   // Handle the integer div common cases
2845   if (Instruction *Common = commonIDivTransforms(I))
2846     return Common;
2847
2848   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2849     // X udiv C^2 -> X >> C
2850     // Check to see if this is an unsigned division with an exact power of 2,
2851     // if so, convert to a right shift.
2852     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2853       return BinaryOperator::CreateLShr(Op0, 
2854                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2855
2856     // X udiv C, where C >= signbit
2857     if (C->getValue().isNegative()) {
2858       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2859                                       I);
2860       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2861                                 ConstantInt::get(I.getType(), 1));
2862     }
2863   }
2864
2865   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2866   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2867     if (RHSI->getOpcode() == Instruction::Shl &&
2868         isa<ConstantInt>(RHSI->getOperand(0))) {
2869       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2870       if (C1.isPowerOf2()) {
2871         Value *N = RHSI->getOperand(1);
2872         const Type *NTy = N->getType();
2873         if (uint32_t C2 = C1.logBase2()) {
2874           Constant *C2V = ConstantInt::get(NTy, C2);
2875           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2876         }
2877         return BinaryOperator::CreateLShr(Op0, N);
2878       }
2879     }
2880   }
2881   
2882   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2883   // where C1&C2 are powers of two.
2884   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2885     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2886       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2887         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2888         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2889           // Compute the shift amounts
2890           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2891           // Construct the "on true" case of the select
2892           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2893           Instruction *TSI = BinaryOperator::CreateLShr(
2894                                                  Op0, TC, SI->getName()+".t");
2895           TSI = InsertNewInstBefore(TSI, I);
2896   
2897           // Construct the "on false" case of the select
2898           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2899           Instruction *FSI = BinaryOperator::CreateLShr(
2900                                                  Op0, FC, SI->getName()+".f");
2901           FSI = InsertNewInstBefore(FSI, I);
2902
2903           // construct the select instruction and return it.
2904           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2905         }
2906       }
2907   return 0;
2908 }
2909
2910 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2911   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2912
2913   // Handle the integer div common cases
2914   if (Instruction *Common = commonIDivTransforms(I))
2915     return Common;
2916
2917   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2918     // sdiv X, -1 == -X
2919     if (RHS->isAllOnesValue())
2920       return BinaryOperator::CreateNeg(Op0);
2921   }
2922
2923   // If the sign bits of both operands are zero (i.e. we can prove they are
2924   // unsigned inputs), turn this into a udiv.
2925   if (I.getType()->isInteger()) {
2926     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2927     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2928       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2929       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2930     }
2931   }      
2932   
2933   return 0;
2934 }
2935
2936 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2937   return commonDivTransforms(I);
2938 }
2939
2940 /// This function implements the transforms on rem instructions that work
2941 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2942 /// is used by the visitors to those instructions.
2943 /// @brief Transforms common to all three rem instructions
2944 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2945   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2946
2947   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2948     if (I.getType()->isFPOrFPVector())
2949       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2950     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2951   }
2952   if (isa<UndefValue>(Op1))
2953     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2954
2955   // Handle cases involving: rem X, (select Cond, Y, Z)
2956   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2957     return &I;
2958
2959   return 0;
2960 }
2961
2962 /// This function implements the transforms common to both integer remainder
2963 /// instructions (urem and srem). It is called by the visitors to those integer
2964 /// remainder instructions.
2965 /// @brief Common integer remainder transforms
2966 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2967   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2968
2969   if (Instruction *common = commonRemTransforms(I))
2970     return common;
2971
2972   // 0 % X == 0 for integer, we don't need to preserve faults!
2973   if (Constant *LHS = dyn_cast<Constant>(Op0))
2974     if (LHS->isNullValue())
2975       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2976
2977   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2978     // X % 0 == undef, we don't need to preserve faults!
2979     if (RHS->equalsInt(0))
2980       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2981     
2982     if (RHS->equalsInt(1))  // X % 1 == 0
2983       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2984
2985     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2986       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2987         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2988           return R;
2989       } else if (isa<PHINode>(Op0I)) {
2990         if (Instruction *NV = FoldOpIntoPhi(I))
2991           return NV;
2992       }
2993
2994       // See if we can fold away this rem instruction.
2995       if (SimplifyDemandedInstructionBits(I))
2996         return &I;
2997     }
2998   }
2999
3000   return 0;
3001 }
3002
3003 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3004   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3005
3006   if (Instruction *common = commonIRemTransforms(I))
3007     return common;
3008   
3009   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3010     // X urem C^2 -> X and C
3011     // Check to see if this is an unsigned remainder with an exact power of 2,
3012     // if so, convert to a bitwise and.
3013     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3014       if (C->getValue().isPowerOf2())
3015         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3016   }
3017
3018   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3019     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3020     if (RHSI->getOpcode() == Instruction::Shl &&
3021         isa<ConstantInt>(RHSI->getOperand(0))) {
3022       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3023         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3024         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3025                                                                    "tmp"), I);
3026         return BinaryOperator::CreateAnd(Op0, Add);
3027       }
3028     }
3029   }
3030
3031   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3032   // where C1&C2 are powers of two.
3033   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3034     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3035       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3036         // STO == 0 and SFO == 0 handled above.
3037         if ((STO->getValue().isPowerOf2()) && 
3038             (SFO->getValue().isPowerOf2())) {
3039           Value *TrueAnd = InsertNewInstBefore(
3040             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3041           Value *FalseAnd = InsertNewInstBefore(
3042             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3043           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3044         }
3045       }
3046   }
3047   
3048   return 0;
3049 }
3050
3051 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3052   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3053
3054   // Handle the integer rem common cases
3055   if (Instruction *common = commonIRemTransforms(I))
3056     return common;
3057   
3058   if (Value *RHSNeg = dyn_castNegVal(Op1))
3059     if (!isa<Constant>(RHSNeg) ||
3060         (isa<ConstantInt>(RHSNeg) &&
3061          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3062       // X % -Y -> X % Y
3063       AddUsesToWorkList(I);
3064       I.setOperand(1, RHSNeg);
3065       return &I;
3066     }
3067
3068   // If the sign bits of both operands are zero (i.e. we can prove they are
3069   // unsigned inputs), turn this into a urem.
3070   if (I.getType()->isInteger()) {
3071     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3072     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3073       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3074       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3075     }
3076   }
3077
3078   // If it's a constant vector, flip any negative values positive.
3079   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3080     unsigned VWidth = RHSV->getNumOperands();
3081
3082     bool hasNegative = false;
3083     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3084       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3085         if (RHS->getValue().isNegative())
3086           hasNegative = true;
3087
3088     if (hasNegative) {
3089       std::vector<Constant *> Elts(VWidth);
3090       for (unsigned i = 0; i != VWidth; ++i) {
3091         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3092           if (RHS->getValue().isNegative())
3093             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3094           else
3095             Elts[i] = RHS;
3096         }
3097       }
3098
3099       Constant *NewRHSV = ConstantVector::get(Elts);
3100       if (NewRHSV != RHSV) {
3101         AddUsesToWorkList(I);
3102         I.setOperand(1, NewRHSV);
3103         return &I;
3104       }
3105     }
3106   }
3107
3108   return 0;
3109 }
3110
3111 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3112   return commonRemTransforms(I);
3113 }
3114
3115 // isOneBitSet - Return true if there is exactly one bit set in the specified
3116 // constant.
3117 static bool isOneBitSet(const ConstantInt *CI) {
3118   return CI->getValue().isPowerOf2();
3119 }
3120
3121 // isHighOnes - Return true if the constant is of the form 1+0+.
3122 // This is the same as lowones(~X).
3123 static bool isHighOnes(const ConstantInt *CI) {
3124   return (~CI->getValue() + 1).isPowerOf2();
3125 }
3126
3127 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3128 /// are carefully arranged to allow folding of expressions such as:
3129 ///
3130 ///      (A < B) | (A > B) --> (A != B)
3131 ///
3132 /// Note that this is only valid if the first and second predicates have the
3133 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3134 ///
3135 /// Three bits are used to represent the condition, as follows:
3136 ///   0  A > B
3137 ///   1  A == B
3138 ///   2  A < B
3139 ///
3140 /// <=>  Value  Definition
3141 /// 000     0   Always false
3142 /// 001     1   A >  B
3143 /// 010     2   A == B
3144 /// 011     3   A >= B
3145 /// 100     4   A <  B
3146 /// 101     5   A != B
3147 /// 110     6   A <= B
3148 /// 111     7   Always true
3149 ///  
3150 static unsigned getICmpCode(const ICmpInst *ICI) {
3151   switch (ICI->getPredicate()) {
3152     // False -> 0
3153   case ICmpInst::ICMP_UGT: return 1;  // 001
3154   case ICmpInst::ICMP_SGT: return 1;  // 001
3155   case ICmpInst::ICMP_EQ:  return 2;  // 010
3156   case ICmpInst::ICMP_UGE: return 3;  // 011
3157   case ICmpInst::ICMP_SGE: return 3;  // 011
3158   case ICmpInst::ICMP_ULT: return 4;  // 100
3159   case ICmpInst::ICMP_SLT: return 4;  // 100
3160   case ICmpInst::ICMP_NE:  return 5;  // 101
3161   case ICmpInst::ICMP_ULE: return 6;  // 110
3162   case ICmpInst::ICMP_SLE: return 6;  // 110
3163     // True -> 7
3164   default:
3165     assert(0 && "Invalid ICmp predicate!");
3166     return 0;
3167   }
3168 }
3169
3170 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3171 /// predicate into a three bit mask. It also returns whether it is an ordered
3172 /// predicate by reference.
3173 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3174   isOrdered = false;
3175   switch (CC) {
3176   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3177   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3178   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3179   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3180   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3181   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3182   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3183   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3184   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3185   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3186   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3187   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3188   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3189   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3190     // True -> 7
3191   default:
3192     // Not expecting FCMP_FALSE and FCMP_TRUE;
3193     assert(0 && "Unexpected FCmp predicate!");
3194     return 0;
3195   }
3196 }
3197
3198 /// getICmpValue - This is the complement of getICmpCode, which turns an
3199 /// opcode and two operands into either a constant true or false, or a brand 
3200 /// new ICmp instruction. The sign is passed in to determine which kind
3201 /// of predicate to use in the new icmp instruction.
3202 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3203   switch (code) {
3204   default: assert(0 && "Illegal ICmp code!");
3205   case  0: return ConstantInt::getFalse();
3206   case  1: 
3207     if (sign)
3208       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3209     else
3210       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3211   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3212   case  3: 
3213     if (sign)
3214       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3215     else
3216       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3217   case  4: 
3218     if (sign)
3219       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3220     else
3221       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3222   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3223   case  6: 
3224     if (sign)
3225       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3226     else
3227       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3228   case  7: return ConstantInt::getTrue();
3229   }
3230 }
3231
3232 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3233 /// opcode and two operands into either a FCmp instruction. isordered is passed
3234 /// in to determine which kind of predicate to use in the new fcmp instruction.
3235 static Value *getFCmpValue(bool isordered, unsigned code,
3236                            Value *LHS, Value *RHS) {
3237   switch (code) {
3238   default: assert(0 && "Illegal FCmp code!");
3239   case  0:
3240     if (isordered)
3241       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3242     else
3243       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3244   case  1: 
3245     if (isordered)
3246       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3247     else
3248       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3249   case  2: 
3250     if (isordered)
3251       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3252     else
3253       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3254   case  3: 
3255     if (isordered)
3256       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3257     else
3258       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3259   case  4: 
3260     if (isordered)
3261       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3262     else
3263       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3264   case  5: 
3265     if (isordered)
3266       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3267     else
3268       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3269   case  6: 
3270     if (isordered)
3271       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3272     else
3273       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3274   case  7: return ConstantInt::getTrue();
3275   }
3276 }
3277
3278 /// PredicatesFoldable - Return true if both predicates match sign or if at
3279 /// least one of them is an equality comparison (which is signless).
3280 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3281   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3282          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3283          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3284 }
3285
3286 namespace { 
3287 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3288 struct FoldICmpLogical {
3289   InstCombiner &IC;
3290   Value *LHS, *RHS;
3291   ICmpInst::Predicate pred;
3292   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3293     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3294       pred(ICI->getPredicate()) {}
3295   bool shouldApply(Value *V) const {
3296     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3297       if (PredicatesFoldable(pred, ICI->getPredicate()))
3298         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3299                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3300     return false;
3301   }
3302   Instruction *apply(Instruction &Log) const {
3303     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3304     if (ICI->getOperand(0) != LHS) {
3305       assert(ICI->getOperand(1) == LHS);
3306       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3307     }
3308
3309     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3310     unsigned LHSCode = getICmpCode(ICI);
3311     unsigned RHSCode = getICmpCode(RHSICI);
3312     unsigned Code;
3313     switch (Log.getOpcode()) {
3314     case Instruction::And: Code = LHSCode & RHSCode; break;
3315     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3316     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3317     default: assert(0 && "Illegal logical opcode!"); return 0;
3318     }
3319
3320     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3321                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3322       
3323     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3324     if (Instruction *I = dyn_cast<Instruction>(RV))
3325       return I;
3326     // Otherwise, it's a constant boolean value...
3327     return IC.ReplaceInstUsesWith(Log, RV);
3328   }
3329 };
3330 } // end anonymous namespace
3331
3332 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3333 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3334 // guaranteed to be a binary operator.
3335 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3336                                     ConstantInt *OpRHS,
3337                                     ConstantInt *AndRHS,
3338                                     BinaryOperator &TheAnd) {
3339   Value *X = Op->getOperand(0);
3340   Constant *Together = 0;
3341   if (!Op->isShift())
3342     Together = And(AndRHS, OpRHS);
3343
3344   switch (Op->getOpcode()) {
3345   case Instruction::Xor:
3346     if (Op->hasOneUse()) {
3347       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3348       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3349       InsertNewInstBefore(And, TheAnd);
3350       And->takeName(Op);
3351       return BinaryOperator::CreateXor(And, Together);
3352     }
3353     break;
3354   case Instruction::Or:
3355     if (Together == AndRHS) // (X | C) & C --> C
3356       return ReplaceInstUsesWith(TheAnd, AndRHS);
3357
3358     if (Op->hasOneUse() && Together != OpRHS) {
3359       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3360       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3361       InsertNewInstBefore(Or, TheAnd);
3362       Or->takeName(Op);
3363       return BinaryOperator::CreateAnd(Or, AndRHS);
3364     }
3365     break;
3366   case Instruction::Add:
3367     if (Op->hasOneUse()) {
3368       // Adding a one to a single bit bit-field should be turned into an XOR
3369       // of the bit.  First thing to check is to see if this AND is with a
3370       // single bit constant.
3371       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3372
3373       // If there is only one bit set...
3374       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3375         // Ok, at this point, we know that we are masking the result of the
3376         // ADD down to exactly one bit.  If the constant we are adding has
3377         // no bits set below this bit, then we can eliminate the ADD.
3378         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3379
3380         // Check to see if any bits below the one bit set in AndRHSV are set.
3381         if ((AddRHS & (AndRHSV-1)) == 0) {
3382           // If not, the only thing that can effect the output of the AND is
3383           // the bit specified by AndRHSV.  If that bit is set, the effect of
3384           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3385           // no effect.
3386           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3387             TheAnd.setOperand(0, X);
3388             return &TheAnd;
3389           } else {
3390             // Pull the XOR out of the AND.
3391             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3392             InsertNewInstBefore(NewAnd, TheAnd);
3393             NewAnd->takeName(Op);
3394             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3395           }
3396         }
3397       }
3398     }
3399     break;
3400
3401   case Instruction::Shl: {
3402     // We know that the AND will not produce any of the bits shifted in, so if
3403     // the anded constant includes them, clear them now!
3404     //
3405     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3406     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3407     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3408     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3409
3410     if (CI->getValue() == ShlMask) { 
3411     // Masking out bits that the shift already masks
3412       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3413     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3414       TheAnd.setOperand(1, CI);
3415       return &TheAnd;
3416     }
3417     break;
3418   }
3419   case Instruction::LShr:
3420   {
3421     // We know that the AND will not produce any of the bits shifted in, so if
3422     // the anded constant includes them, clear them now!  This only applies to
3423     // unsigned shifts, because a signed shr may bring in set bits!
3424     //
3425     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3426     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3427     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3428     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3429
3430     if (CI->getValue() == ShrMask) {   
3431     // Masking out bits that the shift already masks.
3432       return ReplaceInstUsesWith(TheAnd, Op);
3433     } else if (CI != AndRHS) {
3434       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3435       return &TheAnd;
3436     }
3437     break;
3438   }
3439   case Instruction::AShr:
3440     // Signed shr.
3441     // See if this is shifting in some sign extension, then masking it out
3442     // with an and.
3443     if (Op->hasOneUse()) {
3444       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3445       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3446       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3447       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3448       if (C == AndRHS) {          // Masking out bits shifted in.
3449         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3450         // Make the argument unsigned.
3451         Value *ShVal = Op->getOperand(0);
3452         ShVal = InsertNewInstBefore(
3453             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3454                                    Op->getName()), TheAnd);
3455         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3456       }
3457     }
3458     break;
3459   }
3460   return 0;
3461 }
3462
3463
3464 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3465 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3466 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3467 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3468 /// insert new instructions.
3469 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3470                                            bool isSigned, bool Inside, 
3471                                            Instruction &IB) {
3472   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3473             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3474          "Lo is not <= Hi in range emission code!");
3475     
3476   if (Inside) {
3477     if (Lo == Hi)  // Trivially false.
3478       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3479
3480     // V >= Min && V < Hi --> V < Hi
3481     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3482       ICmpInst::Predicate pred = (isSigned ? 
3483         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3484       return new ICmpInst(pred, V, Hi);
3485     }
3486
3487     // Emit V-Lo <u Hi-Lo
3488     Constant *NegLo = ConstantExpr::getNeg(Lo);
3489     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3490     InsertNewInstBefore(Add, IB);
3491     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3492     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3493   }
3494
3495   if (Lo == Hi)  // Trivially true.
3496     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3497
3498   // V < Min || V >= Hi -> V > Hi-1
3499   Hi = SubOne(cast<ConstantInt>(Hi));
3500   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3501     ICmpInst::Predicate pred = (isSigned ? 
3502         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3503     return new ICmpInst(pred, V, Hi);
3504   }
3505
3506   // Emit V-Lo >u Hi-1-Lo
3507   // Note that Hi has already had one subtracted from it, above.
3508   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3509   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3510   InsertNewInstBefore(Add, IB);
3511   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3512   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3513 }
3514
3515 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3516 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3517 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3518 // not, since all 1s are not contiguous.
3519 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3520   const APInt& V = Val->getValue();
3521   uint32_t BitWidth = Val->getType()->getBitWidth();
3522   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3523
3524   // look for the first zero bit after the run of ones
3525   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3526   // look for the first non-zero bit
3527   ME = V.getActiveBits(); 
3528   return true;
3529 }
3530
3531 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3532 /// where isSub determines whether the operator is a sub.  If we can fold one of
3533 /// the following xforms:
3534 /// 
3535 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3536 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3537 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3538 ///
3539 /// return (A +/- B).
3540 ///
3541 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3542                                         ConstantInt *Mask, bool isSub,
3543                                         Instruction &I) {
3544   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3545   if (!LHSI || LHSI->getNumOperands() != 2 ||
3546       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3547
3548   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3549
3550   switch (LHSI->getOpcode()) {
3551   default: return 0;
3552   case Instruction::And:
3553     if (And(N, Mask) == Mask) {
3554       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3555       if ((Mask->getValue().countLeadingZeros() + 
3556            Mask->getValue().countPopulation()) == 
3557           Mask->getValue().getBitWidth())
3558         break;
3559
3560       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3561       // part, we don't need any explicit masks to take them out of A.  If that
3562       // is all N is, ignore it.
3563       uint32_t MB = 0, ME = 0;
3564       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3565         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3566         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3567         if (MaskedValueIsZero(RHS, Mask))
3568           break;
3569       }
3570     }
3571     return 0;
3572   case Instruction::Or:
3573   case Instruction::Xor:
3574     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3575     if ((Mask->getValue().countLeadingZeros() + 
3576          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3577         && And(N, Mask)->isZero())
3578       break;
3579     return 0;
3580   }
3581   
3582   Instruction *New;
3583   if (isSub)
3584     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3585   else
3586     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3587   return InsertNewInstBefore(New, I);
3588 }
3589
3590 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3591 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3592                                           ICmpInst *LHS, ICmpInst *RHS) {
3593   Value *Val, *Val2;
3594   ConstantInt *LHSCst, *RHSCst;
3595   ICmpInst::Predicate LHSCC, RHSCC;
3596   
3597   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3598   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3599       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3600     return 0;
3601   
3602   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3603   // where C is a power of 2
3604   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3605       LHSCst->getValue().isPowerOf2()) {
3606     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3607     InsertNewInstBefore(NewOr, I);
3608     return new ICmpInst(LHSCC, NewOr, LHSCst);
3609   }
3610   
3611   // From here on, we only handle:
3612   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3613   if (Val != Val2) return 0;
3614   
3615   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3616   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3617       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3618       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3619       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3620     return 0;
3621   
3622   // We can't fold (ugt x, C) & (sgt x, C2).
3623   if (!PredicatesFoldable(LHSCC, RHSCC))
3624     return 0;
3625     
3626   // Ensure that the larger constant is on the RHS.
3627   bool ShouldSwap;
3628   if (ICmpInst::isSignedPredicate(LHSCC) ||
3629       (ICmpInst::isEquality(LHSCC) && 
3630        ICmpInst::isSignedPredicate(RHSCC)))
3631     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3632   else
3633     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3634     
3635   if (ShouldSwap) {
3636     std::swap(LHS, RHS);
3637     std::swap(LHSCst, RHSCst);
3638     std::swap(LHSCC, RHSCC);
3639   }
3640
3641   // At this point, we know we have have two icmp instructions
3642   // comparing a value against two constants and and'ing the result
3643   // together.  Because of the above check, we know that we only have
3644   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3645   // (from the FoldICmpLogical check above), that the two constants 
3646   // are not equal and that the larger constant is on the RHS
3647   assert(LHSCst != RHSCst && "Compares not folded above?");
3648
3649   switch (LHSCC) {
3650   default: assert(0 && "Unknown integer condition code!");
3651   case ICmpInst::ICMP_EQ:
3652     switch (RHSCC) {
3653     default: assert(0 && "Unknown integer condition code!");
3654     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3655     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3656     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3657       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3658     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3659     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3660     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3661       return ReplaceInstUsesWith(I, LHS);
3662     }
3663   case ICmpInst::ICMP_NE:
3664     switch (RHSCC) {
3665     default: assert(0 && "Unknown integer condition code!");
3666     case ICmpInst::ICMP_ULT:
3667       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3668         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3669       break;                        // (X != 13 & X u< 15) -> no change
3670     case ICmpInst::ICMP_SLT:
3671       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3672         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3673       break;                        // (X != 13 & X s< 15) -> no change
3674     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3675     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3676     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3677       return ReplaceInstUsesWith(I, RHS);
3678     case ICmpInst::ICMP_NE:
3679       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3680         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3681         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3682                                                      Val->getName()+".off");
3683         InsertNewInstBefore(Add, I);
3684         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3685                             ConstantInt::get(Add->getType(), 1));
3686       }
3687       break;                        // (X != 13 & X != 15) -> no change
3688     }
3689     break;
3690   case ICmpInst::ICMP_ULT:
3691     switch (RHSCC) {
3692     default: assert(0 && "Unknown integer condition code!");
3693     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3694     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3695       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3696     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3697       break;
3698     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3699     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3700       return ReplaceInstUsesWith(I, LHS);
3701     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3702       break;
3703     }
3704     break;
3705   case ICmpInst::ICMP_SLT:
3706     switch (RHSCC) {
3707     default: assert(0 && "Unknown integer condition code!");
3708     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3709     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3710       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3711     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3712       break;
3713     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3714     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3715       return ReplaceInstUsesWith(I, LHS);
3716     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3717       break;
3718     }
3719     break;
3720   case ICmpInst::ICMP_UGT:
3721     switch (RHSCC) {
3722     default: assert(0 && "Unknown integer condition code!");
3723     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3724     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3725       return ReplaceInstUsesWith(I, RHS);
3726     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3727       break;
3728     case ICmpInst::ICMP_NE:
3729       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3730         return new ICmpInst(LHSCC, Val, RHSCst);
3731       break;                        // (X u> 13 & X != 15) -> no change
3732     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3733       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3734     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3735       break;
3736     }
3737     break;
3738   case ICmpInst::ICMP_SGT:
3739     switch (RHSCC) {
3740     default: assert(0 && "Unknown integer condition code!");
3741     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3742     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3743       return ReplaceInstUsesWith(I, RHS);
3744     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3745       break;
3746     case ICmpInst::ICMP_NE:
3747       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3748         return new ICmpInst(LHSCC, Val, RHSCst);
3749       break;                        // (X s> 13 & X != 15) -> no change
3750     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3751       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3752     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3753       break;
3754     }
3755     break;
3756   }
3757  
3758   return 0;
3759 }
3760
3761
3762 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3763   bool Changed = SimplifyCommutative(I);
3764   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3765
3766   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3767     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3768
3769   // and X, X = X
3770   if (Op0 == Op1)
3771     return ReplaceInstUsesWith(I, Op1);
3772
3773   // See if we can simplify any instructions used by the instruction whose sole 
3774   // purpose is to compute bits we don't care about.
3775   if (!isa<VectorType>(I.getType())) {
3776     if (SimplifyDemandedInstructionBits(I))
3777       return &I;
3778   } else {
3779     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3780       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3781         return ReplaceInstUsesWith(I, I.getOperand(0));
3782     } else if (isa<ConstantAggregateZero>(Op1)) {
3783       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3784     }
3785   }
3786   
3787   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3788     const APInt& AndRHSMask = AndRHS->getValue();
3789     APInt NotAndRHS(~AndRHSMask);
3790
3791     // Optimize a variety of ((val OP C1) & C2) combinations...
3792     if (isa<BinaryOperator>(Op0)) {
3793       Instruction *Op0I = cast<Instruction>(Op0);
3794       Value *Op0LHS = Op0I->getOperand(0);
3795       Value *Op0RHS = Op0I->getOperand(1);
3796       switch (Op0I->getOpcode()) {
3797       case Instruction::Xor:
3798       case Instruction::Or:
3799         // If the mask is only needed on one incoming arm, push it up.
3800         if (Op0I->hasOneUse()) {
3801           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3802             // Not masking anything out for the LHS, move to RHS.
3803             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3804                                                    Op0RHS->getName()+".masked");
3805             InsertNewInstBefore(NewRHS, I);
3806             return BinaryOperator::Create(
3807                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3808           }
3809           if (!isa<Constant>(Op0RHS) &&
3810               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3811             // Not masking anything out for the RHS, move to LHS.
3812             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3813                                                    Op0LHS->getName()+".masked");
3814             InsertNewInstBefore(NewLHS, I);
3815             return BinaryOperator::Create(
3816                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3817           }
3818         }
3819
3820         break;
3821       case Instruction::Add:
3822         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3823         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3824         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3825         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3826           return BinaryOperator::CreateAnd(V, AndRHS);
3827         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3828           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3829         break;
3830
3831       case Instruction::Sub:
3832         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3833         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3834         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3835         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3836           return BinaryOperator::CreateAnd(V, AndRHS);
3837
3838         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3839         // has 1's for all bits that the subtraction with A might affect.
3840         if (Op0I->hasOneUse()) {
3841           uint32_t BitWidth = AndRHSMask.getBitWidth();
3842           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3843           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3844
3845           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3846           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3847               MaskedValueIsZero(Op0LHS, Mask)) {
3848             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3849             InsertNewInstBefore(NewNeg, I);
3850             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3851           }
3852         }
3853         break;
3854
3855       case Instruction::Shl:
3856       case Instruction::LShr:
3857         // (1 << x) & 1 --> zext(x == 0)
3858         // (1 >> x) & 1 --> zext(x == 0)
3859         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3860           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3861                                            Constant::getNullValue(I.getType()));
3862           InsertNewInstBefore(NewICmp, I);
3863           return new ZExtInst(NewICmp, I.getType());
3864         }
3865         break;
3866       }
3867
3868       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3869         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3870           return Res;
3871     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3872       // If this is an integer truncation or change from signed-to-unsigned, and
3873       // if the source is an and/or with immediate, transform it.  This
3874       // frequently occurs for bitfield accesses.
3875       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3876         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3877             CastOp->getNumOperands() == 2)
3878           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3879             if (CastOp->getOpcode() == Instruction::And) {
3880               // Change: and (cast (and X, C1) to T), C2
3881               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3882               // This will fold the two constants together, which may allow 
3883               // other simplifications.
3884               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3885                 CastOp->getOperand(0), I.getType(), 
3886                 CastOp->getName()+".shrunk");
3887               NewCast = InsertNewInstBefore(NewCast, I);
3888               // trunc_or_bitcast(C1)&C2
3889               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3890               C3 = ConstantExpr::getAnd(C3, AndRHS);
3891               return BinaryOperator::CreateAnd(NewCast, C3);
3892             } else if (CastOp->getOpcode() == Instruction::Or) {
3893               // Change: and (cast (or X, C1) to T), C2
3894               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3895               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3896               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3897                 return ReplaceInstUsesWith(I, AndRHS);
3898             }
3899           }
3900       }
3901     }
3902
3903     // Try to fold constant and into select arguments.
3904     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3905       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3906         return R;
3907     if (isa<PHINode>(Op0))
3908       if (Instruction *NV = FoldOpIntoPhi(I))
3909         return NV;
3910   }
3911
3912   Value *Op0NotVal = dyn_castNotVal(Op0);
3913   Value *Op1NotVal = dyn_castNotVal(Op1);
3914
3915   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3916     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3917
3918   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3919   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3920     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3921                                                I.getName()+".demorgan");
3922     InsertNewInstBefore(Or, I);
3923     return BinaryOperator::CreateNot(Or);
3924   }
3925   
3926   {
3927     Value *A = 0, *B = 0, *C = 0, *D = 0;
3928     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3929       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3930         return ReplaceInstUsesWith(I, Op1);
3931     
3932       // (A|B) & ~(A&B) -> A^B
3933       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3934         if ((A == C && B == D) || (A == D && B == C))
3935           return BinaryOperator::CreateXor(A, B);
3936       }
3937     }
3938     
3939     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3940       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3941         return ReplaceInstUsesWith(I, Op0);
3942
3943       // ~(A&B) & (A|B) -> A^B
3944       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3945         if ((A == C && B == D) || (A == D && B == C))
3946           return BinaryOperator::CreateXor(A, B);
3947       }
3948     }
3949     
3950     if (Op0->hasOneUse() &&
3951         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3952       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3953         I.swapOperands();     // Simplify below
3954         std::swap(Op0, Op1);
3955       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3956         cast<BinaryOperator>(Op0)->swapOperands();
3957         I.swapOperands();     // Simplify below
3958         std::swap(Op0, Op1);
3959       }
3960     }
3961
3962     if (Op1->hasOneUse() &&
3963         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3964       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3965         cast<BinaryOperator>(Op1)->swapOperands();
3966         std::swap(A, B);
3967       }
3968       if (A == Op0) {                                // A&(A^B) -> A & ~B
3969         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3970         InsertNewInstBefore(NotB, I);
3971         return BinaryOperator::CreateAnd(A, NotB);
3972       }
3973     }
3974
3975     // (A&((~A)|B)) -> A&B
3976     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
3977         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
3978       return BinaryOperator::CreateAnd(A, Op1);
3979     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
3980         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
3981       return BinaryOperator::CreateAnd(A, Op0);
3982   }
3983   
3984   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3985     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3986     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3987       return R;
3988
3989     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
3990       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
3991         return Res;
3992   }
3993
3994   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3995   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3996     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3997       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3998         const Type *SrcTy = Op0C->getOperand(0)->getType();
3999         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4000             // Only do this if the casts both really cause code to be generated.
4001             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4002                               I.getType(), TD) &&
4003             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4004                               I.getType(), TD)) {
4005           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4006                                                          Op1C->getOperand(0),
4007                                                          I.getName());
4008           InsertNewInstBefore(NewOp, I);
4009           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4010         }
4011       }
4012     
4013   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4014   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4015     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4016       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4017           SI0->getOperand(1) == SI1->getOperand(1) &&
4018           (SI0->hasOneUse() || SI1->hasOneUse())) {
4019         Instruction *NewOp =
4020           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4021                                                         SI1->getOperand(0),
4022                                                         SI0->getName()), I);
4023         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4024                                       SI1->getOperand(1));
4025       }
4026   }
4027
4028   // If and'ing two fcmp, try combine them into one.
4029   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4030     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4031       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4032           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4033         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4034         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4035           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4036             // If either of the constants are nans, then the whole thing returns
4037             // false.
4038             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4039               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4040             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4041                                 RHS->getOperand(0));
4042           }
4043       } else {
4044         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4045         FCmpInst::Predicate Op0CC, Op1CC;
4046         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4047             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4048           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4049             // Swap RHS operands to match LHS.
4050             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4051             std::swap(Op1LHS, Op1RHS);
4052           }
4053           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4054             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4055             if (Op0CC == Op1CC)
4056               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4057             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4058                      Op1CC == FCmpInst::FCMP_FALSE)
4059               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4060             else if (Op0CC == FCmpInst::FCMP_TRUE)
4061               return ReplaceInstUsesWith(I, Op1);
4062             else if (Op1CC == FCmpInst::FCMP_TRUE)
4063               return ReplaceInstUsesWith(I, Op0);
4064             bool Op0Ordered;
4065             bool Op1Ordered;
4066             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4067             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4068             if (Op1Pred == 0) {
4069               std::swap(Op0, Op1);
4070               std::swap(Op0Pred, Op1Pred);
4071               std::swap(Op0Ordered, Op1Ordered);
4072             }
4073             if (Op0Pred == 0) {
4074               // uno && ueq -> uno && (uno || eq) -> ueq
4075               // ord && olt -> ord && (ord && lt) -> olt
4076               if (Op0Ordered == Op1Ordered)
4077                 return ReplaceInstUsesWith(I, Op1);
4078               // uno && oeq -> uno && (ord && eq) -> false
4079               // uno && ord -> false
4080               if (!Op0Ordered)
4081                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4082               // ord && ueq -> ord && (uno || eq) -> oeq
4083               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4084                                                     Op0LHS, Op0RHS));
4085             }
4086           }
4087         }
4088       }
4089     }
4090   }
4091
4092   return Changed ? &I : 0;
4093 }
4094
4095 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4096 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4097 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4098 /// the expression came from the corresponding "byte swapped" byte in some other
4099 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4100 /// we know that the expression deposits the low byte of %X into the high byte
4101 /// of the bswap result and that all other bytes are zero.  This expression is
4102 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4103 /// match.
4104 ///
4105 /// This function returns true if the match was unsuccessful and false if so.
4106 /// On entry to the function the "OverallLeftShift" is a signed integer value
4107 /// indicating the number of bytes that the subexpression is later shifted.  For
4108 /// example, if the expression is later right shifted by 16 bits, the
4109 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4110 /// byte of ByteValues is actually being set.
4111 ///
4112 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4113 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4114 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4115 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4116 /// always in the local (OverallLeftShift) coordinate space.
4117 ///
4118 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4119                               SmallVector<Value*, 8> &ByteValues) {
4120   if (Instruction *I = dyn_cast<Instruction>(V)) {
4121     // If this is an or instruction, it may be an inner node of the bswap.
4122     if (I->getOpcode() == Instruction::Or) {
4123       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4124                                ByteValues) ||
4125              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4126                                ByteValues);
4127     }
4128   
4129     // If this is a logical shift by a constant multiple of 8, recurse with
4130     // OverallLeftShift and ByteMask adjusted.
4131     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4132       unsigned ShAmt = 
4133         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4134       // Ensure the shift amount is defined and of a byte value.
4135       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4136         return true;
4137
4138       unsigned ByteShift = ShAmt >> 3;
4139       if (I->getOpcode() == Instruction::Shl) {
4140         // X << 2 -> collect(X, +2)
4141         OverallLeftShift += ByteShift;
4142         ByteMask >>= ByteShift;
4143       } else {
4144         // X >>u 2 -> collect(X, -2)
4145         OverallLeftShift -= ByteShift;
4146         ByteMask <<= ByteShift;
4147         ByteMask &= (~0U >> (32-ByteValues.size()));
4148       }
4149
4150       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4151       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4152
4153       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4154                                ByteValues);
4155     }
4156
4157     // If this is a logical 'and' with a mask that clears bytes, clear the
4158     // corresponding bytes in ByteMask.
4159     if (I->getOpcode() == Instruction::And &&
4160         isa<ConstantInt>(I->getOperand(1))) {
4161       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4162       unsigned NumBytes = ByteValues.size();
4163       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4164       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4165       
4166       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4167         // If this byte is masked out by a later operation, we don't care what
4168         // the and mask is.
4169         if ((ByteMask & (1 << i)) == 0)
4170           continue;
4171         
4172         // If the AndMask is all zeros for this byte, clear the bit.
4173         APInt MaskB = AndMask & Byte;
4174         if (MaskB == 0) {
4175           ByteMask &= ~(1U << i);
4176           continue;
4177         }
4178         
4179         // If the AndMask is not all ones for this byte, it's not a bytezap.
4180         if (MaskB != Byte)
4181           return true;
4182
4183         // Otherwise, this byte is kept.
4184       }
4185
4186       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4187                                ByteValues);
4188     }
4189   }
4190   
4191   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4192   // the input value to the bswap.  Some observations: 1) if more than one byte
4193   // is demanded from this input, then it could not be successfully assembled
4194   // into a byteswap.  At least one of the two bytes would not be aligned with
4195   // their ultimate destination.
4196   if (!isPowerOf2_32(ByteMask)) return true;
4197   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4198   
4199   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4200   // is demanded, it needs to go into byte 0 of the result.  This means that the
4201   // byte needs to be shifted until it lands in the right byte bucket.  The
4202   // shift amount depends on the position: if the byte is coming from the high
4203   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4204   // low part, it must be shifted left.
4205   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4206   if (InputByteNo < ByteValues.size()/2) {
4207     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4208       return true;
4209   } else {
4210     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4211       return true;
4212   }
4213   
4214   // If the destination byte value is already defined, the values are or'd
4215   // together, which isn't a bswap (unless it's an or of the same bits).
4216   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4217     return true;
4218   ByteValues[DestByteNo] = V;
4219   return false;
4220 }
4221
4222 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4223 /// If so, insert the new bswap intrinsic and return it.
4224 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4225   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4226   if (!ITy || ITy->getBitWidth() % 16 || 
4227       // ByteMask only allows up to 32-byte values.
4228       ITy->getBitWidth() > 32*8) 
4229     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4230   
4231   /// ByteValues - For each byte of the result, we keep track of which value
4232   /// defines each byte.
4233   SmallVector<Value*, 8> ByteValues;
4234   ByteValues.resize(ITy->getBitWidth()/8);
4235     
4236   // Try to find all the pieces corresponding to the bswap.
4237   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4238   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4239     return 0;
4240   
4241   // Check to see if all of the bytes come from the same value.
4242   Value *V = ByteValues[0];
4243   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4244   
4245   // Check to make sure that all of the bytes come from the same value.
4246   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4247     if (ByteValues[i] != V)
4248       return 0;
4249   const Type *Tys[] = { ITy };
4250   Module *M = I.getParent()->getParent()->getParent();
4251   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4252   return CallInst::Create(F, V);
4253 }
4254
4255 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4256 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4257 /// we can simplify this expression to "cond ? C : D or B".
4258 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4259                                          Value *C, Value *D) {
4260   // If A is not a select of -1/0, this cannot match.
4261   Value *Cond = 0;
4262   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4263     return 0;
4264
4265   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4266   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4267     return SelectInst::Create(Cond, C, B);
4268   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4269     return SelectInst::Create(Cond, C, B);
4270   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4271   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4272     return SelectInst::Create(Cond, C, D);
4273   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4274     return SelectInst::Create(Cond, C, D);
4275   return 0;
4276 }
4277
4278 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4279 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4280                                          ICmpInst *LHS, ICmpInst *RHS) {
4281   Value *Val, *Val2;
4282   ConstantInt *LHSCst, *RHSCst;
4283   ICmpInst::Predicate LHSCC, RHSCC;
4284   
4285   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4286   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4287       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4288     return 0;
4289   
4290   // From here on, we only handle:
4291   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4292   if (Val != Val2) return 0;
4293   
4294   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4295   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4296       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4297       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4298       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4299     return 0;
4300   
4301   // We can't fold (ugt x, C) | (sgt x, C2).
4302   if (!PredicatesFoldable(LHSCC, RHSCC))
4303     return 0;
4304   
4305   // Ensure that the larger constant is on the RHS.
4306   bool ShouldSwap;
4307   if (ICmpInst::isSignedPredicate(LHSCC) ||
4308       (ICmpInst::isEquality(LHSCC) && 
4309        ICmpInst::isSignedPredicate(RHSCC)))
4310     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4311   else
4312     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4313   
4314   if (ShouldSwap) {
4315     std::swap(LHS, RHS);
4316     std::swap(LHSCst, RHSCst);
4317     std::swap(LHSCC, RHSCC);
4318   }
4319   
4320   // At this point, we know we have have two icmp instructions
4321   // comparing a value against two constants and or'ing the result
4322   // together.  Because of the above check, we know that we only have
4323   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4324   // FoldICmpLogical check above), that the two constants are not
4325   // equal.
4326   assert(LHSCst != RHSCst && "Compares not folded above?");
4327
4328   switch (LHSCC) {
4329   default: assert(0 && "Unknown integer condition code!");
4330   case ICmpInst::ICMP_EQ:
4331     switch (RHSCC) {
4332     default: assert(0 && "Unknown integer condition code!");
4333     case ICmpInst::ICMP_EQ:
4334       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4335         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4336         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4337                                                      Val->getName()+".off");
4338         InsertNewInstBefore(Add, I);
4339         AddCST = Subtract(AddOne(RHSCst), LHSCst);
4340         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4341       }
4342       break;                         // (X == 13 | X == 15) -> no change
4343     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4344     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4345       break;
4346     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4347     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4348     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4349       return ReplaceInstUsesWith(I, RHS);
4350     }
4351     break;
4352   case ICmpInst::ICMP_NE:
4353     switch (RHSCC) {
4354     default: assert(0 && "Unknown integer condition code!");
4355     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4356     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4357     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4358       return ReplaceInstUsesWith(I, LHS);
4359     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4360     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4361     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4362       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4363     }
4364     break;
4365   case ICmpInst::ICMP_ULT:
4366     switch (RHSCC) {
4367     default: assert(0 && "Unknown integer condition code!");
4368     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4369       break;
4370     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4371       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4372       // this can cause overflow.
4373       if (RHSCst->isMaxValue(false))
4374         return ReplaceInstUsesWith(I, LHS);
4375       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4376     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4377       break;
4378     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4379     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4380       return ReplaceInstUsesWith(I, RHS);
4381     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4382       break;
4383     }
4384     break;
4385   case ICmpInst::ICMP_SLT:
4386     switch (RHSCC) {
4387     default: assert(0 && "Unknown integer condition code!");
4388     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4389       break;
4390     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4391       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4392       // this can cause overflow.
4393       if (RHSCst->isMaxValue(true))
4394         return ReplaceInstUsesWith(I, LHS);
4395       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4396     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4397       break;
4398     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4399     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4400       return ReplaceInstUsesWith(I, RHS);
4401     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4402       break;
4403     }
4404     break;
4405   case ICmpInst::ICMP_UGT:
4406     switch (RHSCC) {
4407     default: assert(0 && "Unknown integer condition code!");
4408     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4409     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4410       return ReplaceInstUsesWith(I, LHS);
4411     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4412       break;
4413     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4414     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4415       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4416     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4417       break;
4418     }
4419     break;
4420   case ICmpInst::ICMP_SGT:
4421     switch (RHSCC) {
4422     default: assert(0 && "Unknown integer condition code!");
4423     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4424     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4425       return ReplaceInstUsesWith(I, LHS);
4426     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4427       break;
4428     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4429     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4430       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4431     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4432       break;
4433     }
4434     break;
4435   }
4436   return 0;
4437 }
4438
4439 /// FoldOrWithConstants - This helper function folds:
4440 ///
4441 ///     ((A | B) & C1) | (B & C2)
4442 ///
4443 /// into:
4444 /// 
4445 ///     (A & C1) | B
4446 ///
4447 /// when the XOR of the two constants is "all ones" (-1).
4448 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4449                                                Value *A, Value *B, Value *C) {
4450   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4451   if (!CI1) return 0;
4452
4453   Value *V1 = 0;
4454   ConstantInt *CI2 = 0;
4455   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4456
4457   APInt Xor = CI1->getValue() ^ CI2->getValue();
4458   if (!Xor.isAllOnesValue()) return 0;
4459
4460   if (V1 == A || V1 == B) {
4461     Instruction *NewOp =
4462       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4463     return BinaryOperator::CreateOr(NewOp, V1);
4464   }
4465
4466   return 0;
4467 }
4468
4469 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4470   bool Changed = SimplifyCommutative(I);
4471   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4472
4473   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4474     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4475
4476   // or X, X = X
4477   if (Op0 == Op1)
4478     return ReplaceInstUsesWith(I, Op0);
4479
4480   // See if we can simplify any instructions used by the instruction whose sole 
4481   // purpose is to compute bits we don't care about.
4482   if (!isa<VectorType>(I.getType())) {
4483     if (SimplifyDemandedInstructionBits(I))
4484       return &I;
4485   } else if (isa<ConstantAggregateZero>(Op1)) {
4486     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4487   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4488     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4489       return ReplaceInstUsesWith(I, I.getOperand(1));
4490   }
4491     
4492
4493   
4494   // or X, -1 == -1
4495   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4496     ConstantInt *C1 = 0; Value *X = 0;
4497     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4498     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4499       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4500       InsertNewInstBefore(Or, I);
4501       Or->takeName(Op0);
4502       return BinaryOperator::CreateAnd(Or, 
4503                ConstantInt::get(RHS->getValue() | C1->getValue()));
4504     }
4505
4506     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4507     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4508       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4509       InsertNewInstBefore(Or, I);
4510       Or->takeName(Op0);
4511       return BinaryOperator::CreateXor(Or,
4512                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4513     }
4514
4515     // Try to fold constant and into select arguments.
4516     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4517       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4518         return R;
4519     if (isa<PHINode>(Op0))
4520       if (Instruction *NV = FoldOpIntoPhi(I))
4521         return NV;
4522   }
4523
4524   Value *A = 0, *B = 0;
4525   ConstantInt *C1 = 0, *C2 = 0;
4526
4527   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4528     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4529       return ReplaceInstUsesWith(I, Op1);
4530   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4531     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4532       return ReplaceInstUsesWith(I, Op0);
4533
4534   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4535   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4536   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4537       match(Op1, m_Or(m_Value(), m_Value())) ||
4538       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4539        match(Op1, m_Shift(m_Value(), m_Value())))) {
4540     if (Instruction *BSwap = MatchBSwap(I))
4541       return BSwap;
4542   }
4543   
4544   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4545   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4546       MaskedValueIsZero(Op1, C1->getValue())) {
4547     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4548     InsertNewInstBefore(NOr, I);
4549     NOr->takeName(Op0);
4550     return BinaryOperator::CreateXor(NOr, C1);
4551   }
4552
4553   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4554   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4555       MaskedValueIsZero(Op0, C1->getValue())) {
4556     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4557     InsertNewInstBefore(NOr, I);
4558     NOr->takeName(Op0);
4559     return BinaryOperator::CreateXor(NOr, C1);
4560   }
4561
4562   // (A & C)|(B & D)
4563   Value *C = 0, *D = 0;
4564   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4565       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4566     Value *V1 = 0, *V2 = 0, *V3 = 0;
4567     C1 = dyn_cast<ConstantInt>(C);
4568     C2 = dyn_cast<ConstantInt>(D);
4569     if (C1 && C2) {  // (A & C1)|(B & C2)
4570       // If we have: ((V + N) & C1) | (V & C2)
4571       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4572       // replace with V+N.
4573       if (C1->getValue() == ~C2->getValue()) {
4574         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4575             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4576           // Add commutes, try both ways.
4577           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4578             return ReplaceInstUsesWith(I, A);
4579           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4580             return ReplaceInstUsesWith(I, A);
4581         }
4582         // Or commutes, try both ways.
4583         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4584             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4585           // Add commutes, try both ways.
4586           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4587             return ReplaceInstUsesWith(I, B);
4588           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4589             return ReplaceInstUsesWith(I, B);
4590         }
4591       }
4592       V1 = 0; V2 = 0; V3 = 0;
4593     }
4594     
4595     // Check to see if we have any common things being and'ed.  If so, find the
4596     // terms for V1 & (V2|V3).
4597     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4598       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4599         V1 = A, V2 = C, V3 = D;
4600       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4601         V1 = A, V2 = B, V3 = C;
4602       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4603         V1 = C, V2 = A, V3 = D;
4604       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4605         V1 = C, V2 = A, V3 = B;
4606       
4607       if (V1) {
4608         Value *Or =
4609           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4610         return BinaryOperator::CreateAnd(V1, Or);
4611       }
4612     }
4613
4614     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4615     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4616       return Match;
4617     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4618       return Match;
4619     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4620       return Match;
4621     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4622       return Match;
4623
4624     // ((A&~B)|(~A&B)) -> A^B
4625     if ((match(C, m_Not(m_Specific(D))) &&
4626          match(B, m_Not(m_Specific(A)))))
4627       return BinaryOperator::CreateXor(A, D);
4628     // ((~B&A)|(~A&B)) -> A^B
4629     if ((match(A, m_Not(m_Specific(D))) &&
4630          match(B, m_Not(m_Specific(C)))))
4631       return BinaryOperator::CreateXor(C, D);
4632     // ((A&~B)|(B&~A)) -> A^B
4633     if ((match(C, m_Not(m_Specific(B))) &&
4634          match(D, m_Not(m_Specific(A)))))
4635       return BinaryOperator::CreateXor(A, B);
4636     // ((~B&A)|(B&~A)) -> A^B
4637     if ((match(A, m_Not(m_Specific(B))) &&
4638          match(D, m_Not(m_Specific(C)))))
4639       return BinaryOperator::CreateXor(C, B);
4640   }
4641   
4642   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4643   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4644     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4645       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4646           SI0->getOperand(1) == SI1->getOperand(1) &&
4647           (SI0->hasOneUse() || SI1->hasOneUse())) {
4648         Instruction *NewOp =
4649         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4650                                                      SI1->getOperand(0),
4651                                                      SI0->getName()), I);
4652         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4653                                       SI1->getOperand(1));
4654       }
4655   }
4656
4657   // ((A|B)&1)|(B&-2) -> (A&1) | B
4658   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4659       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4660     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4661     if (Ret) return Ret;
4662   }
4663   // (B&-2)|((A|B)&1) -> (A&1) | B
4664   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4665       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4666     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4667     if (Ret) return Ret;
4668   }
4669
4670   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4671     if (A == Op1)   // ~A | A == -1
4672       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4673   } else {
4674     A = 0;
4675   }
4676   // Note, A is still live here!
4677   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4678     if (Op0 == B)
4679       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4680
4681     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4682     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4683       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4684                                               I.getName()+".demorgan"), I);
4685       return BinaryOperator::CreateNot(And);
4686     }
4687   }
4688
4689   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4690   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4691     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4692       return R;
4693
4694     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4695       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4696         return Res;
4697   }
4698     
4699   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4700   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4701     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4702       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4703         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4704             !isa<ICmpInst>(Op1C->getOperand(0))) {
4705           const Type *SrcTy = Op0C->getOperand(0)->getType();
4706           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4707               // Only do this if the casts both really cause code to be
4708               // generated.
4709               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4710                                 I.getType(), TD) &&
4711               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4712                                 I.getType(), TD)) {
4713             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4714                                                           Op1C->getOperand(0),
4715                                                           I.getName());
4716             InsertNewInstBefore(NewOp, I);
4717             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4718           }
4719         }
4720       }
4721   }
4722   
4723     
4724   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4725   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4726     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4727       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4728           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4729           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4730         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4731           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4732             // If either of the constants are nans, then the whole thing returns
4733             // true.
4734             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4735               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4736             
4737             // Otherwise, no need to compare the two constants, compare the
4738             // rest.
4739             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4740                                 RHS->getOperand(0));
4741           }
4742       } else {
4743         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4744         FCmpInst::Predicate Op0CC, Op1CC;
4745         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4746             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4747           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4748             // Swap RHS operands to match LHS.
4749             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4750             std::swap(Op1LHS, Op1RHS);
4751           }
4752           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4753             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4754             if (Op0CC == Op1CC)
4755               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4756             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4757                      Op1CC == FCmpInst::FCMP_TRUE)
4758               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4759             else if (Op0CC == FCmpInst::FCMP_FALSE)
4760               return ReplaceInstUsesWith(I, Op1);
4761             else if (Op1CC == FCmpInst::FCMP_FALSE)
4762               return ReplaceInstUsesWith(I, Op0);
4763             bool Op0Ordered;
4764             bool Op1Ordered;
4765             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4766             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4767             if (Op0Ordered == Op1Ordered) {
4768               // If both are ordered or unordered, return a new fcmp with
4769               // or'ed predicates.
4770               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4771                                        Op0LHS, Op0RHS);
4772               if (Instruction *I = dyn_cast<Instruction>(RV))
4773                 return I;
4774               // Otherwise, it's a constant boolean value...
4775               return ReplaceInstUsesWith(I, RV);
4776             }
4777           }
4778         }
4779       }
4780     }
4781   }
4782
4783   return Changed ? &I : 0;
4784 }
4785
4786 namespace {
4787
4788 // XorSelf - Implements: X ^ X --> 0
4789 struct XorSelf {
4790   Value *RHS;
4791   XorSelf(Value *rhs) : RHS(rhs) {}
4792   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4793   Instruction *apply(BinaryOperator &Xor) const {
4794     return &Xor;
4795   }
4796 };
4797
4798 }
4799
4800 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4801   bool Changed = SimplifyCommutative(I);
4802   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4803
4804   if (isa<UndefValue>(Op1)) {
4805     if (isa<UndefValue>(Op0))
4806       // Handle undef ^ undef -> 0 special case. This is a common
4807       // idiom (misuse).
4808       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4809     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4810   }
4811
4812   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4813   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4814     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4815     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4816   }
4817   
4818   // See if we can simplify any instructions used by the instruction whose sole 
4819   // purpose is to compute bits we don't care about.
4820   if (!isa<VectorType>(I.getType())) {
4821     if (SimplifyDemandedInstructionBits(I))
4822       return &I;
4823   } else if (isa<ConstantAggregateZero>(Op1)) {
4824     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4825   }
4826
4827   // Is this a ~ operation?
4828   if (Value *NotOp = dyn_castNotVal(&I)) {
4829     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4830     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4831     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4832       if (Op0I->getOpcode() == Instruction::And || 
4833           Op0I->getOpcode() == Instruction::Or) {
4834         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4835         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4836           Instruction *NotY =
4837             BinaryOperator::CreateNot(Op0I->getOperand(1),
4838                                       Op0I->getOperand(1)->getName()+".not");
4839           InsertNewInstBefore(NotY, I);
4840           if (Op0I->getOpcode() == Instruction::And)
4841             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4842           else
4843             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4844         }
4845       }
4846     }
4847   }
4848   
4849   
4850   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4851     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4852       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4853       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4854         return new ICmpInst(ICI->getInversePredicate(),
4855                             ICI->getOperand(0), ICI->getOperand(1));
4856
4857       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4858         return new FCmpInst(FCI->getInversePredicate(),
4859                             FCI->getOperand(0), FCI->getOperand(1));
4860     }
4861
4862     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4863     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4864       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4865         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4866           Instruction::CastOps Opcode = Op0C->getOpcode();
4867           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4868             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4869                                              Op0C->getDestTy())) {
4870               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4871                                      CI->getOpcode(), CI->getInversePredicate(),
4872                                      CI->getOperand(0), CI->getOperand(1)), I);
4873               NewCI->takeName(CI);
4874               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4875             }
4876           }
4877         }
4878       }
4879     }
4880
4881     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4882       // ~(c-X) == X-c-1 == X+(-c-1)
4883       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4884         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4885           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4886           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4887                                               ConstantInt::get(I.getType(), 1));
4888           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4889         }
4890           
4891       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4892         if (Op0I->getOpcode() == Instruction::Add) {
4893           // ~(X-c) --> (-c-1)-X
4894           if (RHS->isAllOnesValue()) {
4895             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4896             return BinaryOperator::CreateSub(
4897                            ConstantExpr::getSub(NegOp0CI,
4898                                              ConstantInt::get(I.getType(), 1)),
4899                                           Op0I->getOperand(0));
4900           } else if (RHS->getValue().isSignBit()) {
4901             // (X + C) ^ signbit -> (X + C + signbit)
4902             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4903             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4904
4905           }
4906         } else if (Op0I->getOpcode() == Instruction::Or) {
4907           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4908           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4909             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4910             // Anything in both C1 and C2 is known to be zero, remove it from
4911             // NewRHS.
4912             Constant *CommonBits = And(Op0CI, RHS);
4913             NewRHS = ConstantExpr::getAnd(NewRHS, 
4914                                           ConstantExpr::getNot(CommonBits));
4915             AddToWorkList(Op0I);
4916             I.setOperand(0, Op0I->getOperand(0));
4917             I.setOperand(1, NewRHS);
4918             return &I;
4919           }
4920         }
4921       }
4922     }
4923
4924     // Try to fold constant and into select arguments.
4925     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4926       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4927         return R;
4928     if (isa<PHINode>(Op0))
4929       if (Instruction *NV = FoldOpIntoPhi(I))
4930         return NV;
4931   }
4932
4933   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4934     if (X == Op1)
4935       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4936
4937   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4938     if (X == Op0)
4939       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4940
4941   
4942   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4943   if (Op1I) {
4944     Value *A, *B;
4945     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4946       if (A == Op0) {              // B^(B|A) == (A|B)^B
4947         Op1I->swapOperands();
4948         I.swapOperands();
4949         std::swap(Op0, Op1);
4950       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4951         I.swapOperands();     // Simplified below.
4952         std::swap(Op0, Op1);
4953       }
4954     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
4955       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
4956     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
4957       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
4958     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4959       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4960         Op1I->swapOperands();
4961         std::swap(A, B);
4962       }
4963       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4964         I.swapOperands();     // Simplified below.
4965         std::swap(Op0, Op1);
4966       }
4967     }
4968   }
4969   
4970   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4971   if (Op0I) {
4972     Value *A, *B;
4973     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4974       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4975         std::swap(A, B);
4976       if (B == Op1) {                                // (A|B)^B == A & ~B
4977         Instruction *NotB =
4978           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4979         return BinaryOperator::CreateAnd(A, NotB);
4980       }
4981     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
4982       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
4983     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
4984       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
4985     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4986       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4987         std::swap(A, B);
4988       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4989           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4990         Instruction *N =
4991           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4992         return BinaryOperator::CreateAnd(N, Op1);
4993       }
4994     }
4995   }
4996   
4997   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4998   if (Op0I && Op1I && Op0I->isShift() && 
4999       Op0I->getOpcode() == Op1I->getOpcode() && 
5000       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5001       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5002     Instruction *NewOp =
5003       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5004                                                     Op1I->getOperand(0),
5005                                                     Op0I->getName()), I);
5006     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5007                                   Op1I->getOperand(1));
5008   }
5009     
5010   if (Op0I && Op1I) {
5011     Value *A, *B, *C, *D;
5012     // (A & B)^(A | B) -> A ^ B
5013     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5014         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5015       if ((A == C && B == D) || (A == D && B == C)) 
5016         return BinaryOperator::CreateXor(A, B);
5017     }
5018     // (A | B)^(A & B) -> A ^ B
5019     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5020         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5021       if ((A == C && B == D) || (A == D && B == C)) 
5022         return BinaryOperator::CreateXor(A, B);
5023     }
5024     
5025     // (A & B)^(C & D)
5026     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5027         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5028         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5029       // (X & Y)^(X & Y) -> (Y^Z) & X
5030       Value *X = 0, *Y = 0, *Z = 0;
5031       if (A == C)
5032         X = A, Y = B, Z = D;
5033       else if (A == D)
5034         X = A, Y = B, Z = C;
5035       else if (B == C)
5036         X = B, Y = A, Z = D;
5037       else if (B == D)
5038         X = B, Y = A, Z = C;
5039       
5040       if (X) {
5041         Instruction *NewOp =
5042         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5043         return BinaryOperator::CreateAnd(NewOp, X);
5044       }
5045     }
5046   }
5047     
5048   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5049   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5050     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5051       return R;
5052
5053   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5054   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5055     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5056       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5057         const Type *SrcTy = Op0C->getOperand(0)->getType();
5058         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5059             // Only do this if the casts both really cause code to be generated.
5060             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5061                               I.getType(), TD) &&
5062             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5063                               I.getType(), TD)) {
5064           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5065                                                          Op1C->getOperand(0),
5066                                                          I.getName());
5067           InsertNewInstBefore(NewOp, I);
5068           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5069         }
5070       }
5071   }
5072
5073   return Changed ? &I : 0;
5074 }
5075
5076 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5077 /// overflowed for this type.
5078 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5079                             ConstantInt *In2, bool IsSigned = false) {
5080   Result = cast<ConstantInt>(Add(In1, In2));
5081
5082   if (IsSigned)
5083     if (In2->getValue().isNegative())
5084       return Result->getValue().sgt(In1->getValue());
5085     else
5086       return Result->getValue().slt(In1->getValue());
5087   else
5088     return Result->getValue().ult(In1->getValue());
5089 }
5090
5091 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5092 /// overflowed for this type.
5093 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5094                             ConstantInt *In2, bool IsSigned = false) {
5095   Result = cast<ConstantInt>(Subtract(In1, In2));
5096
5097   if (IsSigned)
5098     if (In2->getValue().isNegative())
5099       return Result->getValue().slt(In1->getValue());
5100     else
5101       return Result->getValue().sgt(In1->getValue());
5102   else
5103     return Result->getValue().ugt(In1->getValue());
5104 }
5105
5106 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5107 /// code necessary to compute the offset from the base pointer (without adding
5108 /// in the base pointer).  Return the result as a signed integer of intptr size.
5109 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5110   TargetData &TD = IC.getTargetData();
5111   gep_type_iterator GTI = gep_type_begin(GEP);
5112   const Type *IntPtrTy = TD.getIntPtrType();
5113   Value *Result = Constant::getNullValue(IntPtrTy);
5114
5115   // Build a mask for high order bits.
5116   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5117   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5118
5119   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5120        ++i, ++GTI) {
5121     Value *Op = *i;
5122     uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
5123     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5124       if (OpC->isZero()) continue;
5125       
5126       // Handle a struct index, which adds its field offset to the pointer.
5127       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5128         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5129         
5130         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5131           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5132         else
5133           Result = IC.InsertNewInstBefore(
5134                    BinaryOperator::CreateAdd(Result,
5135                                              ConstantInt::get(IntPtrTy, Size),
5136                                              GEP->getName()+".offs"), I);
5137         continue;
5138       }
5139       
5140       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5141       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5142       Scale = ConstantExpr::getMul(OC, Scale);
5143       if (Constant *RC = dyn_cast<Constant>(Result))
5144         Result = ConstantExpr::getAdd(RC, Scale);
5145       else {
5146         // Emit an add instruction.
5147         Result = IC.InsertNewInstBefore(
5148            BinaryOperator::CreateAdd(Result, Scale,
5149                                      GEP->getName()+".offs"), I);
5150       }
5151       continue;
5152     }
5153     // Convert to correct type.
5154     if (Op->getType() != IntPtrTy) {
5155       if (Constant *OpC = dyn_cast<Constant>(Op))
5156         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5157       else
5158         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5159                                                  Op->getName()+".c"), I);
5160     }
5161     if (Size != 1) {
5162       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5163       if (Constant *OpC = dyn_cast<Constant>(Op))
5164         Op = ConstantExpr::getMul(OpC, Scale);
5165       else    // We'll let instcombine(mul) convert this to a shl if possible.
5166         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5167                                                   GEP->getName()+".idx"), I);
5168     }
5169
5170     // Emit an add instruction.
5171     if (isa<Constant>(Op) && isa<Constant>(Result))
5172       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5173                                     cast<Constant>(Result));
5174     else
5175       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5176                                                   GEP->getName()+".offs"), I);
5177   }
5178   return Result;
5179 }
5180
5181
5182 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5183 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5184 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5185 /// complex, and scales are involved.  The above expression would also be legal
5186 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5187 /// later form is less amenable to optimization though, and we are allowed to
5188 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5189 ///
5190 /// If we can't emit an optimized form for this expression, this returns null.
5191 /// 
5192 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5193                                           InstCombiner &IC) {
5194   TargetData &TD = IC.getTargetData();
5195   gep_type_iterator GTI = gep_type_begin(GEP);
5196
5197   // Check to see if this gep only has a single variable index.  If so, and if
5198   // any constant indices are a multiple of its scale, then we can compute this
5199   // in terms of the scale of the variable index.  For example, if the GEP
5200   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5201   // because the expression will cross zero at the same point.
5202   unsigned i, e = GEP->getNumOperands();
5203   int64_t Offset = 0;
5204   for (i = 1; i != e; ++i, ++GTI) {
5205     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5206       // Compute the aggregate offset of constant indices.
5207       if (CI->isZero()) continue;
5208
5209       // Handle a struct index, which adds its field offset to the pointer.
5210       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5211         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5212       } else {
5213         uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
5214         Offset += Size*CI->getSExtValue();
5215       }
5216     } else {
5217       // Found our variable index.
5218       break;
5219     }
5220   }
5221   
5222   // If there are no variable indices, we must have a constant offset, just
5223   // evaluate it the general way.
5224   if (i == e) return 0;
5225   
5226   Value *VariableIdx = GEP->getOperand(i);
5227   // Determine the scale factor of the variable element.  For example, this is
5228   // 4 if the variable index is into an array of i32.
5229   uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
5230   
5231   // Verify that there are no other variable indices.  If so, emit the hard way.
5232   for (++i, ++GTI; i != e; ++i, ++GTI) {
5233     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5234     if (!CI) return 0;
5235    
5236     // Compute the aggregate offset of constant indices.
5237     if (CI->isZero()) continue;
5238     
5239     // Handle a struct index, which adds its field offset to the pointer.
5240     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5241       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5242     } else {
5243       uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
5244       Offset += Size*CI->getSExtValue();
5245     }
5246   }
5247   
5248   // Okay, we know we have a single variable index, which must be a
5249   // pointer/array/vector index.  If there is no offset, life is simple, return
5250   // the index.
5251   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5252   if (Offset == 0) {
5253     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5254     // we don't need to bother extending: the extension won't affect where the
5255     // computation crosses zero.
5256     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5257       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5258                                   VariableIdx->getNameStart(), &I);
5259     return VariableIdx;
5260   }
5261   
5262   // Otherwise, there is an index.  The computation we will do will be modulo
5263   // the pointer size, so get it.
5264   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5265   
5266   Offset &= PtrSizeMask;
5267   VariableScale &= PtrSizeMask;
5268
5269   // To do this transformation, any constant index must be a multiple of the
5270   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5271   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5272   // multiple of the variable scale.
5273   int64_t NewOffs = Offset / (int64_t)VariableScale;
5274   if (Offset != NewOffs*(int64_t)VariableScale)
5275     return 0;
5276
5277   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5278   const Type *IntPtrTy = TD.getIntPtrType();
5279   if (VariableIdx->getType() != IntPtrTy)
5280     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5281                                               true /*SExt*/, 
5282                                               VariableIdx->getNameStart(), &I);
5283   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5284   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5285 }
5286
5287
5288 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5289 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5290 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5291                                        ICmpInst::Predicate Cond,
5292                                        Instruction &I) {
5293   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5294
5295   // Look through bitcasts.
5296   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5297     RHS = BCI->getOperand(0);
5298
5299   Value *PtrBase = GEPLHS->getOperand(0);
5300   if (PtrBase == RHS) {
5301     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5302     // This transformation (ignoring the base and scales) is valid because we
5303     // know pointers can't overflow.  See if we can output an optimized form.
5304     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5305     
5306     // If not, synthesize the offset the hard way.
5307     if (Offset == 0)
5308       Offset = EmitGEPOffset(GEPLHS, I, *this);
5309     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5310                         Constant::getNullValue(Offset->getType()));
5311   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5312     // If the base pointers are different, but the indices are the same, just
5313     // compare the base pointer.
5314     if (PtrBase != GEPRHS->getOperand(0)) {
5315       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5316       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5317                         GEPRHS->getOperand(0)->getType();
5318       if (IndicesTheSame)
5319         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5320           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5321             IndicesTheSame = false;
5322             break;
5323           }
5324
5325       // If all indices are the same, just compare the base pointers.
5326       if (IndicesTheSame)
5327         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5328                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5329
5330       // Otherwise, the base pointers are different and the indices are
5331       // different, bail out.
5332       return 0;
5333     }
5334
5335     // If one of the GEPs has all zero indices, recurse.
5336     bool AllZeros = true;
5337     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5338       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5339           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5340         AllZeros = false;
5341         break;
5342       }
5343     if (AllZeros)
5344       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5345                           ICmpInst::getSwappedPredicate(Cond), I);
5346
5347     // If the other GEP has all zero indices, recurse.
5348     AllZeros = true;
5349     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5350       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5351           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5352         AllZeros = false;
5353         break;
5354       }
5355     if (AllZeros)
5356       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5357
5358     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5359       // If the GEPs only differ by one index, compare it.
5360       unsigned NumDifferences = 0;  // Keep track of # differences.
5361       unsigned DiffOperand = 0;     // The operand that differs.
5362       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5363         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5364           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5365                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5366             // Irreconcilable differences.
5367             NumDifferences = 2;
5368             break;
5369           } else {
5370             if (NumDifferences++) break;
5371             DiffOperand = i;
5372           }
5373         }
5374
5375       if (NumDifferences == 0)   // SAME GEP?
5376         return ReplaceInstUsesWith(I, // No comparison is needed here.
5377                                    ConstantInt::get(Type::Int1Ty,
5378                                              ICmpInst::isTrueWhenEqual(Cond)));
5379
5380       else if (NumDifferences == 1) {
5381         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5382         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5383         // Make sure we do a signed comparison here.
5384         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5385       }
5386     }
5387
5388     // Only lower this if the icmp is the only user of the GEP or if we expect
5389     // the result to fold to a constant!
5390     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5391         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5392       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5393       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5394       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5395       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5396     }
5397   }
5398   return 0;
5399 }
5400
5401 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5402 ///
5403 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5404                                                 Instruction *LHSI,
5405                                                 Constant *RHSC) {
5406   if (!isa<ConstantFP>(RHSC)) return 0;
5407   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5408   
5409   // Get the width of the mantissa.  We don't want to hack on conversions that
5410   // might lose information from the integer, e.g. "i64 -> float"
5411   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5412   if (MantissaWidth == -1) return 0;  // Unknown.
5413   
5414   // Check to see that the input is converted from an integer type that is small
5415   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5416   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5417   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5418   
5419   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5420   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5421   if (LHSUnsigned)
5422     ++InputSize;
5423   
5424   // If the conversion would lose info, don't hack on this.
5425   if ((int)InputSize > MantissaWidth)
5426     return 0;
5427   
5428   // Otherwise, we can potentially simplify the comparison.  We know that it
5429   // will always come through as an integer value and we know the constant is
5430   // not a NAN (it would have been previously simplified).
5431   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5432   
5433   ICmpInst::Predicate Pred;
5434   switch (I.getPredicate()) {
5435   default: assert(0 && "Unexpected predicate!");
5436   case FCmpInst::FCMP_UEQ:
5437   case FCmpInst::FCMP_OEQ:
5438     Pred = ICmpInst::ICMP_EQ;
5439     break;
5440   case FCmpInst::FCMP_UGT:
5441   case FCmpInst::FCMP_OGT:
5442     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5443     break;
5444   case FCmpInst::FCMP_UGE:
5445   case FCmpInst::FCMP_OGE:
5446     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5447     break;
5448   case FCmpInst::FCMP_ULT:
5449   case FCmpInst::FCMP_OLT:
5450     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5451     break;
5452   case FCmpInst::FCMP_ULE:
5453   case FCmpInst::FCMP_OLE:
5454     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5455     break;
5456   case FCmpInst::FCMP_UNE:
5457   case FCmpInst::FCMP_ONE:
5458     Pred = ICmpInst::ICMP_NE;
5459     break;
5460   case FCmpInst::FCMP_ORD:
5461     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5462   case FCmpInst::FCMP_UNO:
5463     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5464   }
5465   
5466   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5467   
5468   // Now we know that the APFloat is a normal number, zero or inf.
5469   
5470   // See if the FP constant is too large for the integer.  For example,
5471   // comparing an i8 to 300.0.
5472   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5473   
5474   if (!LHSUnsigned) {
5475     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5476     // and large values.
5477     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5478     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5479                           APFloat::rmNearestTiesToEven);
5480     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5481       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5482           Pred == ICmpInst::ICMP_SLE)
5483         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5484       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5485     }
5486   } else {
5487     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5488     // +INF and large values.
5489     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5490     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5491                           APFloat::rmNearestTiesToEven);
5492     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5493       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5494           Pred == ICmpInst::ICMP_ULE)
5495         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5496       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5497     }
5498   }
5499   
5500   if (!LHSUnsigned) {
5501     // See if the RHS value is < SignedMin.
5502     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5503     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5504                           APFloat::rmNearestTiesToEven);
5505     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5506       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5507           Pred == ICmpInst::ICMP_SGE)
5508         return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5509       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5510     }
5511   }
5512
5513   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5514   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5515   // casting the FP value to the integer value and back, checking for equality.
5516   // Don't do this for zero, because -0.0 is not fractional.
5517   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5518   if (!RHS.isZero() &&
5519       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5520     // If we had a comparison against a fractional value, we have to adjust the
5521     // compare predicate and sometimes the value.  RHSC is rounded towards zero
5522     // at this point.
5523     switch (Pred) {
5524     default: assert(0 && "Unexpected integer comparison!");
5525     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5526       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5527     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5528       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5529     case ICmpInst::ICMP_ULE:
5530       // (float)int <= 4.4   --> int <= 4
5531       // (float)int <= -4.4  --> false
5532       if (RHS.isNegative())
5533         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5534       break;
5535     case ICmpInst::ICMP_SLE:
5536       // (float)int <= 4.4   --> int <= 4
5537       // (float)int <= -4.4  --> int < -4
5538       if (RHS.isNegative())
5539         Pred = ICmpInst::ICMP_SLT;
5540       break;
5541     case ICmpInst::ICMP_ULT:
5542       // (float)int < -4.4   --> false
5543       // (float)int < 4.4    --> int <= 4
5544       if (RHS.isNegative())
5545         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5546       Pred = ICmpInst::ICMP_ULE;
5547       break;
5548     case ICmpInst::ICMP_SLT:
5549       // (float)int < -4.4   --> int < -4
5550       // (float)int < 4.4    --> int <= 4
5551       if (!RHS.isNegative())
5552         Pred = ICmpInst::ICMP_SLE;
5553       break;
5554     case ICmpInst::ICMP_UGT:
5555       // (float)int > 4.4    --> int > 4
5556       // (float)int > -4.4   --> true
5557       if (RHS.isNegative())
5558         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5559       break;
5560     case ICmpInst::ICMP_SGT:
5561       // (float)int > 4.4    --> int > 4
5562       // (float)int > -4.4   --> int >= -4
5563       if (RHS.isNegative())
5564         Pred = ICmpInst::ICMP_SGE;
5565       break;
5566     case ICmpInst::ICMP_UGE:
5567       // (float)int >= -4.4   --> true
5568       // (float)int >= 4.4    --> int > 4
5569       if (!RHS.isNegative())
5570         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5571       Pred = ICmpInst::ICMP_UGT;
5572       break;
5573     case ICmpInst::ICMP_SGE:
5574       // (float)int >= -4.4   --> int >= -4
5575       // (float)int >= 4.4    --> int > 4
5576       if (!RHS.isNegative())
5577         Pred = ICmpInst::ICMP_SGT;
5578       break;
5579     }
5580   }
5581
5582   // Lower this FP comparison into an appropriate integer version of the
5583   // comparison.
5584   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5585 }
5586
5587 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5588   bool Changed = SimplifyCompare(I);
5589   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5590
5591   // Fold trivial predicates.
5592   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5593     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5594   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5595     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5596   
5597   // Simplify 'fcmp pred X, X'
5598   if (Op0 == Op1) {
5599     switch (I.getPredicate()) {
5600     default: assert(0 && "Unknown predicate!");
5601     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5602     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5603     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5604       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5605     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5606     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5607     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5608       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5609       
5610     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5611     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5612     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5613     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5614       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5615       I.setPredicate(FCmpInst::FCMP_UNO);
5616       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5617       return &I;
5618       
5619     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5620     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5621     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5622     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5623       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5624       I.setPredicate(FCmpInst::FCMP_ORD);
5625       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5626       return &I;
5627     }
5628   }
5629     
5630   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5631     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5632
5633   // Handle fcmp with constant RHS
5634   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5635     // If the constant is a nan, see if we can fold the comparison based on it.
5636     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5637       if (CFP->getValueAPF().isNaN()) {
5638         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5639           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5640         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5641                "Comparison must be either ordered or unordered!");
5642         // True if unordered.
5643         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5644       }
5645     }
5646     
5647     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5648       switch (LHSI->getOpcode()) {
5649       case Instruction::PHI:
5650         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5651         // block.  If in the same block, we're encouraging jump threading.  If
5652         // not, we are just pessimizing the code by making an i1 phi.
5653         if (LHSI->getParent() == I.getParent())
5654           if (Instruction *NV = FoldOpIntoPhi(I))
5655             return NV;
5656         break;
5657       case Instruction::SIToFP:
5658       case Instruction::UIToFP:
5659         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5660           return NV;
5661         break;
5662       case Instruction::Select:
5663         // If either operand of the select is a constant, we can fold the
5664         // comparison into the select arms, which will cause one to be
5665         // constant folded and the select turned into a bitwise or.
5666         Value *Op1 = 0, *Op2 = 0;
5667         if (LHSI->hasOneUse()) {
5668           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5669             // Fold the known value into the constant operand.
5670             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5671             // Insert a new FCmp of the other select operand.
5672             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5673                                                       LHSI->getOperand(2), RHSC,
5674                                                       I.getName()), I);
5675           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5676             // Fold the known value into the constant operand.
5677             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5678             // Insert a new FCmp of the other select operand.
5679             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5680                                                       LHSI->getOperand(1), RHSC,
5681                                                       I.getName()), I);
5682           }
5683         }
5684
5685         if (Op1)
5686           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5687         break;
5688       }
5689   }
5690
5691   return Changed ? &I : 0;
5692 }
5693
5694 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5695   bool Changed = SimplifyCompare(I);
5696   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5697   const Type *Ty = Op0->getType();
5698
5699   // icmp X, X
5700   if (Op0 == Op1)
5701     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5702                                                    I.isTrueWhenEqual()));
5703
5704   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5705     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5706   
5707   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5708   // addresses never equal each other!  We already know that Op0 != Op1.
5709   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5710        isa<ConstantPointerNull>(Op0)) &&
5711       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5712        isa<ConstantPointerNull>(Op1)))
5713     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5714                                                    !I.isTrueWhenEqual()));
5715
5716   // icmp's with boolean values can always be turned into bitwise operations
5717   if (Ty == Type::Int1Ty) {
5718     switch (I.getPredicate()) {
5719     default: assert(0 && "Invalid icmp instruction!");
5720     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5721       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5722       InsertNewInstBefore(Xor, I);
5723       return BinaryOperator::CreateNot(Xor);
5724     }
5725     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5726       return BinaryOperator::CreateXor(Op0, Op1);
5727
5728     case ICmpInst::ICMP_UGT:
5729       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5730       // FALL THROUGH
5731     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5732       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5733       InsertNewInstBefore(Not, I);
5734       return BinaryOperator::CreateAnd(Not, Op1);
5735     }
5736     case ICmpInst::ICMP_SGT:
5737       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5738       // FALL THROUGH
5739     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5740       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5741       InsertNewInstBefore(Not, I);
5742       return BinaryOperator::CreateAnd(Not, Op0);
5743     }
5744     case ICmpInst::ICMP_UGE:
5745       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5746       // FALL THROUGH
5747     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5748       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5749       InsertNewInstBefore(Not, I);
5750       return BinaryOperator::CreateOr(Not, Op1);
5751     }
5752     case ICmpInst::ICMP_SGE:
5753       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5754       // FALL THROUGH
5755     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5756       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5757       InsertNewInstBefore(Not, I);
5758       return BinaryOperator::CreateOr(Not, Op0);
5759     }
5760     }
5761   }
5762
5763   // See if we are doing a comparison with a constant.
5764   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5765     Value *A, *B;
5766     
5767     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5768     if (I.isEquality() && CI->isNullValue() &&
5769         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5770       // (icmp cond A B) if cond is equality
5771       return new ICmpInst(I.getPredicate(), A, B);
5772     }
5773     
5774     // If we have an icmp le or icmp ge instruction, turn it into the
5775     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5776     // them being folded in the code below.
5777     switch (I.getPredicate()) {
5778     default: break;
5779     case ICmpInst::ICMP_ULE:
5780       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5781         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5782       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5783     case ICmpInst::ICMP_SLE:
5784       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5785         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5786       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5787     case ICmpInst::ICMP_UGE:
5788       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5789         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5790       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5791     case ICmpInst::ICMP_SGE:
5792       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5793         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5794       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5795     }
5796     
5797     // See if we can fold the comparison based on range information we can get
5798     // by checking whether bits are known to be zero or one in the input.
5799     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5800     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5801     
5802     // If this comparison is a normal comparison, it demands all
5803     // bits, if it is a sign bit comparison, it only demands the sign bit.
5804     bool UnusedBit;
5805     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5806     
5807     if (SimplifyDemandedBits(I.getOperandUse(0), 
5808                              isSignBit ? APInt::getSignBit(BitWidth)
5809                                        : APInt::getAllOnesValue(BitWidth),
5810                              KnownZero, KnownOne, 0))
5811       return &I;
5812         
5813     // Given the known and unknown bits, compute a range that the LHS could be
5814     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5815     // EQ and NE we use unsigned values.
5816     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5817     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5818       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5819     else
5820       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5821     
5822     // If Min and Max are known to be the same, then SimplifyDemandedBits
5823     // figured out that the LHS is a constant.  Just constant fold this now so
5824     // that code below can assume that Min != Max.
5825     if (Min == Max)
5826       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5827                                                           ConstantInt::get(Min),
5828                                                           CI));
5829     
5830     // Based on the range information we know about the LHS, see if we can
5831     // simplify this comparison.  For example, (x&4) < 8  is always true.
5832     const APInt &RHSVal = CI->getValue();
5833     switch (I.getPredicate()) {  // LE/GE have been folded already.
5834     default: assert(0 && "Unknown icmp opcode!");
5835     case ICmpInst::ICMP_EQ:
5836       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5837         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5838       break;
5839     case ICmpInst::ICMP_NE:
5840       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5841         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5842       break;
5843     case ICmpInst::ICMP_ULT:
5844       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5845         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5846       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5847         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5848       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5849         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5850       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5851         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5852         
5853       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5854       if (CI->isMinValue(true))
5855         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5856                             ConstantInt::getAllOnesValue(Op0->getType()));
5857       break;
5858     case ICmpInst::ICMP_UGT:
5859       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5860         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5861       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5862         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5863         
5864       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5865         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5866       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5867         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5868       
5869       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5870       if (CI->isMaxValue(true))
5871         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5872                             ConstantInt::getNullValue(Op0->getType()));
5873       break;
5874     case ICmpInst::ICMP_SLT:
5875       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5876         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5877       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5878         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5879       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5880         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5881       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5882         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5883       break;
5884     case ICmpInst::ICMP_SGT: 
5885       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5886         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5887       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5888         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5889         
5890       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5891         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5892       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5893         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5894       break;
5895     }
5896   }
5897
5898   // Test if the ICmpInst instruction is used exclusively by a select as
5899   // part of a minimum or maximum operation. If so, refrain from doing
5900   // any other folding. This helps out other analyses which understand
5901   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5902   // and CodeGen. And in this case, at least one of the comparison
5903   // operands has at least one user besides the compare (the select),
5904   // which would often largely negate the benefit of folding anyway.
5905   if (I.hasOneUse())
5906     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5907       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5908           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5909         return 0;
5910
5911   // See if we are doing a comparison between a constant and an instruction that
5912   // can be folded into the comparison.
5913   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5914     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5915     // instruction, see if that instruction also has constants so that the 
5916     // instruction can be folded into the icmp 
5917     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5918       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5919         return Res;
5920   }
5921
5922   // Handle icmp with constant (but not simple integer constant) RHS
5923   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5924     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5925       switch (LHSI->getOpcode()) {
5926       case Instruction::GetElementPtr:
5927         if (RHSC->isNullValue()) {
5928           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5929           bool isAllZeros = true;
5930           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5931             if (!isa<Constant>(LHSI->getOperand(i)) ||
5932                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5933               isAllZeros = false;
5934               break;
5935             }
5936           if (isAllZeros)
5937             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5938                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5939         }
5940         break;
5941
5942       case Instruction::PHI:
5943         // Only fold icmp into the PHI if the phi and fcmp are in the same
5944         // block.  If in the same block, we're encouraging jump threading.  If
5945         // not, we are just pessimizing the code by making an i1 phi.
5946         if (LHSI->getParent() == I.getParent())
5947           if (Instruction *NV = FoldOpIntoPhi(I))
5948             return NV;
5949         break;
5950       case Instruction::Select: {
5951         // If either operand of the select is a constant, we can fold the
5952         // comparison into the select arms, which will cause one to be
5953         // constant folded and the select turned into a bitwise or.
5954         Value *Op1 = 0, *Op2 = 0;
5955         if (LHSI->hasOneUse()) {
5956           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5957             // Fold the known value into the constant operand.
5958             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5959             // Insert a new ICmp of the other select operand.
5960             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5961                                                    LHSI->getOperand(2), RHSC,
5962                                                    I.getName()), I);
5963           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5964             // Fold the known value into the constant operand.
5965             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5966             // Insert a new ICmp of the other select operand.
5967             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5968                                                    LHSI->getOperand(1), RHSC,
5969                                                    I.getName()), I);
5970           }
5971         }
5972
5973         if (Op1)
5974           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5975         break;
5976       }
5977       case Instruction::Malloc:
5978         // If we have (malloc != null), and if the malloc has a single use, we
5979         // can assume it is successful and remove the malloc.
5980         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5981           AddToWorkList(LHSI);
5982           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5983                                                          !I.isTrueWhenEqual()));
5984         }
5985         break;
5986       }
5987   }
5988
5989   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5990   if (User *GEP = dyn_castGetElementPtr(Op0))
5991     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5992       return NI;
5993   if (User *GEP = dyn_castGetElementPtr(Op1))
5994     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5995                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5996       return NI;
5997
5998   // Test to see if the operands of the icmp are casted versions of other
5999   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6000   // now.
6001   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6002     if (isa<PointerType>(Op0->getType()) && 
6003         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6004       // We keep moving the cast from the left operand over to the right
6005       // operand, where it can often be eliminated completely.
6006       Op0 = CI->getOperand(0);
6007
6008       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6009       // so eliminate it as well.
6010       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6011         Op1 = CI2->getOperand(0);
6012
6013       // If Op1 is a constant, we can fold the cast into the constant.
6014       if (Op0->getType() != Op1->getType()) {
6015         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6016           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6017         } else {
6018           // Otherwise, cast the RHS right before the icmp
6019           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6020         }
6021       }
6022       return new ICmpInst(I.getPredicate(), Op0, Op1);
6023     }
6024   }
6025   
6026   if (isa<CastInst>(Op0)) {
6027     // Handle the special case of: icmp (cast bool to X), <cst>
6028     // This comes up when you have code like
6029     //   int X = A < B;
6030     //   if (X) ...
6031     // For generality, we handle any zero-extension of any operand comparison
6032     // with a constant or another cast from the same type.
6033     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6034       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6035         return R;
6036   }
6037   
6038   // See if it's the same type of instruction on the left and right.
6039   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6040     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6041       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6042           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
6043           I.isEquality()) {
6044         switch (Op0I->getOpcode()) {
6045         default: break;
6046         case Instruction::Add:
6047         case Instruction::Sub:
6048         case Instruction::Xor:
6049           // a+x icmp eq/ne b+x --> a icmp b
6050           return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6051                               Op1I->getOperand(0));
6052           break;
6053         case Instruction::Mul:
6054           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6055             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6056             // Mask = -1 >> count-trailing-zeros(Cst).
6057             if (!CI->isZero() && !CI->isOne()) {
6058               const APInt &AP = CI->getValue();
6059               ConstantInt *Mask = ConstantInt::get(
6060                                       APInt::getLowBitsSet(AP.getBitWidth(),
6061                                                            AP.getBitWidth() -
6062                                                       AP.countTrailingZeros()));
6063               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6064                                                             Mask);
6065               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6066                                                             Mask);
6067               InsertNewInstBefore(And1, I);
6068               InsertNewInstBefore(And2, I);
6069               return new ICmpInst(I.getPredicate(), And1, And2);
6070             }
6071           }
6072           break;
6073         }
6074       }
6075     }
6076   }
6077   
6078   // ~x < ~y --> y < x
6079   { Value *A, *B;
6080     if (match(Op0, m_Not(m_Value(A))) &&
6081         match(Op1, m_Not(m_Value(B))))
6082       return new ICmpInst(I.getPredicate(), B, A);
6083   }
6084   
6085   if (I.isEquality()) {
6086     Value *A, *B, *C, *D;
6087     
6088     // -x == -y --> x == y
6089     if (match(Op0, m_Neg(m_Value(A))) &&
6090         match(Op1, m_Neg(m_Value(B))))
6091       return new ICmpInst(I.getPredicate(), A, B);
6092     
6093     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6094       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6095         Value *OtherVal = A == Op1 ? B : A;
6096         return new ICmpInst(I.getPredicate(), OtherVal,
6097                             Constant::getNullValue(A->getType()));
6098       }
6099
6100       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6101         // A^c1 == C^c2 --> A == C^(c1^c2)
6102         ConstantInt *C1, *C2;
6103         if (match(B, m_ConstantInt(C1)) &&
6104             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6105           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6106           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6107           return new ICmpInst(I.getPredicate(), A,
6108                               InsertNewInstBefore(Xor, I));
6109         }
6110         
6111         // A^B == A^D -> B == D
6112         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6113         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6114         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6115         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6116       }
6117     }
6118     
6119     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6120         (A == Op0 || B == Op0)) {
6121       // A == (A^B)  ->  B == 0
6122       Value *OtherVal = A == Op0 ? B : A;
6123       return new ICmpInst(I.getPredicate(), OtherVal,
6124                           Constant::getNullValue(A->getType()));
6125     }
6126
6127     // (A-B) == A  ->  B == 0
6128     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6129       return new ICmpInst(I.getPredicate(), B, 
6130                           Constant::getNullValue(B->getType()));
6131
6132     // A == (A-B)  ->  B == 0
6133     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6134       return new ICmpInst(I.getPredicate(), B,
6135                           Constant::getNullValue(B->getType()));
6136     
6137     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6138     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6139         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6140         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6141       Value *X = 0, *Y = 0, *Z = 0;
6142       
6143       if (A == C) {
6144         X = B; Y = D; Z = A;
6145       } else if (A == D) {
6146         X = B; Y = C; Z = A;
6147       } else if (B == C) {
6148         X = A; Y = D; Z = B;
6149       } else if (B == D) {
6150         X = A; Y = C; Z = B;
6151       }
6152       
6153       if (X) {   // Build (X^Y) & Z
6154         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6155         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6156         I.setOperand(0, Op1);
6157         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6158         return &I;
6159       }
6160     }
6161   }
6162   return Changed ? &I : 0;
6163 }
6164
6165
6166 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6167 /// and CmpRHS are both known to be integer constants.
6168 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6169                                           ConstantInt *DivRHS) {
6170   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6171   const APInt &CmpRHSV = CmpRHS->getValue();
6172   
6173   // FIXME: If the operand types don't match the type of the divide 
6174   // then don't attempt this transform. The code below doesn't have the
6175   // logic to deal with a signed divide and an unsigned compare (and
6176   // vice versa). This is because (x /s C1) <s C2  produces different 
6177   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6178   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6179   // work. :(  The if statement below tests that condition and bails 
6180   // if it finds it. 
6181   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6182   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6183     return 0;
6184   if (DivRHS->isZero())
6185     return 0; // The ProdOV computation fails on divide by zero.
6186   if (DivIsSigned && DivRHS->isAllOnesValue())
6187     return 0; // The overflow computation also screws up here
6188   if (DivRHS->isOne())
6189     return 0; // Not worth bothering, and eliminates some funny cases
6190               // with INT_MIN.
6191
6192   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6193   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6194   // C2 (CI). By solving for X we can turn this into a range check 
6195   // instead of computing a divide. 
6196   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6197
6198   // Determine if the product overflows by seeing if the product is
6199   // not equal to the divide. Make sure we do the same kind of divide
6200   // as in the LHS instruction that we're folding. 
6201   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6202                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6203
6204   // Get the ICmp opcode
6205   ICmpInst::Predicate Pred = ICI.getPredicate();
6206
6207   // Figure out the interval that is being checked.  For example, a comparison
6208   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6209   // Compute this interval based on the constants involved and the signedness of
6210   // the compare/divide.  This computes a half-open interval, keeping track of
6211   // whether either value in the interval overflows.  After analysis each
6212   // overflow variable is set to 0 if it's corresponding bound variable is valid
6213   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6214   int LoOverflow = 0, HiOverflow = 0;
6215   ConstantInt *LoBound = 0, *HiBound = 0;
6216   
6217   if (!DivIsSigned) {  // udiv
6218     // e.g. X/5 op 3  --> [15, 20)
6219     LoBound = Prod;
6220     HiOverflow = LoOverflow = ProdOV;
6221     if (!HiOverflow)
6222       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6223   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6224     if (CmpRHSV == 0) {       // (X / pos) op 0
6225       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6226       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6227       HiBound = DivRHS;
6228     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6229       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6230       HiOverflow = LoOverflow = ProdOV;
6231       if (!HiOverflow)
6232         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6233     } else {                       // (X / pos) op neg
6234       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6235       HiBound = AddOne(Prod);
6236       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6237       if (!LoOverflow) {
6238         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6239         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6240                                      true) ? -1 : 0;
6241        }
6242     }
6243   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6244     if (CmpRHSV == 0) {       // (X / neg) op 0
6245       // e.g. X/-5 op 0  --> [-4, 5)
6246       LoBound = AddOne(DivRHS);
6247       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6248       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6249         HiOverflow = 1;            // [INTMIN+1, overflow)
6250         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6251       }
6252     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6253       // e.g. X/-5 op 3  --> [-19, -14)
6254       HiBound = AddOne(Prod);
6255       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6256       if (!LoOverflow)
6257         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6258     } else {                       // (X / neg) op neg
6259       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6260       LoOverflow = HiOverflow = ProdOV;
6261       if (!HiOverflow)
6262         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6263     }
6264     
6265     // Dividing by a negative swaps the condition.  LT <-> GT
6266     Pred = ICmpInst::getSwappedPredicate(Pred);
6267   }
6268
6269   Value *X = DivI->getOperand(0);
6270   switch (Pred) {
6271   default: assert(0 && "Unhandled icmp opcode!");
6272   case ICmpInst::ICMP_EQ:
6273     if (LoOverflow && HiOverflow)
6274       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6275     else if (HiOverflow)
6276       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6277                           ICmpInst::ICMP_UGE, X, LoBound);
6278     else if (LoOverflow)
6279       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6280                           ICmpInst::ICMP_ULT, X, HiBound);
6281     else
6282       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6283   case ICmpInst::ICMP_NE:
6284     if (LoOverflow && HiOverflow)
6285       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6286     else if (HiOverflow)
6287       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6288                           ICmpInst::ICMP_ULT, X, LoBound);
6289     else if (LoOverflow)
6290       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6291                           ICmpInst::ICMP_UGE, X, HiBound);
6292     else
6293       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6294   case ICmpInst::ICMP_ULT:
6295   case ICmpInst::ICMP_SLT:
6296     if (LoOverflow == +1)   // Low bound is greater than input range.
6297       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6298     if (LoOverflow == -1)   // Low bound is less than input range.
6299       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6300     return new ICmpInst(Pred, X, LoBound);
6301   case ICmpInst::ICMP_UGT:
6302   case ICmpInst::ICMP_SGT:
6303     if (HiOverflow == +1)       // High bound greater than input range.
6304       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6305     else if (HiOverflow == -1)  // High bound less than input range.
6306       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6307     if (Pred == ICmpInst::ICMP_UGT)
6308       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6309     else
6310       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6311   }
6312 }
6313
6314
6315 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6316 ///
6317 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6318                                                           Instruction *LHSI,
6319                                                           ConstantInt *RHS) {
6320   const APInt &RHSV = RHS->getValue();
6321   
6322   switch (LHSI->getOpcode()) {
6323   case Instruction::Trunc:
6324     if (ICI.isEquality() && LHSI->hasOneUse()) {
6325       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6326       // of the high bits truncated out of x are known.
6327       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6328              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6329       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6330       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6331       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6332       
6333       // If all the high bits are known, we can do this xform.
6334       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6335         // Pull in the high bits from known-ones set.
6336         APInt NewRHS(RHS->getValue());
6337         NewRHS.zext(SrcBits);
6338         NewRHS |= KnownOne;
6339         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6340                             ConstantInt::get(NewRHS));
6341       }
6342     }
6343     break;
6344       
6345   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6346     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6347       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6348       // fold the xor.
6349       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6350           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6351         Value *CompareVal = LHSI->getOperand(0);
6352         
6353         // If the sign bit of the XorCST is not set, there is no change to
6354         // the operation, just stop using the Xor.
6355         if (!XorCST->getValue().isNegative()) {
6356           ICI.setOperand(0, CompareVal);
6357           AddToWorkList(LHSI);
6358           return &ICI;
6359         }
6360         
6361         // Was the old condition true if the operand is positive?
6362         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6363         
6364         // If so, the new one isn't.
6365         isTrueIfPositive ^= true;
6366         
6367         if (isTrueIfPositive)
6368           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6369         else
6370           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6371       }
6372     }
6373     break;
6374   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6375     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6376         LHSI->getOperand(0)->hasOneUse()) {
6377       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6378       
6379       // If the LHS is an AND of a truncating cast, we can widen the
6380       // and/compare to be the input width without changing the value
6381       // produced, eliminating a cast.
6382       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6383         // We can do this transformation if either the AND constant does not
6384         // have its sign bit set or if it is an equality comparison. 
6385         // Extending a relational comparison when we're checking the sign
6386         // bit would not work.
6387         if (Cast->hasOneUse() &&
6388             (ICI.isEquality() ||
6389              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6390           uint32_t BitWidth = 
6391             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6392           APInt NewCST = AndCST->getValue();
6393           NewCST.zext(BitWidth);
6394           APInt NewCI = RHSV;
6395           NewCI.zext(BitWidth);
6396           Instruction *NewAnd = 
6397             BinaryOperator::CreateAnd(Cast->getOperand(0),
6398                                       ConstantInt::get(NewCST),LHSI->getName());
6399           InsertNewInstBefore(NewAnd, ICI);
6400           return new ICmpInst(ICI.getPredicate(), NewAnd,
6401                               ConstantInt::get(NewCI));
6402         }
6403       }
6404       
6405       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6406       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6407       // happens a LOT in code produced by the C front-end, for bitfield
6408       // access.
6409       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6410       if (Shift && !Shift->isShift())
6411         Shift = 0;
6412       
6413       ConstantInt *ShAmt;
6414       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6415       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6416       const Type *AndTy = AndCST->getType();          // Type of the and.
6417       
6418       // We can fold this as long as we can't shift unknown bits
6419       // into the mask.  This can only happen with signed shift
6420       // rights, as they sign-extend.
6421       if (ShAmt) {
6422         bool CanFold = Shift->isLogicalShift();
6423         if (!CanFold) {
6424           // To test for the bad case of the signed shr, see if any
6425           // of the bits shifted in could be tested after the mask.
6426           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6427           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6428           
6429           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6430           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6431                AndCST->getValue()) == 0)
6432             CanFold = true;
6433         }
6434         
6435         if (CanFold) {
6436           Constant *NewCst;
6437           if (Shift->getOpcode() == Instruction::Shl)
6438             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6439           else
6440             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6441           
6442           // Check to see if we are shifting out any of the bits being
6443           // compared.
6444           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6445             // If we shifted bits out, the fold is not going to work out.
6446             // As a special case, check to see if this means that the
6447             // result is always true or false now.
6448             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6449               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6450             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6451               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6452           } else {
6453             ICI.setOperand(1, NewCst);
6454             Constant *NewAndCST;
6455             if (Shift->getOpcode() == Instruction::Shl)
6456               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6457             else
6458               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6459             LHSI->setOperand(1, NewAndCST);
6460             LHSI->setOperand(0, Shift->getOperand(0));
6461             AddToWorkList(Shift); // Shift is dead.
6462             AddUsesToWorkList(ICI);
6463             return &ICI;
6464           }
6465         }
6466       }
6467       
6468       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6469       // preferable because it allows the C<<Y expression to be hoisted out
6470       // of a loop if Y is invariant and X is not.
6471       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6472           ICI.isEquality() && !Shift->isArithmeticShift() &&
6473           isa<Instruction>(Shift->getOperand(0))) {
6474         // Compute C << Y.
6475         Value *NS;
6476         if (Shift->getOpcode() == Instruction::LShr) {
6477           NS = BinaryOperator::CreateShl(AndCST, 
6478                                          Shift->getOperand(1), "tmp");
6479         } else {
6480           // Insert a logical shift.
6481           NS = BinaryOperator::CreateLShr(AndCST,
6482                                           Shift->getOperand(1), "tmp");
6483         }
6484         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6485         
6486         // Compute X & (C << Y).
6487         Instruction *NewAnd = 
6488           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6489         InsertNewInstBefore(NewAnd, ICI);
6490         
6491         ICI.setOperand(0, NewAnd);
6492         return &ICI;
6493       }
6494     }
6495     break;
6496     
6497   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6498     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6499     if (!ShAmt) break;
6500     
6501     uint32_t TypeBits = RHSV.getBitWidth();
6502     
6503     // Check that the shift amount is in range.  If not, don't perform
6504     // undefined shifts.  When the shift is visited it will be
6505     // simplified.
6506     if (ShAmt->uge(TypeBits))
6507       break;
6508     
6509     if (ICI.isEquality()) {
6510       // If we are comparing against bits always shifted out, the
6511       // comparison cannot succeed.
6512       Constant *Comp =
6513         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6514       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6515         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6516         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6517         return ReplaceInstUsesWith(ICI, Cst);
6518       }
6519       
6520       if (LHSI->hasOneUse()) {
6521         // Otherwise strength reduce the shift into an and.
6522         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6523         Constant *Mask =
6524           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6525         
6526         Instruction *AndI =
6527           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6528                                     Mask, LHSI->getName()+".mask");
6529         Value *And = InsertNewInstBefore(AndI, ICI);
6530         return new ICmpInst(ICI.getPredicate(), And,
6531                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6532       }
6533     }
6534     
6535     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6536     bool TrueIfSigned = false;
6537     if (LHSI->hasOneUse() &&
6538         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6539       // (X << 31) <s 0  --> (X&1) != 0
6540       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6541                                            (TypeBits-ShAmt->getZExtValue()-1));
6542       Instruction *AndI =
6543         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6544                                   Mask, LHSI->getName()+".mask");
6545       Value *And = InsertNewInstBefore(AndI, ICI);
6546       
6547       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6548                           And, Constant::getNullValue(And->getType()));
6549     }
6550     break;
6551   }
6552     
6553   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6554   case Instruction::AShr: {
6555     // Only handle equality comparisons of shift-by-constant.
6556     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6557     if (!ShAmt || !ICI.isEquality()) break;
6558
6559     // Check that the shift amount is in range.  If not, don't perform
6560     // undefined shifts.  When the shift is visited it will be
6561     // simplified.
6562     uint32_t TypeBits = RHSV.getBitWidth();
6563     if (ShAmt->uge(TypeBits))
6564       break;
6565     
6566     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6567       
6568     // If we are comparing against bits always shifted out, the
6569     // comparison cannot succeed.
6570     APInt Comp = RHSV << ShAmtVal;
6571     if (LHSI->getOpcode() == Instruction::LShr)
6572       Comp = Comp.lshr(ShAmtVal);
6573     else
6574       Comp = Comp.ashr(ShAmtVal);
6575     
6576     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6577       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6578       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6579       return ReplaceInstUsesWith(ICI, Cst);
6580     }
6581     
6582     // Otherwise, check to see if the bits shifted out are known to be zero.
6583     // If so, we can compare against the unshifted value:
6584     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6585     if (LHSI->hasOneUse() &&
6586         MaskedValueIsZero(LHSI->getOperand(0), 
6587                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6588       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6589                           ConstantExpr::getShl(RHS, ShAmt));
6590     }
6591       
6592     if (LHSI->hasOneUse()) {
6593       // Otherwise strength reduce the shift into an and.
6594       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6595       Constant *Mask = ConstantInt::get(Val);
6596       
6597       Instruction *AndI =
6598         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6599                                   Mask, LHSI->getName()+".mask");
6600       Value *And = InsertNewInstBefore(AndI, ICI);
6601       return new ICmpInst(ICI.getPredicate(), And,
6602                           ConstantExpr::getShl(RHS, ShAmt));
6603     }
6604     break;
6605   }
6606     
6607   case Instruction::SDiv:
6608   case Instruction::UDiv:
6609     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6610     // Fold this div into the comparison, producing a range check. 
6611     // Determine, based on the divide type, what the range is being 
6612     // checked.  If there is an overflow on the low or high side, remember 
6613     // it, otherwise compute the range [low, hi) bounding the new value.
6614     // See: InsertRangeTest above for the kinds of replacements possible.
6615     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6616       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6617                                           DivRHS))
6618         return R;
6619     break;
6620
6621   case Instruction::Add:
6622     // Fold: icmp pred (add, X, C1), C2
6623
6624     if (!ICI.isEquality()) {
6625       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6626       if (!LHSC) break;
6627       const APInt &LHSV = LHSC->getValue();
6628
6629       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6630                             .subtract(LHSV);
6631
6632       if (ICI.isSignedPredicate()) {
6633         if (CR.getLower().isSignBit()) {
6634           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6635                               ConstantInt::get(CR.getUpper()));
6636         } else if (CR.getUpper().isSignBit()) {
6637           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6638                               ConstantInt::get(CR.getLower()));
6639         }
6640       } else {
6641         if (CR.getLower().isMinValue()) {
6642           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6643                               ConstantInt::get(CR.getUpper()));
6644         } else if (CR.getUpper().isMinValue()) {
6645           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6646                               ConstantInt::get(CR.getLower()));
6647         }
6648       }
6649     }
6650     break;
6651   }
6652   
6653   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6654   if (ICI.isEquality()) {
6655     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6656     
6657     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6658     // the second operand is a constant, simplify a bit.
6659     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6660       switch (BO->getOpcode()) {
6661       case Instruction::SRem:
6662         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6663         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6664           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6665           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6666             Instruction *NewRem =
6667               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6668                                          BO->getName());
6669             InsertNewInstBefore(NewRem, ICI);
6670             return new ICmpInst(ICI.getPredicate(), NewRem, 
6671                                 Constant::getNullValue(BO->getType()));
6672           }
6673         }
6674         break;
6675       case Instruction::Add:
6676         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6677         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6678           if (BO->hasOneUse())
6679             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6680                                 Subtract(RHS, BOp1C));
6681         } else if (RHSV == 0) {
6682           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6683           // efficiently invertible, or if the add has just this one use.
6684           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6685           
6686           if (Value *NegVal = dyn_castNegVal(BOp1))
6687             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6688           else if (Value *NegVal = dyn_castNegVal(BOp0))
6689             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6690           else if (BO->hasOneUse()) {
6691             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6692             InsertNewInstBefore(Neg, ICI);
6693             Neg->takeName(BO);
6694             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6695           }
6696         }
6697         break;
6698       case Instruction::Xor:
6699         // For the xor case, we can xor two constants together, eliminating
6700         // the explicit xor.
6701         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6702           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6703                               ConstantExpr::getXor(RHS, BOC));
6704         
6705         // FALLTHROUGH
6706       case Instruction::Sub:
6707         // Replace (([sub|xor] A, B) != 0) with (A != B)
6708         if (RHSV == 0)
6709           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6710                               BO->getOperand(1));
6711         break;
6712         
6713       case Instruction::Or:
6714         // If bits are being or'd in that are not present in the constant we
6715         // are comparing against, then the comparison could never succeed!
6716         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6717           Constant *NotCI = ConstantExpr::getNot(RHS);
6718           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6719             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6720                                                              isICMP_NE));
6721         }
6722         break;
6723         
6724       case Instruction::And:
6725         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6726           // If bits are being compared against that are and'd out, then the
6727           // comparison can never succeed!
6728           if ((RHSV & ~BOC->getValue()) != 0)
6729             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6730                                                              isICMP_NE));
6731           
6732           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6733           if (RHS == BOC && RHSV.isPowerOf2())
6734             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6735                                 ICmpInst::ICMP_NE, LHSI,
6736                                 Constant::getNullValue(RHS->getType()));
6737           
6738           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6739           if (BOC->getValue().isSignBit()) {
6740             Value *X = BO->getOperand(0);
6741             Constant *Zero = Constant::getNullValue(X->getType());
6742             ICmpInst::Predicate pred = isICMP_NE ? 
6743               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6744             return new ICmpInst(pred, X, Zero);
6745           }
6746           
6747           // ((X & ~7) == 0) --> X < 8
6748           if (RHSV == 0 && isHighOnes(BOC)) {
6749             Value *X = BO->getOperand(0);
6750             Constant *NegX = ConstantExpr::getNeg(BOC);
6751             ICmpInst::Predicate pred = isICMP_NE ? 
6752               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6753             return new ICmpInst(pred, X, NegX);
6754           }
6755         }
6756       default: break;
6757       }
6758     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6759       // Handle icmp {eq|ne} <intrinsic>, intcst.
6760       if (II->getIntrinsicID() == Intrinsic::bswap) {
6761         AddToWorkList(II);
6762         ICI.setOperand(0, II->getOperand(1));
6763         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6764         return &ICI;
6765       }
6766     }
6767   }
6768   return 0;
6769 }
6770
6771 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6772 /// We only handle extending casts so far.
6773 ///
6774 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6775   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6776   Value *LHSCIOp        = LHSCI->getOperand(0);
6777   const Type *SrcTy     = LHSCIOp->getType();
6778   const Type *DestTy    = LHSCI->getType();
6779   Value *RHSCIOp;
6780
6781   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6782   // integer type is the same size as the pointer type.
6783   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6784       getTargetData().getPointerSizeInBits() == 
6785          cast<IntegerType>(DestTy)->getBitWidth()) {
6786     Value *RHSOp = 0;
6787     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6788       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6789     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6790       RHSOp = RHSC->getOperand(0);
6791       // If the pointer types don't match, insert a bitcast.
6792       if (LHSCIOp->getType() != RHSOp->getType())
6793         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6794     }
6795
6796     if (RHSOp)
6797       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6798   }
6799   
6800   // The code below only handles extension cast instructions, so far.
6801   // Enforce this.
6802   if (LHSCI->getOpcode() != Instruction::ZExt &&
6803       LHSCI->getOpcode() != Instruction::SExt)
6804     return 0;
6805
6806   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6807   bool isSignedCmp = ICI.isSignedPredicate();
6808
6809   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6810     // Not an extension from the same type?
6811     RHSCIOp = CI->getOperand(0);
6812     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6813       return 0;
6814     
6815     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6816     // and the other is a zext), then we can't handle this.
6817     if (CI->getOpcode() != LHSCI->getOpcode())
6818       return 0;
6819
6820     // Deal with equality cases early.
6821     if (ICI.isEquality())
6822       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6823
6824     // A signed comparison of sign extended values simplifies into a
6825     // signed comparison.
6826     if (isSignedCmp && isSignedExt)
6827       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6828
6829     // The other three cases all fold into an unsigned comparison.
6830     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6831   }
6832
6833   // If we aren't dealing with a constant on the RHS, exit early
6834   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6835   if (!CI)
6836     return 0;
6837
6838   // Compute the constant that would happen if we truncated to SrcTy then
6839   // reextended to DestTy.
6840   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6841   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6842
6843   // If the re-extended constant didn't change...
6844   if (Res2 == CI) {
6845     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6846     // For example, we might have:
6847     //    %A = sext short %X to uint
6848     //    %B = icmp ugt uint %A, 1330
6849     // It is incorrect to transform this into 
6850     //    %B = icmp ugt short %X, 1330 
6851     // because %A may have negative value. 
6852     //
6853     // However, we allow this when the compare is EQ/NE, because they are
6854     // signless.
6855     if (isSignedExt == isSignedCmp || ICI.isEquality())
6856       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6857     return 0;
6858   }
6859
6860   // The re-extended constant changed so the constant cannot be represented 
6861   // in the shorter type. Consequently, we cannot emit a simple comparison.
6862
6863   // First, handle some easy cases. We know the result cannot be equal at this
6864   // point so handle the ICI.isEquality() cases
6865   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6866     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6867   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6868     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6869
6870   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6871   // should have been folded away previously and not enter in here.
6872   Value *Result;
6873   if (isSignedCmp) {
6874     // We're performing a signed comparison.
6875     if (cast<ConstantInt>(CI)->getValue().isNegative())
6876       Result = ConstantInt::getFalse();          // X < (small) --> false
6877     else
6878       Result = ConstantInt::getTrue();           // X < (large) --> true
6879   } else {
6880     // We're performing an unsigned comparison.
6881     if (isSignedExt) {
6882       // We're performing an unsigned comp with a sign extended value.
6883       // This is true if the input is >= 0. [aka >s -1]
6884       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6885       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6886                                    NegOne, ICI.getName()), ICI);
6887     } else {
6888       // Unsigned extend & unsigned compare -> always true.
6889       Result = ConstantInt::getTrue();
6890     }
6891   }
6892
6893   // Finally, return the value computed.
6894   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6895       ICI.getPredicate() == ICmpInst::ICMP_SLT)
6896     return ReplaceInstUsesWith(ICI, Result);
6897
6898   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6899           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6900          "ICmp should be folded!");
6901   if (Constant *CI = dyn_cast<Constant>(Result))
6902     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6903   return BinaryOperator::CreateNot(Result);
6904 }
6905
6906 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6907   return commonShiftTransforms(I);
6908 }
6909
6910 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6911   return commonShiftTransforms(I);
6912 }
6913
6914 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6915   if (Instruction *R = commonShiftTransforms(I))
6916     return R;
6917   
6918   Value *Op0 = I.getOperand(0);
6919   
6920   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6921   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6922     if (CSI->isAllOnesValue())
6923       return ReplaceInstUsesWith(I, CSI);
6924   
6925   // See if we can turn a signed shr into an unsigned shr.
6926   if (!isa<VectorType>(I.getType()) &&
6927       MaskedValueIsZero(Op0,
6928                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6929     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6930   
6931   return 0;
6932 }
6933
6934 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6935   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6936   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6937
6938   // shl X, 0 == X and shr X, 0 == X
6939   // shl 0, X == 0 and shr 0, X == 0
6940   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6941       Op0 == Constant::getNullValue(Op0->getType()))
6942     return ReplaceInstUsesWith(I, Op0);
6943   
6944   if (isa<UndefValue>(Op0)) {            
6945     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6946       return ReplaceInstUsesWith(I, Op0);
6947     else                                    // undef << X -> 0, undef >>u X -> 0
6948       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6949   }
6950   if (isa<UndefValue>(Op1)) {
6951     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6952       return ReplaceInstUsesWith(I, Op0);          
6953     else                                     // X << undef, X >>u undef -> 0
6954       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6955   }
6956
6957   // Try to fold constant and into select arguments.
6958   if (isa<Constant>(Op0))
6959     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6960       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6961         return R;
6962
6963   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6964     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6965       return Res;
6966   return 0;
6967 }
6968
6969 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6970                                                BinaryOperator &I) {
6971   bool isLeftShift = I.getOpcode() == Instruction::Shl;
6972
6973   // See if we can simplify any instructions used by the instruction whose sole 
6974   // purpose is to compute bits we don't care about.
6975   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6976   if (SimplifyDemandedInstructionBits(I))
6977     return &I;
6978   
6979   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6980   // of a signed value.
6981   //
6982   if (Op1->uge(TypeBits)) {
6983     if (I.getOpcode() != Instruction::AShr)
6984       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6985     else {
6986       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6987       return &I;
6988     }
6989   }
6990   
6991   // ((X*C1) << C2) == (X * (C1 << C2))
6992   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6993     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6994       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6995         return BinaryOperator::CreateMul(BO->getOperand(0),
6996                                          ConstantExpr::getShl(BOOp, Op1));
6997   
6998   // Try to fold constant and into select arguments.
6999   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7000     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7001       return R;
7002   if (isa<PHINode>(Op0))
7003     if (Instruction *NV = FoldOpIntoPhi(I))
7004       return NV;
7005   
7006   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7007   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7008     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7009     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7010     // place.  Don't try to do this transformation in this case.  Also, we
7011     // require that the input operand is a shift-by-constant so that we have
7012     // confidence that the shifts will get folded together.  We could do this
7013     // xform in more cases, but it is unlikely to be profitable.
7014     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7015         isa<ConstantInt>(TrOp->getOperand(1))) {
7016       // Okay, we'll do this xform.  Make the shift of shift.
7017       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7018       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7019                                                 I.getName());
7020       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7021
7022       // For logical shifts, the truncation has the effect of making the high
7023       // part of the register be zeros.  Emulate this by inserting an AND to
7024       // clear the top bits as needed.  This 'and' will usually be zapped by
7025       // other xforms later if dead.
7026       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7027       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7028       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7029       
7030       // The mask we constructed says what the trunc would do if occurring
7031       // between the shifts.  We want to know the effect *after* the second
7032       // shift.  We know that it is a logical shift by a constant, so adjust the
7033       // mask as appropriate.
7034       if (I.getOpcode() == Instruction::Shl)
7035         MaskV <<= Op1->getZExtValue();
7036       else {
7037         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7038         MaskV = MaskV.lshr(Op1->getZExtValue());
7039       }
7040
7041       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7042                                                    TI->getName());
7043       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7044
7045       // Return the value truncated to the interesting size.
7046       return new TruncInst(And, I.getType());
7047     }
7048   }
7049   
7050   if (Op0->hasOneUse()) {
7051     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7052       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7053       Value *V1, *V2;
7054       ConstantInt *CC;
7055       switch (Op0BO->getOpcode()) {
7056         default: break;
7057         case Instruction::Add:
7058         case Instruction::And:
7059         case Instruction::Or:
7060         case Instruction::Xor: {
7061           // These operators commute.
7062           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7063           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7064               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7065             Instruction *YS = BinaryOperator::CreateShl(
7066                                             Op0BO->getOperand(0), Op1,
7067                                             Op0BO->getName());
7068             InsertNewInstBefore(YS, I); // (Y << C)
7069             Instruction *X = 
7070               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7071                                      Op0BO->getOperand(1)->getName());
7072             InsertNewInstBefore(X, I);  // (X + (Y << C))
7073             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7074             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7075                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7076           }
7077           
7078           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7079           Value *Op0BOOp1 = Op0BO->getOperand(1);
7080           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7081               match(Op0BOOp1, 
7082                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7083                           m_ConstantInt(CC))) &&
7084               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7085             Instruction *YS = BinaryOperator::CreateShl(
7086                                                      Op0BO->getOperand(0), Op1,
7087                                                      Op0BO->getName());
7088             InsertNewInstBefore(YS, I); // (Y << C)
7089             Instruction *XM =
7090               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7091                                         V1->getName()+".mask");
7092             InsertNewInstBefore(XM, I); // X & (CC << C)
7093             
7094             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7095           }
7096         }
7097           
7098         // FALL THROUGH.
7099         case Instruction::Sub: {
7100           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7101           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7102               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7103             Instruction *YS = BinaryOperator::CreateShl(
7104                                                      Op0BO->getOperand(1), Op1,
7105                                                      Op0BO->getName());
7106             InsertNewInstBefore(YS, I); // (Y << C)
7107             Instruction *X =
7108               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7109                                      Op0BO->getOperand(0)->getName());
7110             InsertNewInstBefore(X, I);  // (X + (Y << C))
7111             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7112             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7113                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7114           }
7115           
7116           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7117           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7118               match(Op0BO->getOperand(0),
7119                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7120                           m_ConstantInt(CC))) && V2 == Op1 &&
7121               cast<BinaryOperator>(Op0BO->getOperand(0))
7122                   ->getOperand(0)->hasOneUse()) {
7123             Instruction *YS = BinaryOperator::CreateShl(
7124                                                      Op0BO->getOperand(1), Op1,
7125                                                      Op0BO->getName());
7126             InsertNewInstBefore(YS, I); // (Y << C)
7127             Instruction *XM =
7128               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7129                                         V1->getName()+".mask");
7130             InsertNewInstBefore(XM, I); // X & (CC << C)
7131             
7132             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7133           }
7134           
7135           break;
7136         }
7137       }
7138       
7139       
7140       // If the operand is an bitwise operator with a constant RHS, and the
7141       // shift is the only use, we can pull it out of the shift.
7142       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7143         bool isValid = true;     // Valid only for And, Or, Xor
7144         bool highBitSet = false; // Transform if high bit of constant set?
7145         
7146         switch (Op0BO->getOpcode()) {
7147           default: isValid = false; break;   // Do not perform transform!
7148           case Instruction::Add:
7149             isValid = isLeftShift;
7150             break;
7151           case Instruction::Or:
7152           case Instruction::Xor:
7153             highBitSet = false;
7154             break;
7155           case Instruction::And:
7156             highBitSet = true;
7157             break;
7158         }
7159         
7160         // If this is a signed shift right, and the high bit is modified
7161         // by the logical operation, do not perform the transformation.
7162         // The highBitSet boolean indicates the value of the high bit of
7163         // the constant which would cause it to be modified for this
7164         // operation.
7165         //
7166         if (isValid && I.getOpcode() == Instruction::AShr)
7167           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7168         
7169         if (isValid) {
7170           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7171           
7172           Instruction *NewShift =
7173             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7174           InsertNewInstBefore(NewShift, I);
7175           NewShift->takeName(Op0BO);
7176           
7177           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7178                                         NewRHS);
7179         }
7180       }
7181     }
7182   }
7183   
7184   // Find out if this is a shift of a shift by a constant.
7185   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7186   if (ShiftOp && !ShiftOp->isShift())
7187     ShiftOp = 0;
7188   
7189   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7190     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7191     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7192     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7193     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7194     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7195     Value *X = ShiftOp->getOperand(0);
7196     
7197     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7198     if (AmtSum > TypeBits)
7199       AmtSum = TypeBits;
7200     
7201     const IntegerType *Ty = cast<IntegerType>(I.getType());
7202     
7203     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7204     if (I.getOpcode() == ShiftOp->getOpcode()) {
7205       return BinaryOperator::Create(I.getOpcode(), X,
7206                                     ConstantInt::get(Ty, AmtSum));
7207     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7208                I.getOpcode() == Instruction::AShr) {
7209       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7210       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7211     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7212                I.getOpcode() == Instruction::LShr) {
7213       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7214       Instruction *Shift =
7215         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7216       InsertNewInstBefore(Shift, I);
7217
7218       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7219       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7220     }
7221     
7222     // Okay, if we get here, one shift must be left, and the other shift must be
7223     // right.  See if the amounts are equal.
7224     if (ShiftAmt1 == ShiftAmt2) {
7225       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7226       if (I.getOpcode() == Instruction::Shl) {
7227         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7228         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7229       }
7230       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7231       if (I.getOpcode() == Instruction::LShr) {
7232         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7233         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7234       }
7235       // We can simplify ((X << C) >>s C) into a trunc + sext.
7236       // NOTE: we could do this for any C, but that would make 'unusual' integer
7237       // types.  For now, just stick to ones well-supported by the code
7238       // generators.
7239       const Type *SExtType = 0;
7240       switch (Ty->getBitWidth() - ShiftAmt1) {
7241       case 1  :
7242       case 8  :
7243       case 16 :
7244       case 32 :
7245       case 64 :
7246       case 128:
7247         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7248         break;
7249       default: break;
7250       }
7251       if (SExtType) {
7252         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7253         InsertNewInstBefore(NewTrunc, I);
7254         return new SExtInst(NewTrunc, Ty);
7255       }
7256       // Otherwise, we can't handle it yet.
7257     } else if (ShiftAmt1 < ShiftAmt2) {
7258       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7259       
7260       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7261       if (I.getOpcode() == Instruction::Shl) {
7262         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7263                ShiftOp->getOpcode() == Instruction::AShr);
7264         Instruction *Shift =
7265           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7266         InsertNewInstBefore(Shift, I);
7267         
7268         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7269         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7270       }
7271       
7272       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7273       if (I.getOpcode() == Instruction::LShr) {
7274         assert(ShiftOp->getOpcode() == Instruction::Shl);
7275         Instruction *Shift =
7276           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7277         InsertNewInstBefore(Shift, I);
7278         
7279         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7280         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7281       }
7282       
7283       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7284     } else {
7285       assert(ShiftAmt2 < ShiftAmt1);
7286       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7287
7288       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7289       if (I.getOpcode() == Instruction::Shl) {
7290         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7291                ShiftOp->getOpcode() == Instruction::AShr);
7292         Instruction *Shift =
7293           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7294                                  ConstantInt::get(Ty, ShiftDiff));
7295         InsertNewInstBefore(Shift, I);
7296         
7297         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7298         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7299       }
7300       
7301       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7302       if (I.getOpcode() == Instruction::LShr) {
7303         assert(ShiftOp->getOpcode() == Instruction::Shl);
7304         Instruction *Shift =
7305           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7306         InsertNewInstBefore(Shift, I);
7307         
7308         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7309         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7310       }
7311       
7312       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7313     }
7314   }
7315   return 0;
7316 }
7317
7318
7319 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7320 /// expression.  If so, decompose it, returning some value X, such that Val is
7321 /// X*Scale+Offset.
7322 ///
7323 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7324                                         int &Offset) {
7325   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7326   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7327     Offset = CI->getZExtValue();
7328     Scale  = 0;
7329     return ConstantInt::get(Type::Int32Ty, 0);
7330   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7331     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7332       if (I->getOpcode() == Instruction::Shl) {
7333         // This is a value scaled by '1 << the shift amt'.
7334         Scale = 1U << RHS->getZExtValue();
7335         Offset = 0;
7336         return I->getOperand(0);
7337       } else if (I->getOpcode() == Instruction::Mul) {
7338         // This value is scaled by 'RHS'.
7339         Scale = RHS->getZExtValue();
7340         Offset = 0;
7341         return I->getOperand(0);
7342       } else if (I->getOpcode() == Instruction::Add) {
7343         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7344         // where C1 is divisible by C2.
7345         unsigned SubScale;
7346         Value *SubVal = 
7347           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7348         Offset += RHS->getZExtValue();
7349         Scale = SubScale;
7350         return SubVal;
7351       }
7352     }
7353   }
7354
7355   // Otherwise, we can't look past this.
7356   Scale = 1;
7357   Offset = 0;
7358   return Val;
7359 }
7360
7361
7362 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7363 /// try to eliminate the cast by moving the type information into the alloc.
7364 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7365                                                    AllocationInst &AI) {
7366   const PointerType *PTy = cast<PointerType>(CI.getType());
7367   
7368   // Remove any uses of AI that are dead.
7369   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7370   
7371   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7372     Instruction *User = cast<Instruction>(*UI++);
7373     if (isInstructionTriviallyDead(User)) {
7374       while (UI != E && *UI == User)
7375         ++UI; // If this instruction uses AI more than once, don't break UI.
7376       
7377       ++NumDeadInst;
7378       DOUT << "IC: DCE: " << *User;
7379       EraseInstFromFunction(*User);
7380     }
7381   }
7382   
7383   // Get the type really allocated and the type casted to.
7384   const Type *AllocElTy = AI.getAllocatedType();
7385   const Type *CastElTy = PTy->getElementType();
7386   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7387
7388   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7389   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7390   if (CastElTyAlign < AllocElTyAlign) return 0;
7391
7392   // If the allocation has multiple uses, only promote it if we are strictly
7393   // increasing the alignment of the resultant allocation.  If we keep it the
7394   // same, we open the door to infinite loops of various kinds.
7395   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7396
7397   uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7398   uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
7399   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7400
7401   // See if we can satisfy the modulus by pulling a scale out of the array
7402   // size argument.
7403   unsigned ArraySizeScale;
7404   int ArrayOffset;
7405   Value *NumElements = // See if the array size is a decomposable linear expr.
7406     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7407  
7408   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7409   // do the xform.
7410   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7411       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7412
7413   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7414   Value *Amt = 0;
7415   if (Scale == 1) {
7416     Amt = NumElements;
7417   } else {
7418     // If the allocation size is constant, form a constant mul expression
7419     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7420     if (isa<ConstantInt>(NumElements))
7421       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7422     // otherwise multiply the amount and the number of elements
7423     else if (Scale != 1) {
7424       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7425       Amt = InsertNewInstBefore(Tmp, AI);
7426     }
7427   }
7428   
7429   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7430     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7431     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7432     Amt = InsertNewInstBefore(Tmp, AI);
7433   }
7434   
7435   AllocationInst *New;
7436   if (isa<MallocInst>(AI))
7437     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7438   else
7439     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7440   InsertNewInstBefore(New, AI);
7441   New->takeName(&AI);
7442   
7443   // If the allocation has multiple uses, insert a cast and change all things
7444   // that used it to use the new cast.  This will also hack on CI, but it will
7445   // die soon.
7446   if (!AI.hasOneUse()) {
7447     AddUsesToWorkList(AI);
7448     // New is the allocation instruction, pointer typed. AI is the original
7449     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7450     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7451     InsertNewInstBefore(NewCast, AI);
7452     AI.replaceAllUsesWith(NewCast);
7453   }
7454   return ReplaceInstUsesWith(CI, New);
7455 }
7456
7457 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7458 /// and return it as type Ty without inserting any new casts and without
7459 /// changing the computed value.  This is used by code that tries to decide
7460 /// whether promoting or shrinking integer operations to wider or smaller types
7461 /// will allow us to eliminate a truncate or extend.
7462 ///
7463 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7464 /// extension operation if Ty is larger.
7465 ///
7466 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7467 /// should return true if trunc(V) can be computed by computing V in the smaller
7468 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7469 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7470 /// efficiently truncated.
7471 ///
7472 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7473 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7474 /// the final result.
7475 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7476                                               unsigned CastOpc,
7477                                               int &NumCastsRemoved){
7478   // We can always evaluate constants in another type.
7479   if (isa<ConstantInt>(V))
7480     return true;
7481   
7482   Instruction *I = dyn_cast<Instruction>(V);
7483   if (!I) return false;
7484   
7485   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7486   
7487   // If this is an extension or truncate, we can often eliminate it.
7488   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7489     // If this is a cast from the destination type, we can trivially eliminate
7490     // it, and this will remove a cast overall.
7491     if (I->getOperand(0)->getType() == Ty) {
7492       // If the first operand is itself a cast, and is eliminable, do not count
7493       // this as an eliminable cast.  We would prefer to eliminate those two
7494       // casts first.
7495       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7496         ++NumCastsRemoved;
7497       return true;
7498     }
7499   }
7500
7501   // We can't extend or shrink something that has multiple uses: doing so would
7502   // require duplicating the instruction in general, which isn't profitable.
7503   if (!I->hasOneUse()) return false;
7504
7505   unsigned Opc = I->getOpcode();
7506   switch (Opc) {
7507   case Instruction::Add:
7508   case Instruction::Sub:
7509   case Instruction::Mul:
7510   case Instruction::And:
7511   case Instruction::Or:
7512   case Instruction::Xor:
7513     // These operators can all arbitrarily be extended or truncated.
7514     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7515                                       NumCastsRemoved) &&
7516            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7517                                       NumCastsRemoved);
7518
7519   case Instruction::Shl:
7520     // If we are truncating the result of this SHL, and if it's a shift of a
7521     // constant amount, we can always perform a SHL in a smaller type.
7522     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7523       uint32_t BitWidth = Ty->getBitWidth();
7524       if (BitWidth < OrigTy->getBitWidth() && 
7525           CI->getLimitedValue(BitWidth) < BitWidth)
7526         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7527                                           NumCastsRemoved);
7528     }
7529     break;
7530   case Instruction::LShr:
7531     // If this is a truncate of a logical shr, we can truncate it to a smaller
7532     // lshr iff we know that the bits we would otherwise be shifting in are
7533     // already zeros.
7534     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7535       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7536       uint32_t BitWidth = Ty->getBitWidth();
7537       if (BitWidth < OrigBitWidth &&
7538           MaskedValueIsZero(I->getOperand(0),
7539             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7540           CI->getLimitedValue(BitWidth) < BitWidth) {
7541         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7542                                           NumCastsRemoved);
7543       }
7544     }
7545     break;
7546   case Instruction::ZExt:
7547   case Instruction::SExt:
7548   case Instruction::Trunc:
7549     // If this is the same kind of case as our original (e.g. zext+zext), we
7550     // can safely replace it.  Note that replacing it does not reduce the number
7551     // of casts in the input.
7552     if (Opc == CastOpc)
7553       return true;
7554
7555     // sext (zext ty1), ty2 -> zext ty2
7556     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7557       return true;
7558     break;
7559   case Instruction::Select: {
7560     SelectInst *SI = cast<SelectInst>(I);
7561     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7562                                       NumCastsRemoved) &&
7563            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7564                                       NumCastsRemoved);
7565   }
7566   case Instruction::PHI: {
7567     // We can change a phi if we can change all operands.
7568     PHINode *PN = cast<PHINode>(I);
7569     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7570       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7571                                       NumCastsRemoved))
7572         return false;
7573     return true;
7574   }
7575   default:
7576     // TODO: Can handle more cases here.
7577     break;
7578   }
7579   
7580   return false;
7581 }
7582
7583 /// EvaluateInDifferentType - Given an expression that 
7584 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7585 /// evaluate the expression.
7586 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7587                                              bool isSigned) {
7588   if (Constant *C = dyn_cast<Constant>(V))
7589     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7590
7591   // Otherwise, it must be an instruction.
7592   Instruction *I = cast<Instruction>(V);
7593   Instruction *Res = 0;
7594   unsigned Opc = I->getOpcode();
7595   switch (Opc) {
7596   case Instruction::Add:
7597   case Instruction::Sub:
7598   case Instruction::Mul:
7599   case Instruction::And:
7600   case Instruction::Or:
7601   case Instruction::Xor:
7602   case Instruction::AShr:
7603   case Instruction::LShr:
7604   case Instruction::Shl: {
7605     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7606     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7607     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7608     break;
7609   }    
7610   case Instruction::Trunc:
7611   case Instruction::ZExt:
7612   case Instruction::SExt:
7613     // If the source type of the cast is the type we're trying for then we can
7614     // just return the source.  There's no need to insert it because it is not
7615     // new.
7616     if (I->getOperand(0)->getType() == Ty)
7617       return I->getOperand(0);
7618     
7619     // Otherwise, must be the same type of cast, so just reinsert a new one.
7620     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7621                            Ty);
7622     break;
7623   case Instruction::Select: {
7624     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7625     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7626     Res = SelectInst::Create(I->getOperand(0), True, False);
7627     break;
7628   }
7629   case Instruction::PHI: {
7630     PHINode *OPN = cast<PHINode>(I);
7631     PHINode *NPN = PHINode::Create(Ty);
7632     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7633       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7634       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7635     }
7636     Res = NPN;
7637     break;
7638   }
7639   default: 
7640     // TODO: Can handle more cases here.
7641     assert(0 && "Unreachable!");
7642     break;
7643   }
7644   
7645   Res->takeName(I);
7646   return InsertNewInstBefore(Res, *I);
7647 }
7648
7649 /// @brief Implement the transforms common to all CastInst visitors.
7650 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7651   Value *Src = CI.getOperand(0);
7652
7653   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7654   // eliminate it now.
7655   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7656     if (Instruction::CastOps opc = 
7657         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7658       // The first cast (CSrc) is eliminable so we need to fix up or replace
7659       // the second cast (CI). CSrc will then have a good chance of being dead.
7660       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7661     }
7662   }
7663
7664   // If we are casting a select then fold the cast into the select
7665   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7666     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7667       return NV;
7668
7669   // If we are casting a PHI then fold the cast into the PHI
7670   if (isa<PHINode>(Src))
7671     if (Instruction *NV = FoldOpIntoPhi(CI))
7672       return NV;
7673   
7674   return 0;
7675 }
7676
7677 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7678 /// or not there is a sequence of GEP indices into the type that will land us at
7679 /// the specified offset.  If so, fill them into NewIndices and return the
7680 /// resultant element type, otherwise return null.
7681 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
7682                                        SmallVectorImpl<Value*> &NewIndices,
7683                                        const TargetData *TD) {
7684   if (!Ty->isSized()) return 0;
7685   
7686   // Start with the index over the outer type.  Note that the type size
7687   // might be zero (even if the offset isn't zero) if the indexed type
7688   // is something like [0 x {int, int}]
7689   const Type *IntPtrTy = TD->getIntPtrType();
7690   int64_t FirstIdx = 0;
7691   if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
7692     FirstIdx = Offset/TySize;
7693     Offset -= FirstIdx*TySize;
7694     
7695     // Handle hosts where % returns negative instead of values [0..TySize).
7696     if (Offset < 0) {
7697       --FirstIdx;
7698       Offset += TySize;
7699       assert(Offset >= 0);
7700     }
7701     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7702   }
7703   
7704   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7705     
7706   // Index into the types.  If we fail, set OrigBase to null.
7707   while (Offset) {
7708     // Indexing into tail padding between struct/array elements.
7709     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
7710       return 0;
7711     
7712     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7713       const StructLayout *SL = TD->getStructLayout(STy);
7714       assert(Offset < (int64_t)SL->getSizeInBytes() &&
7715              "Offset must stay within the indexed type");
7716       
7717       unsigned Elt = SL->getElementContainingOffset(Offset);
7718       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7719       
7720       Offset -= SL->getElementOffset(Elt);
7721       Ty = STy->getElementType(Elt);
7722     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
7723       uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
7724       assert(EltSize && "Cannot index into a zero-sized array");
7725       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7726       Offset %= EltSize;
7727       Ty = AT->getElementType();
7728     } else {
7729       // Otherwise, we can't index into the middle of this atomic type, bail.
7730       return 0;
7731     }
7732   }
7733   
7734   return Ty;
7735 }
7736
7737 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7738 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7739   Value *Src = CI.getOperand(0);
7740   
7741   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7742     // If casting the result of a getelementptr instruction with no offset, turn
7743     // this into a cast of the original pointer!
7744     if (GEP->hasAllZeroIndices()) {
7745       // Changing the cast operand is usually not a good idea but it is safe
7746       // here because the pointer operand is being replaced with another 
7747       // pointer operand so the opcode doesn't need to change.
7748       AddToWorkList(GEP);
7749       CI.setOperand(0, GEP->getOperand(0));
7750       return &CI;
7751     }
7752     
7753     // If the GEP has a single use, and the base pointer is a bitcast, and the
7754     // GEP computes a constant offset, see if we can convert these three
7755     // instructions into fewer.  This typically happens with unions and other
7756     // non-type-safe code.
7757     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7758       if (GEP->hasAllConstantIndices()) {
7759         // We are guaranteed to get a constant from EmitGEPOffset.
7760         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7761         int64_t Offset = OffsetV->getSExtValue();
7762         
7763         // Get the base pointer input of the bitcast, and the type it points to.
7764         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7765         const Type *GEPIdxTy =
7766           cast<PointerType>(OrigBase->getType())->getElementType();
7767         SmallVector<Value*, 8> NewIndices;
7768         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7769           // If we were able to index down into an element, create the GEP
7770           // and bitcast the result.  This eliminates one bitcast, potentially
7771           // two.
7772           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7773                                                         NewIndices.begin(),
7774                                                         NewIndices.end(), "");
7775           InsertNewInstBefore(NGEP, CI);
7776           NGEP->takeName(GEP);
7777           
7778           if (isa<BitCastInst>(CI))
7779             return new BitCastInst(NGEP, CI.getType());
7780           assert(isa<PtrToIntInst>(CI));
7781           return new PtrToIntInst(NGEP, CI.getType());
7782         }
7783       }      
7784     }
7785   }
7786     
7787   return commonCastTransforms(CI);
7788 }
7789
7790
7791 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7792 /// integer types. This function implements the common transforms for all those
7793 /// cases.
7794 /// @brief Implement the transforms common to CastInst with integer operands
7795 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7796   if (Instruction *Result = commonCastTransforms(CI))
7797     return Result;
7798
7799   Value *Src = CI.getOperand(0);
7800   const Type *SrcTy = Src->getType();
7801   const Type *DestTy = CI.getType();
7802   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7803   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7804
7805   // See if we can simplify any instructions used by the LHS whose sole 
7806   // purpose is to compute bits we don't care about.
7807   if (SimplifyDemandedInstructionBits(CI))
7808     return &CI;
7809
7810   // If the source isn't an instruction or has more than one use then we
7811   // can't do anything more. 
7812   Instruction *SrcI = dyn_cast<Instruction>(Src);
7813   if (!SrcI || !Src->hasOneUse())
7814     return 0;
7815
7816   // Attempt to propagate the cast into the instruction for int->int casts.
7817   int NumCastsRemoved = 0;
7818   if (!isa<BitCastInst>(CI) &&
7819       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7820                                  CI.getOpcode(), NumCastsRemoved)) {
7821     // If this cast is a truncate, evaluting in a different type always
7822     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7823     // we need to do an AND to maintain the clear top-part of the computation,
7824     // so we require that the input have eliminated at least one cast.  If this
7825     // is a sign extension, we insert two new casts (to do the extension) so we
7826     // require that two casts have been eliminated.
7827     bool DoXForm = false;
7828     bool JustReplace = false;
7829     switch (CI.getOpcode()) {
7830     default:
7831       // All the others use floating point so we shouldn't actually 
7832       // get here because of the check above.
7833       assert(0 && "Unknown cast type");
7834     case Instruction::Trunc:
7835       DoXForm = true;
7836       break;
7837     case Instruction::ZExt: {
7838       DoXForm = NumCastsRemoved >= 1;
7839       if (!DoXForm) {
7840         // If it's unnecessary to issue an AND to clear the high bits, it's
7841         // always profitable to do this xform.
7842         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, 
7843                                            CI.getOpcode() == Instruction::SExt);
7844         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7845         if (MaskedValueIsZero(TryRes, Mask))
7846           return ReplaceInstUsesWith(CI, TryRes);
7847         else if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7848           if (TryI->use_empty())
7849             EraseInstFromFunction(*TryI);
7850       }
7851       break;
7852     }
7853     case Instruction::SExt: {
7854       DoXForm = NumCastsRemoved >= 2;
7855       if (!DoXForm && !isa<TruncInst>(SrcI)) {
7856         // If we do not have to emit the truncate + sext pair, then it's always
7857         // profitable to do this xform.
7858         //
7859         // It's not safe to eliminate the trunc + sext pair if one of the
7860         // eliminated cast is a truncate. e.g.
7861         // t2 = trunc i32 t1 to i16
7862         // t3 = sext i16 t2 to i32
7863         // !=
7864         // i32 t1
7865         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, 
7866                                            CI.getOpcode() == Instruction::SExt);
7867         unsigned NumSignBits = ComputeNumSignBits(TryRes);
7868         if (NumSignBits > (DestBitSize - SrcBitSize))
7869           return ReplaceInstUsesWith(CI, TryRes);
7870         else if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7871           if (TryI->use_empty())
7872             EraseInstFromFunction(*TryI);
7873       }
7874       break;
7875     }
7876     }
7877     
7878     if (DoXForm) {
7879       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7880                                            CI.getOpcode() == Instruction::SExt);
7881       if (JustReplace)
7882           // Just replace this cast with the result.
7883           return ReplaceInstUsesWith(CI, Res);
7884
7885       assert(Res->getType() == DestTy);
7886       switch (CI.getOpcode()) {
7887       default: assert(0 && "Unknown cast type!");
7888       case Instruction::Trunc:
7889       case Instruction::BitCast:
7890         // Just replace this cast with the result.
7891         return ReplaceInstUsesWith(CI, Res);
7892       case Instruction::ZExt: {
7893         assert(SrcBitSize < DestBitSize && "Not a zext?");
7894
7895         // If the high bits are already zero, just replace this cast with the
7896         // result.
7897         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7898         if (MaskedValueIsZero(Res, Mask))
7899           return ReplaceInstUsesWith(CI, Res);
7900
7901         // We need to emit an AND to clear the high bits.
7902         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7903                                                             SrcBitSize));
7904         return BinaryOperator::CreateAnd(Res, C);
7905       }
7906       case Instruction::SExt: {
7907         // If the high bits are already filled with sign bit, just replace this
7908         // cast with the result.
7909         unsigned NumSignBits = ComputeNumSignBits(Res);
7910         if (NumSignBits > (DestBitSize - SrcBitSize))
7911           return ReplaceInstUsesWith(CI, Res);
7912
7913         // We need to emit a cast to truncate, then a cast to sext.
7914         return CastInst::Create(Instruction::SExt,
7915             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7916                              CI), DestTy);
7917       }
7918       }
7919     }
7920   }
7921   
7922   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7923   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7924
7925   switch (SrcI->getOpcode()) {
7926   case Instruction::Add:
7927   case Instruction::Mul:
7928   case Instruction::And:
7929   case Instruction::Or:
7930   case Instruction::Xor:
7931     // If we are discarding information, rewrite.
7932     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7933       // Don't insert two casts if they cannot be eliminated.  We allow 
7934       // two casts to be inserted if the sizes are the same.  This could 
7935       // only be converting signedness, which is a noop.
7936       if (DestBitSize == SrcBitSize || 
7937           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7938           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7939         Instruction::CastOps opcode = CI.getOpcode();
7940         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7941         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
7942         return BinaryOperator::Create(
7943             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7944       }
7945     }
7946
7947     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7948     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7949         SrcI->getOpcode() == Instruction::Xor &&
7950         Op1 == ConstantInt::getTrue() &&
7951         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7952       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
7953       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7954     }
7955     break;
7956   case Instruction::SDiv:
7957   case Instruction::UDiv:
7958   case Instruction::SRem:
7959   case Instruction::URem:
7960     // If we are just changing the sign, rewrite.
7961     if (DestBitSize == SrcBitSize) {
7962       // Don't insert two casts if they cannot be eliminated.  We allow 
7963       // two casts to be inserted if the sizes are the same.  This could 
7964       // only be converting signedness, which is a noop.
7965       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7966           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7967         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
7968                                        Op0, DestTy, *SrcI);
7969         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
7970                                        Op1, DestTy, *SrcI);
7971         return BinaryOperator::Create(
7972           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7973       }
7974     }
7975     break;
7976
7977   case Instruction::Shl:
7978     // Allow changing the sign of the source operand.  Do not allow 
7979     // changing the size of the shift, UNLESS the shift amount is a 
7980     // constant.  We must not change variable sized shifts to a smaller 
7981     // size, because it is undefined to shift more bits out than exist 
7982     // in the value.
7983     if (DestBitSize == SrcBitSize ||
7984         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7985       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7986           Instruction::BitCast : Instruction::Trunc);
7987       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7988       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
7989       return BinaryOperator::CreateShl(Op0c, Op1c);
7990     }
7991     break;
7992   case Instruction::AShr:
7993     // If this is a signed shr, and if all bits shifted in are about to be
7994     // truncated off, turn it into an unsigned shr to allow greater
7995     // simplifications.
7996     if (DestBitSize < SrcBitSize &&
7997         isa<ConstantInt>(Op1)) {
7998       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7999       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8000         // Insert the new logical shift right.
8001         return BinaryOperator::CreateLShr(Op0, Op1);
8002       }
8003     }
8004     break;
8005   }
8006   return 0;
8007 }
8008
8009 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8010   if (Instruction *Result = commonIntCastTransforms(CI))
8011     return Result;
8012   
8013   Value *Src = CI.getOperand(0);
8014   const Type *Ty = CI.getType();
8015   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8016   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
8017   
8018   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
8019     switch (SrcI->getOpcode()) {
8020     default: break;
8021     case Instruction::LShr:
8022       // We can shrink lshr to something smaller if we know the bits shifted in
8023       // are already zeros.
8024       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
8025         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8026         
8027         // Get a mask for the bits shifting in.
8028         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8029         Value* SrcIOp0 = SrcI->getOperand(0);
8030         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
8031           if (ShAmt >= DestBitWidth)        // All zeros.
8032             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8033
8034           // Okay, we can shrink this.  Truncate the input, then return a new
8035           // shift.
8036           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
8037           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
8038                                        Ty, CI);
8039           return BinaryOperator::CreateLShr(V1, V2);
8040         }
8041       } else {     // This is a variable shr.
8042         
8043         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
8044         // more LLVM instructions, but allows '1 << Y' to be hoisted if
8045         // loop-invariant and CSE'd.
8046         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
8047           Value *One = ConstantInt::get(SrcI->getType(), 1);
8048
8049           Value *V = InsertNewInstBefore(
8050               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
8051                                      "tmp"), CI);
8052           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
8053                                                             SrcI->getOperand(0),
8054                                                             "tmp"), CI);
8055           Value *Zero = Constant::getNullValue(V->getType());
8056           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
8057         }
8058       }
8059       break;
8060     }
8061   }
8062   
8063   return 0;
8064 }
8065
8066 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8067 /// in order to eliminate the icmp.
8068 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8069                                              bool DoXform) {
8070   // If we are just checking for a icmp eq of a single bit and zext'ing it
8071   // to an integer, then shift the bit to the appropriate place and then
8072   // cast to integer to avoid the comparison.
8073   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8074     const APInt &Op1CV = Op1C->getValue();
8075       
8076     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8077     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8078     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8079         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8080       if (!DoXform) return ICI;
8081
8082       Value *In = ICI->getOperand(0);
8083       Value *Sh = ConstantInt::get(In->getType(),
8084                                    In->getType()->getPrimitiveSizeInBits()-1);
8085       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8086                                                         In->getName()+".lobit"),
8087                                CI);
8088       if (In->getType() != CI.getType())
8089         In = CastInst::CreateIntegerCast(In, CI.getType(),
8090                                          false/*ZExt*/, "tmp", &CI);
8091
8092       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8093         Constant *One = ConstantInt::get(In->getType(), 1);
8094         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8095                                                          In->getName()+".not"),
8096                                  CI);
8097       }
8098
8099       return ReplaceInstUsesWith(CI, In);
8100     }
8101       
8102       
8103       
8104     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8105     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8106     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8107     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8108     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8109     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8110     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8111     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8112     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8113         // This only works for EQ and NE
8114         ICI->isEquality()) {
8115       // If Op1C some other power of two, convert:
8116       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8117       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8118       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8119       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8120         
8121       APInt KnownZeroMask(~KnownZero);
8122       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8123         if (!DoXform) return ICI;
8124
8125         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8126         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8127           // (X&4) == 2 --> false
8128           // (X&4) != 2 --> true
8129           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8130           Res = ConstantExpr::getZExt(Res, CI.getType());
8131           return ReplaceInstUsesWith(CI, Res);
8132         }
8133           
8134         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8135         Value *In = ICI->getOperand(0);
8136         if (ShiftAmt) {
8137           // Perform a logical shr by shiftamt.
8138           // Insert the shift to put the result in the low bit.
8139           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8140                                   ConstantInt::get(In->getType(), ShiftAmt),
8141                                                    In->getName()+".lobit"), CI);
8142         }
8143           
8144         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8145           Constant *One = ConstantInt::get(In->getType(), 1);
8146           In = BinaryOperator::CreateXor(In, One, "tmp");
8147           InsertNewInstBefore(cast<Instruction>(In), CI);
8148         }
8149           
8150         if (CI.getType() == In->getType())
8151           return ReplaceInstUsesWith(CI, In);
8152         else
8153           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8154       }
8155     }
8156   }
8157
8158   return 0;
8159 }
8160
8161 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8162   // If one of the common conversion will work ..
8163   if (Instruction *Result = commonIntCastTransforms(CI))
8164     return Result;
8165
8166   Value *Src = CI.getOperand(0);
8167
8168   // If this is a cast of a cast
8169   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8170     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8171     // types and if the sizes are just right we can convert this into a logical
8172     // 'and' which will be much cheaper than the pair of casts.
8173     if (isa<TruncInst>(CSrc)) {
8174       // Get the sizes of the types involved
8175       Value *A = CSrc->getOperand(0);
8176       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8177       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8178       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8179       // If we're actually extending zero bits and the trunc is a no-op
8180       if (MidSize < DstSize && SrcSize == DstSize) {
8181         // Replace both of the casts with an And of the type mask.
8182         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8183         Constant *AndConst = ConstantInt::get(AndValue);
8184         Instruction *And = 
8185           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8186         // Unfortunately, if the type changed, we need to cast it back.
8187         if (And->getType() != CI.getType()) {
8188           And->setName(CSrc->getName()+".mask");
8189           InsertNewInstBefore(And, CI);
8190           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8191         }
8192         return And;
8193       }
8194     }
8195   }
8196
8197   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8198     return transformZExtICmp(ICI, CI);
8199
8200   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8201   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8202     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8203     // of the (zext icmp) will be transformed.
8204     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8205     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8206     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8207         (transformZExtICmp(LHS, CI, false) ||
8208          transformZExtICmp(RHS, CI, false))) {
8209       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8210       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8211       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8212     }
8213   }
8214
8215   return 0;
8216 }
8217
8218 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8219   if (Instruction *I = commonIntCastTransforms(CI))
8220     return I;
8221   
8222   Value *Src = CI.getOperand(0);
8223   
8224   // Canonicalize sign-extend from i1 to a select.
8225   if (Src->getType() == Type::Int1Ty)
8226     return SelectInst::Create(Src,
8227                               ConstantInt::getAllOnesValue(CI.getType()),
8228                               Constant::getNullValue(CI.getType()));
8229
8230   // See if the value being truncated is already sign extended.  If so, just
8231   // eliminate the trunc/sext pair.
8232   if (getOpcode(Src) == Instruction::Trunc) {
8233     Value *Op = cast<User>(Src)->getOperand(0);
8234     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8235     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8236     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8237     unsigned NumSignBits = ComputeNumSignBits(Op);
8238
8239     if (OpBits == DestBits) {
8240       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8241       // bits, it is already ready.
8242       if (NumSignBits > DestBits-MidBits)
8243         return ReplaceInstUsesWith(CI, Op);
8244     } else if (OpBits < DestBits) {
8245       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8246       // bits, just sext from i32.
8247       if (NumSignBits > OpBits-MidBits)
8248         return new SExtInst(Op, CI.getType(), "tmp");
8249     } else {
8250       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8251       // bits, just truncate to i32.
8252       if (NumSignBits > OpBits-MidBits)
8253         return new TruncInst(Op, CI.getType(), "tmp");
8254     }
8255   }
8256
8257   // If the input is a shl/ashr pair of a same constant, then this is a sign
8258   // extension from a smaller value.  If we could trust arbitrary bitwidth
8259   // integers, we could turn this into a truncate to the smaller bit and then
8260   // use a sext for the whole extension.  Since we don't, look deeper and check
8261   // for a truncate.  If the source and dest are the same type, eliminate the
8262   // trunc and extend and just do shifts.  For example, turn:
8263   //   %a = trunc i32 %i to i8
8264   //   %b = shl i8 %a, 6
8265   //   %c = ashr i8 %b, 6
8266   //   %d = sext i8 %c to i32
8267   // into:
8268   //   %a = shl i32 %i, 30
8269   //   %d = ashr i32 %a, 30
8270   Value *A = 0;
8271   ConstantInt *BA = 0, *CA = 0;
8272   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8273                         m_ConstantInt(CA))) &&
8274       BA == CA && isa<TruncInst>(A)) {
8275     Value *I = cast<TruncInst>(A)->getOperand(0);
8276     if (I->getType() == CI.getType()) {
8277       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8278       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8279       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8280       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8281       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8282                                                         CI.getName()), CI);
8283       return BinaryOperator::CreateAShr(I, ShAmtV);
8284     }
8285   }
8286   
8287   return 0;
8288 }
8289
8290 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8291 /// in the specified FP type without changing its value.
8292 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8293   bool losesInfo;
8294   APFloat F = CFP->getValueAPF();
8295   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8296   if (!losesInfo)
8297     return ConstantFP::get(F);
8298   return 0;
8299 }
8300
8301 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8302 /// through it until we get the source value.
8303 static Value *LookThroughFPExtensions(Value *V) {
8304   if (Instruction *I = dyn_cast<Instruction>(V))
8305     if (I->getOpcode() == Instruction::FPExt)
8306       return LookThroughFPExtensions(I->getOperand(0));
8307   
8308   // If this value is a constant, return the constant in the smallest FP type
8309   // that can accurately represent it.  This allows us to turn
8310   // (float)((double)X+2.0) into x+2.0f.
8311   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8312     if (CFP->getType() == Type::PPC_FP128Ty)
8313       return V;  // No constant folding of this.
8314     // See if the value can be truncated to float and then reextended.
8315     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8316       return V;
8317     if (CFP->getType() == Type::DoubleTy)
8318       return V;  // Won't shrink.
8319     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8320       return V;
8321     // Don't try to shrink to various long double types.
8322   }
8323   
8324   return V;
8325 }
8326
8327 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8328   if (Instruction *I = commonCastTransforms(CI))
8329     return I;
8330   
8331   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8332   // smaller than the destination type, we can eliminate the truncate by doing
8333   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8334   // many builtins (sqrt, etc).
8335   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8336   if (OpI && OpI->hasOneUse()) {
8337     switch (OpI->getOpcode()) {
8338     default: break;
8339     case Instruction::Add:
8340     case Instruction::Sub:
8341     case Instruction::Mul:
8342     case Instruction::FDiv:
8343     case Instruction::FRem:
8344       const Type *SrcTy = OpI->getType();
8345       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8346       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8347       if (LHSTrunc->getType() != SrcTy && 
8348           RHSTrunc->getType() != SrcTy) {
8349         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8350         // If the source types were both smaller than the destination type of
8351         // the cast, do this xform.
8352         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8353             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8354           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8355                                       CI.getType(), CI);
8356           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8357                                       CI.getType(), CI);
8358           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8359         }
8360       }
8361       break;  
8362     }
8363   }
8364   return 0;
8365 }
8366
8367 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8368   return commonCastTransforms(CI);
8369 }
8370
8371 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8372   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8373   if (OpI == 0)
8374     return commonCastTransforms(FI);
8375
8376   // fptoui(uitofp(X)) --> X
8377   // fptoui(sitofp(X)) --> X
8378   // This is safe if the intermediate type has enough bits in its mantissa to
8379   // accurately represent all values of X.  For example, do not do this with
8380   // i64->float->i64.  This is also safe for sitofp case, because any negative
8381   // 'X' value would cause an undefined result for the fptoui. 
8382   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8383       OpI->getOperand(0)->getType() == FI.getType() &&
8384       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8385                     OpI->getType()->getFPMantissaWidth())
8386     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8387
8388   return commonCastTransforms(FI);
8389 }
8390
8391 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8392   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8393   if (OpI == 0)
8394     return commonCastTransforms(FI);
8395   
8396   // fptosi(sitofp(X)) --> X
8397   // fptosi(uitofp(X)) --> X
8398   // This is safe if the intermediate type has enough bits in its mantissa to
8399   // accurately represent all values of X.  For example, do not do this with
8400   // i64->float->i64.  This is also safe for sitofp case, because any negative
8401   // 'X' value would cause an undefined result for the fptoui. 
8402   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8403       OpI->getOperand(0)->getType() == FI.getType() &&
8404       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8405                     OpI->getType()->getFPMantissaWidth())
8406     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8407   
8408   return commonCastTransforms(FI);
8409 }
8410
8411 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8412   return commonCastTransforms(CI);
8413 }
8414
8415 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8416   return commonCastTransforms(CI);
8417 }
8418
8419 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8420   return commonPointerCastTransforms(CI);
8421 }
8422
8423 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8424   if (Instruction *I = commonCastTransforms(CI))
8425     return I;
8426   
8427   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8428   if (!DestPointee->isSized()) return 0;
8429
8430   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8431   ConstantInt *Cst;
8432   Value *X;
8433   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8434                                     m_ConstantInt(Cst)))) {
8435     // If the source and destination operands have the same type, see if this
8436     // is a single-index GEP.
8437     if (X->getType() == CI.getType()) {
8438       // Get the size of the pointee type.
8439       uint64_t Size = TD->getTypePaddedSize(DestPointee);
8440
8441       // Convert the constant to intptr type.
8442       APInt Offset = Cst->getValue();
8443       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8444
8445       // If Offset is evenly divisible by Size, we can do this xform.
8446       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8447         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8448         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8449       }
8450     }
8451     // TODO: Could handle other cases, e.g. where add is indexing into field of
8452     // struct etc.
8453   } else if (CI.getOperand(0)->hasOneUse() &&
8454              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8455     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8456     // "inttoptr+GEP" instead of "add+intptr".
8457     
8458     // Get the size of the pointee type.
8459     uint64_t Size = TD->getTypePaddedSize(DestPointee);
8460     
8461     // Convert the constant to intptr type.
8462     APInt Offset = Cst->getValue();
8463     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8464     
8465     // If Offset is evenly divisible by Size, we can do this xform.
8466     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8467       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8468       
8469       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8470                                                             "tmp"), CI);
8471       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8472     }
8473   }
8474   return 0;
8475 }
8476
8477 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8478   // If the operands are integer typed then apply the integer transforms,
8479   // otherwise just apply the common ones.
8480   Value *Src = CI.getOperand(0);
8481   const Type *SrcTy = Src->getType();
8482   const Type *DestTy = CI.getType();
8483
8484   if (SrcTy->isInteger() && DestTy->isInteger()) {
8485     if (Instruction *Result = commonIntCastTransforms(CI))
8486       return Result;
8487   } else if (isa<PointerType>(SrcTy)) {
8488     if (Instruction *I = commonPointerCastTransforms(CI))
8489       return I;
8490   } else {
8491     if (Instruction *Result = commonCastTransforms(CI))
8492       return Result;
8493   }
8494
8495
8496   // Get rid of casts from one type to the same type. These are useless and can
8497   // be replaced by the operand.
8498   if (DestTy == Src->getType())
8499     return ReplaceInstUsesWith(CI, Src);
8500
8501   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8502     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8503     const Type *DstElTy = DstPTy->getElementType();
8504     const Type *SrcElTy = SrcPTy->getElementType();
8505     
8506     // If the address spaces don't match, don't eliminate the bitcast, which is
8507     // required for changing types.
8508     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8509       return 0;
8510     
8511     // If we are casting a malloc or alloca to a pointer to a type of the same
8512     // size, rewrite the allocation instruction to allocate the "right" type.
8513     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8514       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8515         return V;
8516     
8517     // If the source and destination are pointers, and this cast is equivalent
8518     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8519     // This can enhance SROA and other transforms that want type-safe pointers.
8520     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8521     unsigned NumZeros = 0;
8522     while (SrcElTy != DstElTy && 
8523            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8524            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8525       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8526       ++NumZeros;
8527     }
8528
8529     // If we found a path from the src to dest, create the getelementptr now.
8530     if (SrcElTy == DstElTy) {
8531       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8532       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8533                                        ((Instruction*) NULL));
8534     }
8535   }
8536
8537   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8538     if (SVI->hasOneUse()) {
8539       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8540       // a bitconvert to a vector with the same # elts.
8541       if (isa<VectorType>(DestTy) && 
8542           cast<VectorType>(DestTy)->getNumElements() ==
8543                 SVI->getType()->getNumElements() &&
8544           SVI->getType()->getNumElements() ==
8545             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8546         CastInst *Tmp;
8547         // If either of the operands is a cast from CI.getType(), then
8548         // evaluating the shuffle in the casted destination's type will allow
8549         // us to eliminate at least one cast.
8550         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8551              Tmp->getOperand(0)->getType() == DestTy) ||
8552             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8553              Tmp->getOperand(0)->getType() == DestTy)) {
8554           Value *LHS = InsertCastBefore(Instruction::BitCast,
8555                                         SVI->getOperand(0), DestTy, CI);
8556           Value *RHS = InsertCastBefore(Instruction::BitCast,
8557                                         SVI->getOperand(1), DestTy, CI);
8558           // Return a new shuffle vector.  Use the same element ID's, as we
8559           // know the vector types match #elts.
8560           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8561         }
8562       }
8563     }
8564   }
8565   return 0;
8566 }
8567
8568 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8569 ///   %C = or %A, %B
8570 ///   %D = select %cond, %C, %A
8571 /// into:
8572 ///   %C = select %cond, %B, 0
8573 ///   %D = or %A, %C
8574 ///
8575 /// Assuming that the specified instruction is an operand to the select, return
8576 /// a bitmask indicating which operands of this instruction are foldable if they
8577 /// equal the other incoming value of the select.
8578 ///
8579 static unsigned GetSelectFoldableOperands(Instruction *I) {
8580   switch (I->getOpcode()) {
8581   case Instruction::Add:
8582   case Instruction::Mul:
8583   case Instruction::And:
8584   case Instruction::Or:
8585   case Instruction::Xor:
8586     return 3;              // Can fold through either operand.
8587   case Instruction::Sub:   // Can only fold on the amount subtracted.
8588   case Instruction::Shl:   // Can only fold on the shift amount.
8589   case Instruction::LShr:
8590   case Instruction::AShr:
8591     return 1;
8592   default:
8593     return 0;              // Cannot fold
8594   }
8595 }
8596
8597 /// GetSelectFoldableConstant - For the same transformation as the previous
8598 /// function, return the identity constant that goes into the select.
8599 static Constant *GetSelectFoldableConstant(Instruction *I) {
8600   switch (I->getOpcode()) {
8601   default: assert(0 && "This cannot happen!"); abort();
8602   case Instruction::Add:
8603   case Instruction::Sub:
8604   case Instruction::Or:
8605   case Instruction::Xor:
8606   case Instruction::Shl:
8607   case Instruction::LShr:
8608   case Instruction::AShr:
8609     return Constant::getNullValue(I->getType());
8610   case Instruction::And:
8611     return Constant::getAllOnesValue(I->getType());
8612   case Instruction::Mul:
8613     return ConstantInt::get(I->getType(), 1);
8614   }
8615 }
8616
8617 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8618 /// have the same opcode and only one use each.  Try to simplify this.
8619 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8620                                           Instruction *FI) {
8621   if (TI->getNumOperands() == 1) {
8622     // If this is a non-volatile load or a cast from the same type,
8623     // merge.
8624     if (TI->isCast()) {
8625       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8626         return 0;
8627     } else {
8628       return 0;  // unknown unary op.
8629     }
8630
8631     // Fold this by inserting a select from the input values.
8632     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8633                                            FI->getOperand(0), SI.getName()+".v");
8634     InsertNewInstBefore(NewSI, SI);
8635     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8636                             TI->getType());
8637   }
8638
8639   // Only handle binary operators here.
8640   if (!isa<BinaryOperator>(TI))
8641     return 0;
8642
8643   // Figure out if the operations have any operands in common.
8644   Value *MatchOp, *OtherOpT, *OtherOpF;
8645   bool MatchIsOpZero;
8646   if (TI->getOperand(0) == FI->getOperand(0)) {
8647     MatchOp  = TI->getOperand(0);
8648     OtherOpT = TI->getOperand(1);
8649     OtherOpF = FI->getOperand(1);
8650     MatchIsOpZero = true;
8651   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8652     MatchOp  = TI->getOperand(1);
8653     OtherOpT = TI->getOperand(0);
8654     OtherOpF = FI->getOperand(0);
8655     MatchIsOpZero = false;
8656   } else if (!TI->isCommutative()) {
8657     return 0;
8658   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8659     MatchOp  = TI->getOperand(0);
8660     OtherOpT = TI->getOperand(1);
8661     OtherOpF = FI->getOperand(0);
8662     MatchIsOpZero = true;
8663   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8664     MatchOp  = TI->getOperand(1);
8665     OtherOpT = TI->getOperand(0);
8666     OtherOpF = FI->getOperand(1);
8667     MatchIsOpZero = true;
8668   } else {
8669     return 0;
8670   }
8671
8672   // If we reach here, they do have operations in common.
8673   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8674                                          OtherOpF, SI.getName()+".v");
8675   InsertNewInstBefore(NewSI, SI);
8676
8677   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8678     if (MatchIsOpZero)
8679       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8680     else
8681       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8682   }
8683   assert(0 && "Shouldn't get here");
8684   return 0;
8685 }
8686
8687 /// visitSelectInstWithICmp - Visit a SelectInst that has an
8688 /// ICmpInst as its first operand.
8689 ///
8690 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8691                                                    ICmpInst *ICI) {
8692   bool Changed = false;
8693   ICmpInst::Predicate Pred = ICI->getPredicate();
8694   Value *CmpLHS = ICI->getOperand(0);
8695   Value *CmpRHS = ICI->getOperand(1);
8696   Value *TrueVal = SI.getTrueValue();
8697   Value *FalseVal = SI.getFalseValue();
8698
8699   // Check cases where the comparison is with a constant that
8700   // can be adjusted to fit the min/max idiom. We may edit ICI in
8701   // place here, so make sure the select is the only user.
8702   if (ICI->hasOneUse())
8703     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
8704       switch (Pred) {
8705       default: break;
8706       case ICmpInst::ICMP_ULT:
8707       case ICmpInst::ICMP_SLT: {
8708         // X < MIN ? T : F  -->  F
8709         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8710           return ReplaceInstUsesWith(SI, FalseVal);
8711         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
8712         Constant *AdjustedRHS = SubOne(CI);
8713         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8714             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8715           Pred = ICmpInst::getSwappedPredicate(Pred);
8716           CmpRHS = AdjustedRHS;
8717           std::swap(FalseVal, TrueVal);
8718           ICI->setPredicate(Pred);
8719           ICI->setOperand(1, CmpRHS);
8720           SI.setOperand(1, TrueVal);
8721           SI.setOperand(2, FalseVal);
8722           Changed = true;
8723         }
8724         break;
8725       }
8726       case ICmpInst::ICMP_UGT:
8727       case ICmpInst::ICMP_SGT: {
8728         // X > MAX ? T : F  -->  F
8729         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8730           return ReplaceInstUsesWith(SI, FalseVal);
8731         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
8732         Constant *AdjustedRHS = AddOne(CI);
8733         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8734             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8735           Pred = ICmpInst::getSwappedPredicate(Pred);
8736           CmpRHS = AdjustedRHS;
8737           std::swap(FalseVal, TrueVal);
8738           ICI->setPredicate(Pred);
8739           ICI->setOperand(1, CmpRHS);
8740           SI.setOperand(1, TrueVal);
8741           SI.setOperand(2, FalseVal);
8742           Changed = true;
8743         }
8744         break;
8745       }
8746       }
8747
8748       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
8749       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
8750       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
8751       if (match(TrueVal, m_ConstantInt<-1>()) &&
8752           match(FalseVal, m_ConstantInt<0>()))
8753         Pred = ICI->getPredicate();
8754       else if (match(TrueVal, m_ConstantInt<0>()) &&
8755                match(FalseVal, m_ConstantInt<-1>()))
8756         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8757       
8758       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8759         // If we are just checking for a icmp eq of a single bit and zext'ing it
8760         // to an integer, then shift the bit to the appropriate place and then
8761         // cast to integer to avoid the comparison.
8762         const APInt &Op1CV = CI->getValue();
8763     
8764         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
8765         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
8766         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8767             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
8768           Value *In = ICI->getOperand(0);
8769           Value *Sh = ConstantInt::get(In->getType(),
8770                                        In->getType()->getPrimitiveSizeInBits()-1);
8771           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8772                                                           In->getName()+".lobit"),
8773                                    *ICI);
8774           if (In->getType() != SI.getType())
8775             In = CastInst::CreateIntegerCast(In, SI.getType(),
8776                                              true/*SExt*/, "tmp", ICI);
8777     
8778           if (Pred == ICmpInst::ICMP_SGT)
8779             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8780                                        In->getName()+".not"), *ICI);
8781     
8782           return ReplaceInstUsesWith(SI, In);
8783         }
8784       }
8785     }
8786
8787   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8788     // Transform (X == Y) ? X : Y  -> Y
8789     if (Pred == ICmpInst::ICMP_EQ)
8790       return ReplaceInstUsesWith(SI, FalseVal);
8791     // Transform (X != Y) ? X : Y  -> X
8792     if (Pred == ICmpInst::ICMP_NE)
8793       return ReplaceInstUsesWith(SI, TrueVal);
8794     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8795
8796   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8797     // Transform (X == Y) ? Y : X  -> X
8798     if (Pred == ICmpInst::ICMP_EQ)
8799       return ReplaceInstUsesWith(SI, FalseVal);
8800     // Transform (X != Y) ? Y : X  -> Y
8801     if (Pred == ICmpInst::ICMP_NE)
8802       return ReplaceInstUsesWith(SI, TrueVal);
8803     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8804   }
8805
8806   /// NOTE: if we wanted to, this is where to detect integer ABS
8807
8808   return Changed ? &SI : 0;
8809 }
8810
8811 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8812   Value *CondVal = SI.getCondition();
8813   Value *TrueVal = SI.getTrueValue();
8814   Value *FalseVal = SI.getFalseValue();
8815
8816   // select true, X, Y  -> X
8817   // select false, X, Y -> Y
8818   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8819     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8820
8821   // select C, X, X -> X
8822   if (TrueVal == FalseVal)
8823     return ReplaceInstUsesWith(SI, TrueVal);
8824
8825   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8826     return ReplaceInstUsesWith(SI, FalseVal);
8827   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8828     return ReplaceInstUsesWith(SI, TrueVal);
8829   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8830     if (isa<Constant>(TrueVal))
8831       return ReplaceInstUsesWith(SI, TrueVal);
8832     else
8833       return ReplaceInstUsesWith(SI, FalseVal);
8834   }
8835
8836   if (SI.getType() == Type::Int1Ty) {
8837     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8838       if (C->getZExtValue()) {
8839         // Change: A = select B, true, C --> A = or B, C
8840         return BinaryOperator::CreateOr(CondVal, FalseVal);
8841       } else {
8842         // Change: A = select B, false, C --> A = and !B, C
8843         Value *NotCond =
8844           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8845                                              "not."+CondVal->getName()), SI);
8846         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8847       }
8848     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8849       if (C->getZExtValue() == false) {
8850         // Change: A = select B, C, false --> A = and B, C
8851         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8852       } else {
8853         // Change: A = select B, C, true --> A = or !B, C
8854         Value *NotCond =
8855           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8856                                              "not."+CondVal->getName()), SI);
8857         return BinaryOperator::CreateOr(NotCond, TrueVal);
8858       }
8859     }
8860     
8861     // select a, b, a  -> a&b
8862     // select a, a, b  -> a|b
8863     if (CondVal == TrueVal)
8864       return BinaryOperator::CreateOr(CondVal, FalseVal);
8865     else if (CondVal == FalseVal)
8866       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8867   }
8868
8869   // Selecting between two integer constants?
8870   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8871     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8872       // select C, 1, 0 -> zext C to int
8873       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8874         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8875       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8876         // select C, 0, 1 -> zext !C to int
8877         Value *NotCond =
8878           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8879                                                "not."+CondVal->getName()), SI);
8880         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8881       }
8882
8883       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8884
8885         // (x <s 0) ? -1 : 0 -> ashr x, 31
8886         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8887           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8888             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8889               // The comparison constant and the result are not neccessarily the
8890               // same width. Make an all-ones value by inserting a AShr.
8891               Value *X = IC->getOperand(0);
8892               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8893               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8894               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8895                                                         ShAmt, "ones");
8896               InsertNewInstBefore(SRA, SI);
8897
8898               // Then cast to the appropriate width.
8899               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
8900             }
8901           }
8902
8903
8904         // If one of the constants is zero (we know they can't both be) and we
8905         // have an icmp instruction with zero, and we have an 'and' with the
8906         // non-constant value, eliminate this whole mess.  This corresponds to
8907         // cases like this: ((X & 27) ? 27 : 0)
8908         if (TrueValC->isZero() || FalseValC->isZero())
8909           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8910               cast<Constant>(IC->getOperand(1))->isNullValue())
8911             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8912               if (ICA->getOpcode() == Instruction::And &&
8913                   isa<ConstantInt>(ICA->getOperand(1)) &&
8914                   (ICA->getOperand(1) == TrueValC ||
8915                    ICA->getOperand(1) == FalseValC) &&
8916                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8917                 // Okay, now we know that everything is set up, we just don't
8918                 // know whether we have a icmp_ne or icmp_eq and whether the 
8919                 // true or false val is the zero.
8920                 bool ShouldNotVal = !TrueValC->isZero();
8921                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8922                 Value *V = ICA;
8923                 if (ShouldNotVal)
8924                   V = InsertNewInstBefore(BinaryOperator::Create(
8925                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8926                 return ReplaceInstUsesWith(SI, V);
8927               }
8928       }
8929     }
8930
8931   // See if we are selecting two values based on a comparison of the two values.
8932   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8933     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8934       // Transform (X == Y) ? X : Y  -> Y
8935       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8936         // This is not safe in general for floating point:  
8937         // consider X== -0, Y== +0.
8938         // It becomes safe if either operand is a nonzero constant.
8939         ConstantFP *CFPt, *CFPf;
8940         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8941               !CFPt->getValueAPF().isZero()) ||
8942             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8943              !CFPf->getValueAPF().isZero()))
8944         return ReplaceInstUsesWith(SI, FalseVal);
8945       }
8946       // Transform (X != Y) ? X : Y  -> X
8947       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8948         return ReplaceInstUsesWith(SI, TrueVal);
8949       // NOTE: if we wanted to, this is where to detect MIN/MAX
8950
8951     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8952       // Transform (X == Y) ? Y : X  -> X
8953       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8954         // This is not safe in general for floating point:  
8955         // consider X== -0, Y== +0.
8956         // It becomes safe if either operand is a nonzero constant.
8957         ConstantFP *CFPt, *CFPf;
8958         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8959               !CFPt->getValueAPF().isZero()) ||
8960             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8961              !CFPf->getValueAPF().isZero()))
8962           return ReplaceInstUsesWith(SI, FalseVal);
8963       }
8964       // Transform (X != Y) ? Y : X  -> Y
8965       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8966         return ReplaceInstUsesWith(SI, TrueVal);
8967       // NOTE: if we wanted to, this is where to detect MIN/MAX
8968     }
8969     // NOTE: if we wanted to, this is where to detect ABS
8970   }
8971
8972   // See if we are selecting two values based on a comparison of the two values.
8973   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
8974     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
8975       return Result;
8976
8977   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8978     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8979       if (TI->hasOneUse() && FI->hasOneUse()) {
8980         Instruction *AddOp = 0, *SubOp = 0;
8981
8982         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8983         if (TI->getOpcode() == FI->getOpcode())
8984           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8985             return IV;
8986
8987         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8988         // even legal for FP.
8989         if (TI->getOpcode() == Instruction::Sub &&
8990             FI->getOpcode() == Instruction::Add) {
8991           AddOp = FI; SubOp = TI;
8992         } else if (FI->getOpcode() == Instruction::Sub &&
8993                    TI->getOpcode() == Instruction::Add) {
8994           AddOp = TI; SubOp = FI;
8995         }
8996
8997         if (AddOp) {
8998           Value *OtherAddOp = 0;
8999           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9000             OtherAddOp = AddOp->getOperand(1);
9001           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9002             OtherAddOp = AddOp->getOperand(0);
9003           }
9004
9005           if (OtherAddOp) {
9006             // So at this point we know we have (Y -> OtherAddOp):
9007             //        select C, (add X, Y), (sub X, Z)
9008             Value *NegVal;  // Compute -Z
9009             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9010               NegVal = ConstantExpr::getNeg(C);
9011             } else {
9012               NegVal = InsertNewInstBefore(
9013                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9014             }
9015
9016             Value *NewTrueOp = OtherAddOp;
9017             Value *NewFalseOp = NegVal;
9018             if (AddOp != TI)
9019               std::swap(NewTrueOp, NewFalseOp);
9020             Instruction *NewSel =
9021               SelectInst::Create(CondVal, NewTrueOp,
9022                                  NewFalseOp, SI.getName() + ".p");
9023
9024             NewSel = InsertNewInstBefore(NewSel, SI);
9025             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9026           }
9027         }
9028       }
9029
9030   // See if we can fold the select into one of our operands.
9031   if (SI.getType()->isInteger()) {
9032     // See the comment above GetSelectFoldableOperands for a description of the
9033     // transformation we are doing here.
9034     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9035       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9036           !isa<Constant>(FalseVal))
9037         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9038           unsigned OpToFold = 0;
9039           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9040             OpToFold = 1;
9041           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9042             OpToFold = 2;
9043           }
9044
9045           if (OpToFold) {
9046             Constant *C = GetSelectFoldableConstant(TVI);
9047             Instruction *NewSel =
9048               SelectInst::Create(SI.getCondition(),
9049                                  TVI->getOperand(2-OpToFold), C);
9050             InsertNewInstBefore(NewSel, SI);
9051             NewSel->takeName(TVI);
9052             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9053               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9054             else {
9055               assert(0 && "Unknown instruction!!");
9056             }
9057           }
9058         }
9059
9060     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9061       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9062           !isa<Constant>(TrueVal))
9063         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9064           unsigned OpToFold = 0;
9065           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9066             OpToFold = 1;
9067           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9068             OpToFold = 2;
9069           }
9070
9071           if (OpToFold) {
9072             Constant *C = GetSelectFoldableConstant(FVI);
9073             Instruction *NewSel =
9074               SelectInst::Create(SI.getCondition(), C,
9075                                  FVI->getOperand(2-OpToFold));
9076             InsertNewInstBefore(NewSel, SI);
9077             NewSel->takeName(FVI);
9078             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9079               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9080             else
9081               assert(0 && "Unknown instruction!!");
9082           }
9083         }
9084   }
9085
9086   if (BinaryOperator::isNot(CondVal)) {
9087     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9088     SI.setOperand(1, FalseVal);
9089     SI.setOperand(2, TrueVal);
9090     return &SI;
9091   }
9092
9093   return 0;
9094 }
9095
9096 /// EnforceKnownAlignment - If the specified pointer points to an object that
9097 /// we control, modify the object's alignment to PrefAlign. This isn't
9098 /// often possible though. If alignment is important, a more reliable approach
9099 /// is to simply align all global variables and allocation instructions to
9100 /// their preferred alignment from the beginning.
9101 ///
9102 static unsigned EnforceKnownAlignment(Value *V,
9103                                       unsigned Align, unsigned PrefAlign) {
9104
9105   User *U = dyn_cast<User>(V);
9106   if (!U) return Align;
9107
9108   switch (getOpcode(U)) {
9109   default: break;
9110   case Instruction::BitCast:
9111     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9112   case Instruction::GetElementPtr: {
9113     // If all indexes are zero, it is just the alignment of the base pointer.
9114     bool AllZeroOperands = true;
9115     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9116       if (!isa<Constant>(*i) ||
9117           !cast<Constant>(*i)->isNullValue()) {
9118         AllZeroOperands = false;
9119         break;
9120       }
9121
9122     if (AllZeroOperands) {
9123       // Treat this like a bitcast.
9124       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9125     }
9126     break;
9127   }
9128   }
9129
9130   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9131     // If there is a large requested alignment and we can, bump up the alignment
9132     // of the global.
9133     if (!GV->isDeclaration()) {
9134       GV->setAlignment(PrefAlign);
9135       Align = PrefAlign;
9136     }
9137   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9138     // If there is a requested alignment and if this is an alloca, round up.  We
9139     // don't do this for malloc, because some systems can't respect the request.
9140     if (isa<AllocaInst>(AI)) {
9141       AI->setAlignment(PrefAlign);
9142       Align = PrefAlign;
9143     }
9144   }
9145
9146   return Align;
9147 }
9148
9149 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9150 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9151 /// and it is more than the alignment of the ultimate object, see if we can
9152 /// increase the alignment of the ultimate object, making this check succeed.
9153 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9154                                                   unsigned PrefAlign) {
9155   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9156                       sizeof(PrefAlign) * CHAR_BIT;
9157   APInt Mask = APInt::getAllOnesValue(BitWidth);
9158   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9159   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9160   unsigned TrailZ = KnownZero.countTrailingOnes();
9161   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9162
9163   if (PrefAlign > Align)
9164     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9165   
9166     // We don't need to make any adjustment.
9167   return Align;
9168 }
9169
9170 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9171   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9172   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9173   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9174   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9175
9176   if (CopyAlign < MinAlign) {
9177     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9178     return MI;
9179   }
9180   
9181   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9182   // load/store.
9183   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9184   if (MemOpLength == 0) return 0;
9185   
9186   // Source and destination pointer types are always "i8*" for intrinsic.  See
9187   // if the size is something we can handle with a single primitive load/store.
9188   // A single load+store correctly handles overlapping memory in the memmove
9189   // case.
9190   unsigned Size = MemOpLength->getZExtValue();
9191   if (Size == 0) return MI;  // Delete this mem transfer.
9192   
9193   if (Size > 8 || (Size&(Size-1)))
9194     return 0;  // If not 1/2/4/8 bytes, exit.
9195   
9196   // Use an integer load+store unless we can find something better.
9197   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9198   
9199   // Memcpy forces the use of i8* for the source and destination.  That means
9200   // that if you're using memcpy to move one double around, you'll get a cast
9201   // from double* to i8*.  We'd much rather use a double load+store rather than
9202   // an i64 load+store, here because this improves the odds that the source or
9203   // dest address will be promotable.  See if we can find a better type than the
9204   // integer datatype.
9205   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9206     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9207     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9208       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9209       // down through these levels if so.
9210       while (!SrcETy->isSingleValueType()) {
9211         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9212           if (STy->getNumElements() == 1)
9213             SrcETy = STy->getElementType(0);
9214           else
9215             break;
9216         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9217           if (ATy->getNumElements() == 1)
9218             SrcETy = ATy->getElementType();
9219           else
9220             break;
9221         } else
9222           break;
9223       }
9224       
9225       if (SrcETy->isSingleValueType())
9226         NewPtrTy = PointerType::getUnqual(SrcETy);
9227     }
9228   }
9229   
9230   
9231   // If the memcpy/memmove provides better alignment info than we can
9232   // infer, use it.
9233   SrcAlign = std::max(SrcAlign, CopyAlign);
9234   DstAlign = std::max(DstAlign, CopyAlign);
9235   
9236   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9237   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9238   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9239   InsertNewInstBefore(L, *MI);
9240   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9241
9242   // Set the size of the copy to 0, it will be deleted on the next iteration.
9243   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9244   return MI;
9245 }
9246
9247 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9248   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9249   if (MI->getAlignment()->getZExtValue() < Alignment) {
9250     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9251     return MI;
9252   }
9253   
9254   // Extract the length and alignment and fill if they are constant.
9255   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9256   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9257   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9258     return 0;
9259   uint64_t Len = LenC->getZExtValue();
9260   Alignment = MI->getAlignment()->getZExtValue();
9261   
9262   // If the length is zero, this is a no-op
9263   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9264   
9265   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9266   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9267     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9268     
9269     Value *Dest = MI->getDest();
9270     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9271
9272     // Alignment 0 is identity for alignment 1 for memset, but not store.
9273     if (Alignment == 0) Alignment = 1;
9274     
9275     // Extract the fill value and store.
9276     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9277     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9278                                       Alignment), *MI);
9279     
9280     // Set the size of the copy to 0, it will be deleted on the next iteration.
9281     MI->setLength(Constant::getNullValue(LenC->getType()));
9282     return MI;
9283   }
9284
9285   return 0;
9286 }
9287
9288
9289 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9290 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9291 /// the heavy lifting.
9292 ///
9293 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9294   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9295   if (!II) return visitCallSite(&CI);
9296   
9297   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9298   // visitCallSite.
9299   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9300     bool Changed = false;
9301
9302     // memmove/cpy/set of zero bytes is a noop.
9303     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9304       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9305
9306       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9307         if (CI->getZExtValue() == 1) {
9308           // Replace the instruction with just byte operations.  We would
9309           // transform other cases to loads/stores, but we don't know if
9310           // alignment is sufficient.
9311         }
9312     }
9313
9314     // If we have a memmove and the source operation is a constant global,
9315     // then the source and dest pointers can't alias, so we can change this
9316     // into a call to memcpy.
9317     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9318       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9319         if (GVSrc->isConstant()) {
9320           Module *M = CI.getParent()->getParent()->getParent();
9321           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9322           const Type *Tys[1];
9323           Tys[0] = CI.getOperand(3)->getType();
9324           CI.setOperand(0, 
9325                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9326           Changed = true;
9327         }
9328
9329       // memmove(x,x,size) -> noop.
9330       if (MMI->getSource() == MMI->getDest())
9331         return EraseInstFromFunction(CI);
9332     }
9333
9334     // If we can determine a pointer alignment that is bigger than currently
9335     // set, update the alignment.
9336     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9337       if (Instruction *I = SimplifyMemTransfer(MI))
9338         return I;
9339     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9340       if (Instruction *I = SimplifyMemSet(MSI))
9341         return I;
9342     }
9343           
9344     if (Changed) return II;
9345   }
9346   
9347   switch (II->getIntrinsicID()) {
9348   default: break;
9349   case Intrinsic::bswap:
9350     // bswap(bswap(x)) -> x
9351     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9352       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9353         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9354     break;
9355   case Intrinsic::ppc_altivec_lvx:
9356   case Intrinsic::ppc_altivec_lvxl:
9357   case Intrinsic::x86_sse_loadu_ps:
9358   case Intrinsic::x86_sse2_loadu_pd:
9359   case Intrinsic::x86_sse2_loadu_dq:
9360     // Turn PPC lvx     -> load if the pointer is known aligned.
9361     // Turn X86 loadups -> load if the pointer is known aligned.
9362     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9363       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9364                                        PointerType::getUnqual(II->getType()),
9365                                        CI);
9366       return new LoadInst(Ptr);
9367     }
9368     break;
9369   case Intrinsic::ppc_altivec_stvx:
9370   case Intrinsic::ppc_altivec_stvxl:
9371     // Turn stvx -> store if the pointer is known aligned.
9372     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9373       const Type *OpPtrTy = 
9374         PointerType::getUnqual(II->getOperand(1)->getType());
9375       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9376       return new StoreInst(II->getOperand(1), Ptr);
9377     }
9378     break;
9379   case Intrinsic::x86_sse_storeu_ps:
9380   case Intrinsic::x86_sse2_storeu_pd:
9381   case Intrinsic::x86_sse2_storeu_dq:
9382     // Turn X86 storeu -> store if the pointer is known aligned.
9383     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9384       const Type *OpPtrTy = 
9385         PointerType::getUnqual(II->getOperand(2)->getType());
9386       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9387       return new StoreInst(II->getOperand(2), Ptr);
9388     }
9389     break;
9390     
9391   case Intrinsic::x86_sse_cvttss2si: {
9392     // These intrinsics only demands the 0th element of its input vector.  If
9393     // we can simplify the input based on that, do so now.
9394     uint64_t UndefElts;
9395     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
9396                                               UndefElts)) {
9397       II->setOperand(1, V);
9398       return II;
9399     }
9400     break;
9401   }
9402     
9403   case Intrinsic::ppc_altivec_vperm:
9404     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9405     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9406       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9407       
9408       // Check that all of the elements are integer constants or undefs.
9409       bool AllEltsOk = true;
9410       for (unsigned i = 0; i != 16; ++i) {
9411         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9412             !isa<UndefValue>(Mask->getOperand(i))) {
9413           AllEltsOk = false;
9414           break;
9415         }
9416       }
9417       
9418       if (AllEltsOk) {
9419         // Cast the input vectors to byte vectors.
9420         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9421         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9422         Value *Result = UndefValue::get(Op0->getType());
9423         
9424         // Only extract each element once.
9425         Value *ExtractedElts[32];
9426         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9427         
9428         for (unsigned i = 0; i != 16; ++i) {
9429           if (isa<UndefValue>(Mask->getOperand(i)))
9430             continue;
9431           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9432           Idx &= 31;  // Match the hardware behavior.
9433           
9434           if (ExtractedElts[Idx] == 0) {
9435             Instruction *Elt = 
9436               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9437             InsertNewInstBefore(Elt, CI);
9438             ExtractedElts[Idx] = Elt;
9439           }
9440         
9441           // Insert this value into the result vector.
9442           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9443                                              i, "tmp");
9444           InsertNewInstBefore(cast<Instruction>(Result), CI);
9445         }
9446         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9447       }
9448     }
9449     break;
9450
9451   case Intrinsic::stackrestore: {
9452     // If the save is right next to the restore, remove the restore.  This can
9453     // happen when variable allocas are DCE'd.
9454     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9455       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9456         BasicBlock::iterator BI = SS;
9457         if (&*++BI == II)
9458           return EraseInstFromFunction(CI);
9459       }
9460     }
9461     
9462     // Scan down this block to see if there is another stack restore in the
9463     // same block without an intervening call/alloca.
9464     BasicBlock::iterator BI = II;
9465     TerminatorInst *TI = II->getParent()->getTerminator();
9466     bool CannotRemove = false;
9467     for (++BI; &*BI != TI; ++BI) {
9468       if (isa<AllocaInst>(BI)) {
9469         CannotRemove = true;
9470         break;
9471       }
9472       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9473         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9474           // If there is a stackrestore below this one, remove this one.
9475           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9476             return EraseInstFromFunction(CI);
9477           // Otherwise, ignore the intrinsic.
9478         } else {
9479           // If we found a non-intrinsic call, we can't remove the stack
9480           // restore.
9481           CannotRemove = true;
9482           break;
9483         }
9484       }
9485     }
9486     
9487     // If the stack restore is in a return/unwind block and if there are no
9488     // allocas or calls between the restore and the return, nuke the restore.
9489     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9490       return EraseInstFromFunction(CI);
9491     break;
9492   }
9493   }
9494
9495   return visitCallSite(II);
9496 }
9497
9498 // InvokeInst simplification
9499 //
9500 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9501   return visitCallSite(&II);
9502 }
9503
9504 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9505 /// passed through the varargs area, we can eliminate the use of the cast.
9506 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9507                                          const CastInst * const CI,
9508                                          const TargetData * const TD,
9509                                          const int ix) {
9510   if (!CI->isLosslessCast())
9511     return false;
9512
9513   // The size of ByVal arguments is derived from the type, so we
9514   // can't change to a type with a different size.  If the size were
9515   // passed explicitly we could avoid this check.
9516   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9517     return true;
9518
9519   const Type* SrcTy = 
9520             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9521   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9522   if (!SrcTy->isSized() || !DstTy->isSized())
9523     return false;
9524   if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
9525     return false;
9526   return true;
9527 }
9528
9529 // visitCallSite - Improvements for call and invoke instructions.
9530 //
9531 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9532   bool Changed = false;
9533
9534   // If the callee is a constexpr cast of a function, attempt to move the cast
9535   // to the arguments of the call/invoke.
9536   if (transformConstExprCastCall(CS)) return 0;
9537
9538   Value *Callee = CS.getCalledValue();
9539
9540   if (Function *CalleeF = dyn_cast<Function>(Callee))
9541     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9542       Instruction *OldCall = CS.getInstruction();
9543       // If the call and callee calling conventions don't match, this call must
9544       // be unreachable, as the call is undefined.
9545       new StoreInst(ConstantInt::getTrue(),
9546                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9547                                     OldCall);
9548       if (!OldCall->use_empty())
9549         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9550       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9551         return EraseInstFromFunction(*OldCall);
9552       return 0;
9553     }
9554
9555   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9556     // This instruction is not reachable, just remove it.  We insert a store to
9557     // undef so that we know that this code is not reachable, despite the fact
9558     // that we can't modify the CFG here.
9559     new StoreInst(ConstantInt::getTrue(),
9560                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9561                   CS.getInstruction());
9562
9563     if (!CS.getInstruction()->use_empty())
9564       CS.getInstruction()->
9565         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9566
9567     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9568       // Don't break the CFG, insert a dummy cond branch.
9569       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9570                          ConstantInt::getTrue(), II);
9571     }
9572     return EraseInstFromFunction(*CS.getInstruction());
9573   }
9574
9575   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9576     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9577       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9578         return transformCallThroughTrampoline(CS);
9579
9580   const PointerType *PTy = cast<PointerType>(Callee->getType());
9581   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9582   if (FTy->isVarArg()) {
9583     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9584     // See if we can optimize any arguments passed through the varargs area of
9585     // the call.
9586     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9587            E = CS.arg_end(); I != E; ++I, ++ix) {
9588       CastInst *CI = dyn_cast<CastInst>(*I);
9589       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9590         *I = CI->getOperand(0);
9591         Changed = true;
9592       }
9593     }
9594   }
9595
9596   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9597     // Inline asm calls cannot throw - mark them 'nounwind'.
9598     CS.setDoesNotThrow();
9599     Changed = true;
9600   }
9601
9602   return Changed ? CS.getInstruction() : 0;
9603 }
9604
9605 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9606 // attempt to move the cast to the arguments of the call/invoke.
9607 //
9608 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9609   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9610   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9611   if (CE->getOpcode() != Instruction::BitCast || 
9612       !isa<Function>(CE->getOperand(0)))
9613     return false;
9614   Function *Callee = cast<Function>(CE->getOperand(0));
9615   Instruction *Caller = CS.getInstruction();
9616   const AttrListPtr &CallerPAL = CS.getAttributes();
9617
9618   // Okay, this is a cast from a function to a different type.  Unless doing so
9619   // would cause a type conversion of one of our arguments, change this call to
9620   // be a direct call with arguments casted to the appropriate types.
9621   //
9622   const FunctionType *FT = Callee->getFunctionType();
9623   const Type *OldRetTy = Caller->getType();
9624   const Type *NewRetTy = FT->getReturnType();
9625
9626   if (isa<StructType>(NewRetTy))
9627     return false; // TODO: Handle multiple return values.
9628
9629   // Check to see if we are changing the return type...
9630   if (OldRetTy != NewRetTy) {
9631     if (Callee->isDeclaration() &&
9632         // Conversion is ok if changing from one pointer type to another or from
9633         // a pointer to an integer of the same size.
9634         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9635           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9636       return false;   // Cannot transform this return value.
9637
9638     if (!Caller->use_empty() &&
9639         // void -> non-void is handled specially
9640         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9641       return false;   // Cannot transform this return value.
9642
9643     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9644       Attributes RAttrs = CallerPAL.getRetAttributes();
9645       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9646         return false;   // Attribute not compatible with transformed value.
9647     }
9648
9649     // If the callsite is an invoke instruction, and the return value is used by
9650     // a PHI node in a successor, we cannot change the return type of the call
9651     // because there is no place to put the cast instruction (without breaking
9652     // the critical edge).  Bail out in this case.
9653     if (!Caller->use_empty())
9654       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9655         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9656              UI != E; ++UI)
9657           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9658             if (PN->getParent() == II->getNormalDest() ||
9659                 PN->getParent() == II->getUnwindDest())
9660               return false;
9661   }
9662
9663   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9664   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9665
9666   CallSite::arg_iterator AI = CS.arg_begin();
9667   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9668     const Type *ParamTy = FT->getParamType(i);
9669     const Type *ActTy = (*AI)->getType();
9670
9671     if (!CastInst::isCastable(ActTy, ParamTy))
9672       return false;   // Cannot transform this parameter value.
9673
9674     if (CallerPAL.getParamAttributes(i + 1) 
9675         & Attribute::typeIncompatible(ParamTy))
9676       return false;   // Attribute not compatible with transformed value.
9677
9678     // Converting from one pointer type to another or between a pointer and an
9679     // integer of the same size is safe even if we do not have a body.
9680     bool isConvertible = ActTy == ParamTy ||
9681       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9682        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9683     if (Callee->isDeclaration() && !isConvertible) return false;
9684   }
9685
9686   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9687       Callee->isDeclaration())
9688     return false;   // Do not delete arguments unless we have a function body.
9689
9690   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9691       !CallerPAL.isEmpty())
9692     // In this case we have more arguments than the new function type, but we
9693     // won't be dropping them.  Check that these extra arguments have attributes
9694     // that are compatible with being a vararg call argument.
9695     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9696       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9697         break;
9698       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9699       if (PAttrs & Attribute::VarArgsIncompatible)
9700         return false;
9701     }
9702
9703   // Okay, we decided that this is a safe thing to do: go ahead and start
9704   // inserting cast instructions as necessary...
9705   std::vector<Value*> Args;
9706   Args.reserve(NumActualArgs);
9707   SmallVector<AttributeWithIndex, 8> attrVec;
9708   attrVec.reserve(NumCommonArgs);
9709
9710   // Get any return attributes.
9711   Attributes RAttrs = CallerPAL.getRetAttributes();
9712
9713   // If the return value is not being used, the type may not be compatible
9714   // with the existing attributes.  Wipe out any problematic attributes.
9715   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
9716
9717   // Add the new return attributes.
9718   if (RAttrs)
9719     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
9720
9721   AI = CS.arg_begin();
9722   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9723     const Type *ParamTy = FT->getParamType(i);
9724     if ((*AI)->getType() == ParamTy) {
9725       Args.push_back(*AI);
9726     } else {
9727       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9728           false, ParamTy, false);
9729       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9730       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9731     }
9732
9733     // Add any parameter attributes.
9734     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9735       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9736   }
9737
9738   // If the function takes more arguments than the call was taking, add them
9739   // now...
9740   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9741     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9742
9743   // If we are removing arguments to the function, emit an obnoxious warning...
9744   if (FT->getNumParams() < NumActualArgs) {
9745     if (!FT->isVarArg()) {
9746       cerr << "WARNING: While resolving call to function '"
9747            << Callee->getName() << "' arguments were dropped!\n";
9748     } else {
9749       // Add all of the arguments in their promoted form to the arg list...
9750       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9751         const Type *PTy = getPromotedType((*AI)->getType());
9752         if (PTy != (*AI)->getType()) {
9753           // Must promote to pass through va_arg area!
9754           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9755                                                                 PTy, false);
9756           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9757           InsertNewInstBefore(Cast, *Caller);
9758           Args.push_back(Cast);
9759         } else {
9760           Args.push_back(*AI);
9761         }
9762
9763         // Add any parameter attributes.
9764         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9765           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9766       }
9767     }
9768   }
9769
9770   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
9771     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9772
9773   if (NewRetTy == Type::VoidTy)
9774     Caller->setName("");   // Void type should not have a name.
9775
9776   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
9777
9778   Instruction *NC;
9779   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9780     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9781                             Args.begin(), Args.end(),
9782                             Caller->getName(), Caller);
9783     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9784     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
9785   } else {
9786     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9787                           Caller->getName(), Caller);
9788     CallInst *CI = cast<CallInst>(Caller);
9789     if (CI->isTailCall())
9790       cast<CallInst>(NC)->setTailCall();
9791     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9792     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
9793   }
9794
9795   // Insert a cast of the return type as necessary.
9796   Value *NV = NC;
9797   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9798     if (NV->getType() != Type::VoidTy) {
9799       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9800                                                             OldRetTy, false);
9801       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9802
9803       // If this is an invoke instruction, we should insert it after the first
9804       // non-phi, instruction in the normal successor block.
9805       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9806         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9807         InsertNewInstBefore(NC, *I);
9808       } else {
9809         // Otherwise, it's a call, just insert cast right after the call instr
9810         InsertNewInstBefore(NC, *Caller);
9811       }
9812       AddUsersToWorkList(*Caller);
9813     } else {
9814       NV = UndefValue::get(Caller->getType());
9815     }
9816   }
9817
9818   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9819     Caller->replaceAllUsesWith(NV);
9820   Caller->eraseFromParent();
9821   RemoveFromWorkList(Caller);
9822   return true;
9823 }
9824
9825 // transformCallThroughTrampoline - Turn a call to a function created by the
9826 // init_trampoline intrinsic into a direct call to the underlying function.
9827 //
9828 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9829   Value *Callee = CS.getCalledValue();
9830   const PointerType *PTy = cast<PointerType>(Callee->getType());
9831   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9832   const AttrListPtr &Attrs = CS.getAttributes();
9833
9834   // If the call already has the 'nest' attribute somewhere then give up -
9835   // otherwise 'nest' would occur twice after splicing in the chain.
9836   if (Attrs.hasAttrSomewhere(Attribute::Nest))
9837     return 0;
9838
9839   IntrinsicInst *Tramp =
9840     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9841
9842   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9843   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9844   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9845
9846   const AttrListPtr &NestAttrs = NestF->getAttributes();
9847   if (!NestAttrs.isEmpty()) {
9848     unsigned NestIdx = 1;
9849     const Type *NestTy = 0;
9850     Attributes NestAttr = Attribute::None;
9851
9852     // Look for a parameter marked with the 'nest' attribute.
9853     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9854          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9855       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
9856         // Record the parameter type and any other attributes.
9857         NestTy = *I;
9858         NestAttr = NestAttrs.getParamAttributes(NestIdx);
9859         break;
9860       }
9861
9862     if (NestTy) {
9863       Instruction *Caller = CS.getInstruction();
9864       std::vector<Value*> NewArgs;
9865       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9866
9867       SmallVector<AttributeWithIndex, 8> NewAttrs;
9868       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9869
9870       // Insert the nest argument into the call argument list, which may
9871       // mean appending it.  Likewise for attributes.
9872
9873       // Add any result attributes.
9874       if (Attributes Attr = Attrs.getRetAttributes())
9875         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
9876
9877       {
9878         unsigned Idx = 1;
9879         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9880         do {
9881           if (Idx == NestIdx) {
9882             // Add the chain argument and attributes.
9883             Value *NestVal = Tramp->getOperand(3);
9884             if (NestVal->getType() != NestTy)
9885               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9886             NewArgs.push_back(NestVal);
9887             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
9888           }
9889
9890           if (I == E)
9891             break;
9892
9893           // Add the original argument and attributes.
9894           NewArgs.push_back(*I);
9895           if (Attributes Attr = Attrs.getParamAttributes(Idx))
9896             NewAttrs.push_back
9897               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9898
9899           ++Idx, ++I;
9900         } while (1);
9901       }
9902
9903       // Add any function attributes.
9904       if (Attributes Attr = Attrs.getFnAttributes())
9905         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9906
9907       // The trampoline may have been bitcast to a bogus type (FTy).
9908       // Handle this by synthesizing a new function type, equal to FTy
9909       // with the chain parameter inserted.
9910
9911       std::vector<const Type*> NewTypes;
9912       NewTypes.reserve(FTy->getNumParams()+1);
9913
9914       // Insert the chain's type into the list of parameter types, which may
9915       // mean appending it.
9916       {
9917         unsigned Idx = 1;
9918         FunctionType::param_iterator I = FTy->param_begin(),
9919           E = FTy->param_end();
9920
9921         do {
9922           if (Idx == NestIdx)
9923             // Add the chain's type.
9924             NewTypes.push_back(NestTy);
9925
9926           if (I == E)
9927             break;
9928
9929           // Add the original type.
9930           NewTypes.push_back(*I);
9931
9932           ++Idx, ++I;
9933         } while (1);
9934       }
9935
9936       // Replace the trampoline call with a direct call.  Let the generic
9937       // code sort out any function type mismatches.
9938       FunctionType *NewFTy =
9939         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9940       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9941         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9942       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
9943
9944       Instruction *NewCaller;
9945       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9946         NewCaller = InvokeInst::Create(NewCallee,
9947                                        II->getNormalDest(), II->getUnwindDest(),
9948                                        NewArgs.begin(), NewArgs.end(),
9949                                        Caller->getName(), Caller);
9950         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9951         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
9952       } else {
9953         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9954                                      Caller->getName(), Caller);
9955         if (cast<CallInst>(Caller)->isTailCall())
9956           cast<CallInst>(NewCaller)->setTailCall();
9957         cast<CallInst>(NewCaller)->
9958           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9959         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
9960       }
9961       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9962         Caller->replaceAllUsesWith(NewCaller);
9963       Caller->eraseFromParent();
9964       RemoveFromWorkList(Caller);
9965       return 0;
9966     }
9967   }
9968
9969   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9970   // parameter, there is no need to adjust the argument list.  Let the generic
9971   // code sort out any function type mismatches.
9972   Constant *NewCallee =
9973     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9974   CS.setCalledFunction(NewCallee);
9975   return CS.getInstruction();
9976 }
9977
9978 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9979 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9980 /// and a single binop.
9981 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9982   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9983   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
9984   unsigned Opc = FirstInst->getOpcode();
9985   Value *LHSVal = FirstInst->getOperand(0);
9986   Value *RHSVal = FirstInst->getOperand(1);
9987     
9988   const Type *LHSType = LHSVal->getType();
9989   const Type *RHSType = RHSVal->getType();
9990   
9991   // Scan to see if all operands are the same opcode, all have one use, and all
9992   // kill their operands (i.e. the operands have one use).
9993   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
9994     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9995     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9996         // Verify type of the LHS matches so we don't fold cmp's of different
9997         // types or GEP's with different index types.
9998         I->getOperand(0)->getType() != LHSType ||
9999         I->getOperand(1)->getType() != RHSType)
10000       return 0;
10001
10002     // If they are CmpInst instructions, check their predicates
10003     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10004       if (cast<CmpInst>(I)->getPredicate() !=
10005           cast<CmpInst>(FirstInst)->getPredicate())
10006         return 0;
10007     
10008     // Keep track of which operand needs a phi node.
10009     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10010     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10011   }
10012   
10013   // Otherwise, this is safe to transform!
10014   
10015   Value *InLHS = FirstInst->getOperand(0);
10016   Value *InRHS = FirstInst->getOperand(1);
10017   PHINode *NewLHS = 0, *NewRHS = 0;
10018   if (LHSVal == 0) {
10019     NewLHS = PHINode::Create(LHSType,
10020                              FirstInst->getOperand(0)->getName() + ".pn");
10021     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10022     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10023     InsertNewInstBefore(NewLHS, PN);
10024     LHSVal = NewLHS;
10025   }
10026   
10027   if (RHSVal == 0) {
10028     NewRHS = PHINode::Create(RHSType,
10029                              FirstInst->getOperand(1)->getName() + ".pn");
10030     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10031     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10032     InsertNewInstBefore(NewRHS, PN);
10033     RHSVal = NewRHS;
10034   }
10035   
10036   // Add all operands to the new PHIs.
10037   if (NewLHS || NewRHS) {
10038     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10039       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10040       if (NewLHS) {
10041         Value *NewInLHS = InInst->getOperand(0);
10042         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10043       }
10044       if (NewRHS) {
10045         Value *NewInRHS = InInst->getOperand(1);
10046         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10047       }
10048     }
10049   }
10050     
10051   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10052     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10053   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10054   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10055                          RHSVal);
10056 }
10057
10058 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10059   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10060   
10061   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10062                                         FirstInst->op_end());
10063   
10064   // Scan to see if all operands are the same opcode, all have one use, and all
10065   // kill their operands (i.e. the operands have one use).
10066   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10067     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10068     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10069       GEP->getNumOperands() != FirstInst->getNumOperands())
10070       return 0;
10071
10072     // Compare the operand lists.
10073     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10074       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10075         continue;
10076       
10077       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10078       // if one of the PHIs has a constant for the index.  The index may be
10079       // substantially cheaper to compute for the constants, so making it a
10080       // variable index could pessimize the path.  This also handles the case
10081       // for struct indices, which must always be constant.
10082       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10083           isa<ConstantInt>(GEP->getOperand(op)))
10084         return 0;
10085       
10086       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10087         return 0;
10088       FixedOperands[op] = 0;  // Needs a PHI.
10089     }
10090   }
10091   
10092   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10093   // that is variable.
10094   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10095   
10096   bool HasAnyPHIs = false;
10097   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10098     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10099     Value *FirstOp = FirstInst->getOperand(i);
10100     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10101                                      FirstOp->getName()+".pn");
10102     InsertNewInstBefore(NewPN, PN);
10103     
10104     NewPN->reserveOperandSpace(e);
10105     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10106     OperandPhis[i] = NewPN;
10107     FixedOperands[i] = NewPN;
10108     HasAnyPHIs = true;
10109   }
10110
10111   
10112   // Add all operands to the new PHIs.
10113   if (HasAnyPHIs) {
10114     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10115       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10116       BasicBlock *InBB = PN.getIncomingBlock(i);
10117       
10118       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10119         if (PHINode *OpPhi = OperandPhis[op])
10120           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10121     }
10122   }
10123   
10124   Value *Base = FixedOperands[0];
10125   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10126                                    FixedOperands.end());
10127 }
10128
10129
10130 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
10131 /// of the block that defines it.  This means that it must be obvious the value
10132 /// of the load is not changed from the point of the load to the end of the
10133 /// block it is in.
10134 ///
10135 /// Finally, it is safe, but not profitable, to sink a load targetting a
10136 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10137 /// to a register.
10138 static bool isSafeToSinkLoad(LoadInst *L) {
10139   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10140   
10141   for (++BBI; BBI != E; ++BBI)
10142     if (BBI->mayWriteToMemory())
10143       return false;
10144   
10145   // Check for non-address taken alloca.  If not address-taken already, it isn't
10146   // profitable to do this xform.
10147   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10148     bool isAddressTaken = false;
10149     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10150          UI != E; ++UI) {
10151       if (isa<LoadInst>(UI)) continue;
10152       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10153         // If storing TO the alloca, then the address isn't taken.
10154         if (SI->getOperand(1) == AI) continue;
10155       }
10156       isAddressTaken = true;
10157       break;
10158     }
10159     
10160     if (!isAddressTaken)
10161       return false;
10162   }
10163   
10164   return true;
10165 }
10166
10167
10168 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10169 // operator and they all are only used by the PHI, PHI together their
10170 // inputs, and do the operation once, to the result of the PHI.
10171 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10172   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10173
10174   // Scan the instruction, looking for input operations that can be folded away.
10175   // If all input operands to the phi are the same instruction (e.g. a cast from
10176   // the same type or "+42") we can pull the operation through the PHI, reducing
10177   // code size and simplifying code.
10178   Constant *ConstantOp = 0;
10179   const Type *CastSrcTy = 0;
10180   bool isVolatile = false;
10181   if (isa<CastInst>(FirstInst)) {
10182     CastSrcTy = FirstInst->getOperand(0)->getType();
10183   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10184     // Can fold binop, compare or shift here if the RHS is a constant, 
10185     // otherwise call FoldPHIArgBinOpIntoPHI.
10186     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10187     if (ConstantOp == 0)
10188       return FoldPHIArgBinOpIntoPHI(PN);
10189   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10190     isVolatile = LI->isVolatile();
10191     // We can't sink the load if the loaded value could be modified between the
10192     // load and the PHI.
10193     if (LI->getParent() != PN.getIncomingBlock(0) ||
10194         !isSafeToSinkLoad(LI))
10195       return 0;
10196     
10197     // If the PHI is of volatile loads and the load block has multiple
10198     // successors, sinking it would remove a load of the volatile value from
10199     // the path through the other successor.
10200     if (isVolatile &&
10201         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10202       return 0;
10203     
10204   } else if (isa<GetElementPtrInst>(FirstInst)) {
10205     return FoldPHIArgGEPIntoPHI(PN);
10206   } else {
10207     return 0;  // Cannot fold this operation.
10208   }
10209
10210   // Check to see if all arguments are the same operation.
10211   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10212     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10213     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10214     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10215       return 0;
10216     if (CastSrcTy) {
10217       if (I->getOperand(0)->getType() != CastSrcTy)
10218         return 0;  // Cast operation must match.
10219     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10220       // We can't sink the load if the loaded value could be modified between 
10221       // the load and the PHI.
10222       if (LI->isVolatile() != isVolatile ||
10223           LI->getParent() != PN.getIncomingBlock(i) ||
10224           !isSafeToSinkLoad(LI))
10225         return 0;
10226       
10227       // If the PHI is of volatile loads and the load block has multiple
10228       // successors, sinking it would remove a load of the volatile value from
10229       // the path through the other successor.
10230       if (isVolatile &&
10231           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10232         return 0;
10233
10234       
10235     } else if (I->getOperand(1) != ConstantOp) {
10236       return 0;
10237     }
10238   }
10239
10240   // Okay, they are all the same operation.  Create a new PHI node of the
10241   // correct type, and PHI together all of the LHS's of the instructions.
10242   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10243                                    PN.getName()+".in");
10244   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10245
10246   Value *InVal = FirstInst->getOperand(0);
10247   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10248
10249   // Add all operands to the new PHI.
10250   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10251     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10252     if (NewInVal != InVal)
10253       InVal = 0;
10254     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10255   }
10256
10257   Value *PhiVal;
10258   if (InVal) {
10259     // The new PHI unions all of the same values together.  This is really
10260     // common, so we handle it intelligently here for compile-time speed.
10261     PhiVal = InVal;
10262     delete NewPN;
10263   } else {
10264     InsertNewInstBefore(NewPN, PN);
10265     PhiVal = NewPN;
10266   }
10267
10268   // Insert and return the new operation.
10269   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10270     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10271   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10272     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10273   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10274     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10275                            PhiVal, ConstantOp);
10276   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10277   
10278   // If this was a volatile load that we are merging, make sure to loop through
10279   // and mark all the input loads as non-volatile.  If we don't do this, we will
10280   // insert a new volatile load and the old ones will not be deletable.
10281   if (isVolatile)
10282     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10283       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10284   
10285   return new LoadInst(PhiVal, "", isVolatile);
10286 }
10287
10288 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10289 /// that is dead.
10290 static bool DeadPHICycle(PHINode *PN,
10291                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10292   if (PN->use_empty()) return true;
10293   if (!PN->hasOneUse()) return false;
10294
10295   // Remember this node, and if we find the cycle, return.
10296   if (!PotentiallyDeadPHIs.insert(PN))
10297     return true;
10298   
10299   // Don't scan crazily complex things.
10300   if (PotentiallyDeadPHIs.size() == 16)
10301     return false;
10302
10303   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10304     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10305
10306   return false;
10307 }
10308
10309 /// PHIsEqualValue - Return true if this phi node is always equal to
10310 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10311 ///   z = some value; x = phi (y, z); y = phi (x, z)
10312 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10313                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10314   // See if we already saw this PHI node.
10315   if (!ValueEqualPHIs.insert(PN))
10316     return true;
10317   
10318   // Don't scan crazily complex things.
10319   if (ValueEqualPHIs.size() == 16)
10320     return false;
10321  
10322   // Scan the operands to see if they are either phi nodes or are equal to
10323   // the value.
10324   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10325     Value *Op = PN->getIncomingValue(i);
10326     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10327       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10328         return false;
10329     } else if (Op != NonPhiInVal)
10330       return false;
10331   }
10332   
10333   return true;
10334 }
10335
10336
10337 // PHINode simplification
10338 //
10339 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10340   // If LCSSA is around, don't mess with Phi nodes
10341   if (MustPreserveLCSSA) return 0;
10342   
10343   if (Value *V = PN.hasConstantValue())
10344     return ReplaceInstUsesWith(PN, V);
10345
10346   // If all PHI operands are the same operation, pull them through the PHI,
10347   // reducing code size.
10348   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10349       isa<Instruction>(PN.getIncomingValue(1)) &&
10350       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10351       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10352       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10353       // than themselves more than once.
10354       PN.getIncomingValue(0)->hasOneUse())
10355     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10356       return Result;
10357
10358   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10359   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10360   // PHI)... break the cycle.
10361   if (PN.hasOneUse()) {
10362     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10363     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10364       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10365       PotentiallyDeadPHIs.insert(&PN);
10366       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10367         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10368     }
10369    
10370     // If this phi has a single use, and if that use just computes a value for
10371     // the next iteration of a loop, delete the phi.  This occurs with unused
10372     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10373     // common case here is good because the only other things that catch this
10374     // are induction variable analysis (sometimes) and ADCE, which is only run
10375     // late.
10376     if (PHIUser->hasOneUse() &&
10377         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10378         PHIUser->use_back() == &PN) {
10379       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10380     }
10381   }
10382
10383   // We sometimes end up with phi cycles that non-obviously end up being the
10384   // same value, for example:
10385   //   z = some value; x = phi (y, z); y = phi (x, z)
10386   // where the phi nodes don't necessarily need to be in the same block.  Do a
10387   // quick check to see if the PHI node only contains a single non-phi value, if
10388   // so, scan to see if the phi cycle is actually equal to that value.
10389   {
10390     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10391     // Scan for the first non-phi operand.
10392     while (InValNo != NumOperandVals && 
10393            isa<PHINode>(PN.getIncomingValue(InValNo)))
10394       ++InValNo;
10395
10396     if (InValNo != NumOperandVals) {
10397       Value *NonPhiInVal = PN.getOperand(InValNo);
10398       
10399       // Scan the rest of the operands to see if there are any conflicts, if so
10400       // there is no need to recursively scan other phis.
10401       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10402         Value *OpVal = PN.getIncomingValue(InValNo);
10403         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10404           break;
10405       }
10406       
10407       // If we scanned over all operands, then we have one unique value plus
10408       // phi values.  Scan PHI nodes to see if they all merge in each other or
10409       // the value.
10410       if (InValNo == NumOperandVals) {
10411         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10412         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10413           return ReplaceInstUsesWith(PN, NonPhiInVal);
10414       }
10415     }
10416   }
10417   return 0;
10418 }
10419
10420 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10421                                    Instruction *InsertPoint,
10422                                    InstCombiner *IC) {
10423   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10424   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10425   // We must cast correctly to the pointer type. Ensure that we
10426   // sign extend the integer value if it is smaller as this is
10427   // used for address computation.
10428   Instruction::CastOps opcode = 
10429      (VTySize < PtrSize ? Instruction::SExt :
10430       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10431   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10432 }
10433
10434
10435 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10436   Value *PtrOp = GEP.getOperand(0);
10437   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10438   // If so, eliminate the noop.
10439   if (GEP.getNumOperands() == 1)
10440     return ReplaceInstUsesWith(GEP, PtrOp);
10441
10442   if (isa<UndefValue>(GEP.getOperand(0)))
10443     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10444
10445   bool HasZeroPointerIndex = false;
10446   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10447     HasZeroPointerIndex = C->isNullValue();
10448
10449   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10450     return ReplaceInstUsesWith(GEP, PtrOp);
10451
10452   // Eliminate unneeded casts for indices.
10453   bool MadeChange = false;
10454   
10455   gep_type_iterator GTI = gep_type_begin(GEP);
10456   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10457        i != e; ++i, ++GTI) {
10458     if (isa<SequentialType>(*GTI)) {
10459       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10460         if (CI->getOpcode() == Instruction::ZExt ||
10461             CI->getOpcode() == Instruction::SExt) {
10462           const Type *SrcTy = CI->getOperand(0)->getType();
10463           // We can eliminate a cast from i32 to i64 iff the target 
10464           // is a 32-bit pointer target.
10465           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10466             MadeChange = true;
10467             *i = CI->getOperand(0);
10468           }
10469         }
10470       }
10471       // If we are using a wider index than needed for this platform, shrink it
10472       // to what we need.  If narrower, sign-extend it to what we need.
10473       // If the incoming value needs a cast instruction,
10474       // insert it.  This explicit cast can make subsequent optimizations more
10475       // obvious.
10476       Value *Op = *i;
10477       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10478         if (Constant *C = dyn_cast<Constant>(Op)) {
10479           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10480           MadeChange = true;
10481         } else {
10482           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10483                                 GEP);
10484           *i = Op;
10485           MadeChange = true;
10486         }
10487       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10488         if (Constant *C = dyn_cast<Constant>(Op)) {
10489           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10490           MadeChange = true;
10491         } else {
10492           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10493                                 GEP);
10494           *i = Op;
10495           MadeChange = true;
10496         }
10497       }
10498     }
10499   }
10500   if (MadeChange) return &GEP;
10501
10502   // Combine Indices - If the source pointer to this getelementptr instruction
10503   // is a getelementptr instruction, combine the indices of the two
10504   // getelementptr instructions into a single instruction.
10505   //
10506   SmallVector<Value*, 8> SrcGEPOperands;
10507   if (User *Src = dyn_castGetElementPtr(PtrOp))
10508     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10509
10510   if (!SrcGEPOperands.empty()) {
10511     // Note that if our source is a gep chain itself that we wait for that
10512     // chain to be resolved before we perform this transformation.  This
10513     // avoids us creating a TON of code in some cases.
10514     //
10515     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10516         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10517       return 0;   // Wait until our source is folded to completion.
10518
10519     SmallVector<Value*, 8> Indices;
10520
10521     // Find out whether the last index in the source GEP is a sequential idx.
10522     bool EndsWithSequential = false;
10523     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10524            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10525       EndsWithSequential = !isa<StructType>(*I);
10526
10527     // Can we combine the two pointer arithmetics offsets?
10528     if (EndsWithSequential) {
10529       // Replace: gep (gep %P, long B), long A, ...
10530       // With:    T = long A+B; gep %P, T, ...
10531       //
10532       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10533       if (SO1 == Constant::getNullValue(SO1->getType())) {
10534         Sum = GO1;
10535       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10536         Sum = SO1;
10537       } else {
10538         // If they aren't the same type, convert both to an integer of the
10539         // target's pointer size.
10540         if (SO1->getType() != GO1->getType()) {
10541           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10542             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10543           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10544             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10545           } else {
10546             unsigned PS = TD->getPointerSizeInBits();
10547             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10548               // Convert GO1 to SO1's type.
10549               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10550
10551             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10552               // Convert SO1 to GO1's type.
10553               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10554             } else {
10555               const Type *PT = TD->getIntPtrType();
10556               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10557               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10558             }
10559           }
10560         }
10561         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10562           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10563         else {
10564           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10565           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10566         }
10567       }
10568
10569       // Recycle the GEP we already have if possible.
10570       if (SrcGEPOperands.size() == 2) {
10571         GEP.setOperand(0, SrcGEPOperands[0]);
10572         GEP.setOperand(1, Sum);
10573         return &GEP;
10574       } else {
10575         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10576                        SrcGEPOperands.end()-1);
10577         Indices.push_back(Sum);
10578         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10579       }
10580     } else if (isa<Constant>(*GEP.idx_begin()) &&
10581                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10582                SrcGEPOperands.size() != 1) {
10583       // Otherwise we can do the fold if the first index of the GEP is a zero
10584       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10585                      SrcGEPOperands.end());
10586       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10587     }
10588
10589     if (!Indices.empty())
10590       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10591                                        Indices.end(), GEP.getName());
10592
10593   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10594     // GEP of global variable.  If all of the indices for this GEP are
10595     // constants, we can promote this to a constexpr instead of an instruction.
10596
10597     // Scan for nonconstants...
10598     SmallVector<Constant*, 8> Indices;
10599     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10600     for (; I != E && isa<Constant>(*I); ++I)
10601       Indices.push_back(cast<Constant>(*I));
10602
10603     if (I == E) {  // If they are all constants...
10604       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10605                                                     &Indices[0],Indices.size());
10606
10607       // Replace all uses of the GEP with the new constexpr...
10608       return ReplaceInstUsesWith(GEP, CE);
10609     }
10610   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10611     if (!isa<PointerType>(X->getType())) {
10612       // Not interesting.  Source pointer must be a cast from pointer.
10613     } else if (HasZeroPointerIndex) {
10614       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10615       // into     : GEP [10 x i8]* X, i32 0, ...
10616       //
10617       // This occurs when the program declares an array extern like "int X[];"
10618       //
10619       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10620       const PointerType *XTy = cast<PointerType>(X->getType());
10621       if (const ArrayType *XATy =
10622           dyn_cast<ArrayType>(XTy->getElementType()))
10623         if (const ArrayType *CATy =
10624             dyn_cast<ArrayType>(CPTy->getElementType()))
10625           if (CATy->getElementType() == XATy->getElementType()) {
10626             // At this point, we know that the cast source type is a pointer
10627             // to an array of the same type as the destination pointer
10628             // array.  Because the array type is never stepped over (there
10629             // is a leading zero) we can fold the cast into this GEP.
10630             GEP.setOperand(0, X);
10631             return &GEP;
10632           }
10633     } else if (GEP.getNumOperands() == 2) {
10634       // Transform things like:
10635       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10636       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10637       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10638       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10639       if (isa<ArrayType>(SrcElTy) &&
10640           TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10641           TD->getTypePaddedSize(ResElTy)) {
10642         Value *Idx[2];
10643         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10644         Idx[1] = GEP.getOperand(1);
10645         Value *V = InsertNewInstBefore(
10646                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10647         // V and GEP are both pointer types --> BitCast
10648         return new BitCastInst(V, GEP.getType());
10649       }
10650       
10651       // Transform things like:
10652       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10653       //   (where tmp = 8*tmp2) into:
10654       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10655       
10656       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10657         uint64_t ArrayEltSize =
10658             TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
10659         
10660         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10661         // allow either a mul, shift, or constant here.
10662         Value *NewIdx = 0;
10663         ConstantInt *Scale = 0;
10664         if (ArrayEltSize == 1) {
10665           NewIdx = GEP.getOperand(1);
10666           Scale = ConstantInt::get(NewIdx->getType(), 1);
10667         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10668           NewIdx = ConstantInt::get(CI->getType(), 1);
10669           Scale = CI;
10670         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10671           if (Inst->getOpcode() == Instruction::Shl &&
10672               isa<ConstantInt>(Inst->getOperand(1))) {
10673             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10674             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10675             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10676             NewIdx = Inst->getOperand(0);
10677           } else if (Inst->getOpcode() == Instruction::Mul &&
10678                      isa<ConstantInt>(Inst->getOperand(1))) {
10679             Scale = cast<ConstantInt>(Inst->getOperand(1));
10680             NewIdx = Inst->getOperand(0);
10681           }
10682         }
10683         
10684         // If the index will be to exactly the right offset with the scale taken
10685         // out, perform the transformation. Note, we don't know whether Scale is
10686         // signed or not. We'll use unsigned version of division/modulo
10687         // operation after making sure Scale doesn't have the sign bit set.
10688         if (Scale && Scale->getSExtValue() >= 0LL &&
10689             Scale->getZExtValue() % ArrayEltSize == 0) {
10690           Scale = ConstantInt::get(Scale->getType(),
10691                                    Scale->getZExtValue() / ArrayEltSize);
10692           if (Scale->getZExtValue() != 1) {
10693             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10694                                                        false /*ZExt*/);
10695             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10696             NewIdx = InsertNewInstBefore(Sc, GEP);
10697           }
10698
10699           // Insert the new GEP instruction.
10700           Value *Idx[2];
10701           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10702           Idx[1] = NewIdx;
10703           Instruction *NewGEP =
10704             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10705           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10706           // The NewGEP must be pointer typed, so must the old one -> BitCast
10707           return new BitCastInst(NewGEP, GEP.getType());
10708         }
10709       }
10710     }
10711   }
10712   
10713   /// See if we can simplify:
10714   ///   X = bitcast A to B*
10715   ///   Y = gep X, <...constant indices...>
10716   /// into a gep of the original struct.  This is important for SROA and alias
10717   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
10718   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
10719     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10720       // Determine how much the GEP moves the pointer.  We are guaranteed to get
10721       // a constant back from EmitGEPOffset.
10722       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10723       int64_t Offset = OffsetV->getSExtValue();
10724       
10725       // If this GEP instruction doesn't move the pointer, just replace the GEP
10726       // with a bitcast of the real input to the dest type.
10727       if (Offset == 0) {
10728         // If the bitcast is of an allocation, and the allocation will be
10729         // converted to match the type of the cast, don't touch this.
10730         if (isa<AllocationInst>(BCI->getOperand(0))) {
10731           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10732           if (Instruction *I = visitBitCast(*BCI)) {
10733             if (I != BCI) {
10734               I->takeName(BCI);
10735               BCI->getParent()->getInstList().insert(BCI, I);
10736               ReplaceInstUsesWith(*BCI, I);
10737             }
10738             return &GEP;
10739           }
10740         }
10741         return new BitCastInst(BCI->getOperand(0), GEP.getType());
10742       }
10743       
10744       // Otherwise, if the offset is non-zero, we need to find out if there is a
10745       // field at Offset in 'A's type.  If so, we can pull the cast through the
10746       // GEP.
10747       SmallVector<Value*, 8> NewIndices;
10748       const Type *InTy =
10749         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10750       if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10751         Instruction *NGEP =
10752            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10753                                      NewIndices.end());
10754         if (NGEP->getType() == GEP.getType()) return NGEP;
10755         InsertNewInstBefore(NGEP, GEP);
10756         NGEP->takeName(&GEP);
10757         return new BitCastInst(NGEP, GEP.getType());
10758       }
10759     }
10760   }    
10761     
10762   return 0;
10763 }
10764
10765 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10766   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10767   if (AI.isArrayAllocation()) {  // Check C != 1
10768     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10769       const Type *NewTy = 
10770         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10771       AllocationInst *New = 0;
10772
10773       // Create and insert the replacement instruction...
10774       if (isa<MallocInst>(AI))
10775         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10776       else {
10777         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10778         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10779       }
10780
10781       InsertNewInstBefore(New, AI);
10782
10783       // Scan to the end of the allocation instructions, to skip over a block of
10784       // allocas if possible...
10785       //
10786       BasicBlock::iterator It = New;
10787       while (isa<AllocationInst>(*It)) ++It;
10788
10789       // Now that I is pointing to the first non-allocation-inst in the block,
10790       // insert our getelementptr instruction...
10791       //
10792       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10793       Value *Idx[2];
10794       Idx[0] = NullIdx;
10795       Idx[1] = NullIdx;
10796       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10797                                            New->getName()+".sub", It);
10798
10799       // Now make everything use the getelementptr instead of the original
10800       // allocation.
10801       return ReplaceInstUsesWith(AI, V);
10802     } else if (isa<UndefValue>(AI.getArraySize())) {
10803       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10804     }
10805   }
10806
10807   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
10808     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10809     // Note that we only do this for alloca's, because malloc should allocate and
10810     // return a unique pointer, even for a zero byte allocation.
10811     if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
10812       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10813
10814     // If the alignment is 0 (unspecified), assign it the preferred alignment.
10815     if (AI.getAlignment() == 0)
10816       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
10817   }
10818
10819   return 0;
10820 }
10821
10822 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10823   Value *Op = FI.getOperand(0);
10824
10825   // free undef -> unreachable.
10826   if (isa<UndefValue>(Op)) {
10827     // Insert a new store to null because we cannot modify the CFG here.
10828     new StoreInst(ConstantInt::getTrue(),
10829                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10830     return EraseInstFromFunction(FI);
10831   }
10832   
10833   // If we have 'free null' delete the instruction.  This can happen in stl code
10834   // when lots of inlining happens.
10835   if (isa<ConstantPointerNull>(Op))
10836     return EraseInstFromFunction(FI);
10837   
10838   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10839   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10840     FI.setOperand(0, CI->getOperand(0));
10841     return &FI;
10842   }
10843   
10844   // Change free (gep X, 0,0,0,0) into free(X)
10845   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10846     if (GEPI->hasAllZeroIndices()) {
10847       AddToWorkList(GEPI);
10848       FI.setOperand(0, GEPI->getOperand(0));
10849       return &FI;
10850     }
10851   }
10852   
10853   // Change free(malloc) into nothing, if the malloc has a single use.
10854   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10855     if (MI->hasOneUse()) {
10856       EraseInstFromFunction(FI);
10857       return EraseInstFromFunction(*MI);
10858     }
10859
10860   return 0;
10861 }
10862
10863
10864 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10865 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10866                                         const TargetData *TD) {
10867   User *CI = cast<User>(LI.getOperand(0));
10868   Value *CastOp = CI->getOperand(0);
10869
10870   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10871     // Instead of loading constant c string, use corresponding integer value
10872     // directly if string length is small enough.
10873     std::string Str;
10874     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10875       unsigned len = Str.length();
10876       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10877       unsigned numBits = Ty->getPrimitiveSizeInBits();
10878       // Replace LI with immediate integer store.
10879       if ((numBits >> 3) == len + 1) {
10880         APInt StrVal(numBits, 0);
10881         APInt SingleChar(numBits, 0);
10882         if (TD->isLittleEndian()) {
10883           for (signed i = len-1; i >= 0; i--) {
10884             SingleChar = (uint64_t) Str[i];
10885             StrVal = (StrVal << 8) | SingleChar;
10886           }
10887         } else {
10888           for (unsigned i = 0; i < len; i++) {
10889             SingleChar = (uint64_t) Str[i];
10890             StrVal = (StrVal << 8) | SingleChar;
10891           }
10892           // Append NULL at the end.
10893           SingleChar = 0;
10894           StrVal = (StrVal << 8) | SingleChar;
10895         }
10896         Value *NL = ConstantInt::get(StrVal);
10897         return IC.ReplaceInstUsesWith(LI, NL);
10898       }
10899     }
10900   }
10901
10902   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10903   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10904     const Type *SrcPTy = SrcTy->getElementType();
10905
10906     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10907          isa<VectorType>(DestPTy)) {
10908       // If the source is an array, the code below will not succeed.  Check to
10909       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10910       // constants.
10911       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10912         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10913           if (ASrcTy->getNumElements() != 0) {
10914             Value *Idxs[2];
10915             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10916             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10917             SrcTy = cast<PointerType>(CastOp->getType());
10918             SrcPTy = SrcTy->getElementType();
10919           }
10920
10921       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10922             isa<VectorType>(SrcPTy)) &&
10923           // Do not allow turning this into a load of an integer, which is then
10924           // casted to a pointer, this pessimizes pointer analysis a lot.
10925           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10926           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10927                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10928
10929         // Okay, we are casting from one integer or pointer type to another of
10930         // the same size.  Instead of casting the pointer before the load, cast
10931         // the result of the loaded value.
10932         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10933                                                              CI->getName(),
10934                                                          LI.isVolatile()),LI);
10935         // Now cast the result of the load.
10936         return new BitCastInst(NewLoad, LI.getType());
10937       }
10938     }
10939   }
10940   return 0;
10941 }
10942
10943 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10944 /// from this value cannot trap.  If it is not obviously safe to load from the
10945 /// specified pointer, we do a quick local scan of the basic block containing
10946 /// ScanFrom, to determine if the address is already accessed.
10947 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10948   // If it is an alloca it is always safe to load from.
10949   if (isa<AllocaInst>(V)) return true;
10950
10951   // If it is a global variable it is mostly safe to load from.
10952   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10953     // Don't try to evaluate aliases.  External weak GV can be null.
10954     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10955
10956   // Otherwise, be a little bit agressive by scanning the local block where we
10957   // want to check to see if the pointer is already being loaded or stored
10958   // from/to.  If so, the previous load or store would have already trapped,
10959   // so there is no harm doing an extra load (also, CSE will later eliminate
10960   // the load entirely).
10961   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10962
10963   while (BBI != E) {
10964     --BBI;
10965
10966     // If we see a free or a call (which might do a free) the pointer could be
10967     // marked invalid.
10968     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10969       return false;
10970     
10971     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10972       if (LI->getOperand(0) == V) return true;
10973     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10974       if (SI->getOperand(1) == V) return true;
10975     }
10976
10977   }
10978   return false;
10979 }
10980
10981 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10982   Value *Op = LI.getOperand(0);
10983
10984   // Attempt to improve the alignment.
10985   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10986   if (KnownAlign >
10987       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10988                                 LI.getAlignment()))
10989     LI.setAlignment(KnownAlign);
10990
10991   // load (cast X) --> cast (load X) iff safe
10992   if (isa<CastInst>(Op))
10993     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10994       return Res;
10995
10996   // None of the following transforms are legal for volatile loads.
10997   if (LI.isVolatile()) return 0;
10998   
10999   // Do really simple store-to-load forwarding and load CSE, to catch cases
11000   // where there are several consequtive memory accesses to the same location,
11001   // separated by a few arithmetic operations.
11002   BasicBlock::iterator BBI = &LI;
11003   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11004     return ReplaceInstUsesWith(LI, AvailableVal);
11005
11006   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11007     const Value *GEPI0 = GEPI->getOperand(0);
11008     // TODO: Consider a target hook for valid address spaces for this xform.
11009     if (isa<ConstantPointerNull>(GEPI0) &&
11010         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11011       // Insert a new store to null instruction before the load to indicate
11012       // that this code is not reachable.  We do this instead of inserting
11013       // an unreachable instruction directly because we cannot modify the
11014       // CFG.
11015       new StoreInst(UndefValue::get(LI.getType()),
11016                     Constant::getNullValue(Op->getType()), &LI);
11017       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11018     }
11019   } 
11020
11021   if (Constant *C = dyn_cast<Constant>(Op)) {
11022     // load null/undef -> undef
11023     // TODO: Consider a target hook for valid address spaces for this xform.
11024     if (isa<UndefValue>(C) || (C->isNullValue() && 
11025         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11026       // Insert a new store to null instruction before the load to indicate that
11027       // this code is not reachable.  We do this instead of inserting an
11028       // unreachable instruction directly because we cannot modify the CFG.
11029       new StoreInst(UndefValue::get(LI.getType()),
11030                     Constant::getNullValue(Op->getType()), &LI);
11031       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11032     }
11033
11034     // Instcombine load (constant global) into the value loaded.
11035     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11036       if (GV->isConstant() && !GV->isDeclaration())
11037         return ReplaceInstUsesWith(LI, GV->getInitializer());
11038
11039     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11040     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11041       if (CE->getOpcode() == Instruction::GetElementPtr) {
11042         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11043           if (GV->isConstant() && !GV->isDeclaration())
11044             if (Constant *V = 
11045                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11046               return ReplaceInstUsesWith(LI, V);
11047         if (CE->getOperand(0)->isNullValue()) {
11048           // Insert a new store to null instruction before the load to indicate
11049           // that this code is not reachable.  We do this instead of inserting
11050           // an unreachable instruction directly because we cannot modify the
11051           // CFG.
11052           new StoreInst(UndefValue::get(LI.getType()),
11053                         Constant::getNullValue(Op->getType()), &LI);
11054           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11055         }
11056
11057       } else if (CE->isCast()) {
11058         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11059           return Res;
11060       }
11061     }
11062   }
11063     
11064   // If this load comes from anywhere in a constant global, and if the global
11065   // is all undef or zero, we know what it loads.
11066   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11067     if (GV->isConstant() && GV->hasInitializer()) {
11068       if (GV->getInitializer()->isNullValue())
11069         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11070       else if (isa<UndefValue>(GV->getInitializer()))
11071         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11072     }
11073   }
11074
11075   if (Op->hasOneUse()) {
11076     // Change select and PHI nodes to select values instead of addresses: this
11077     // helps alias analysis out a lot, allows many others simplifications, and
11078     // exposes redundancy in the code.
11079     //
11080     // Note that we cannot do the transformation unless we know that the
11081     // introduced loads cannot trap!  Something like this is valid as long as
11082     // the condition is always false: load (select bool %C, int* null, int* %G),
11083     // but it would not be valid if we transformed it to load from null
11084     // unconditionally.
11085     //
11086     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11087       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11088       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11089           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11090         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11091                                      SI->getOperand(1)->getName()+".val"), LI);
11092         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11093                                      SI->getOperand(2)->getName()+".val"), LI);
11094         return SelectInst::Create(SI->getCondition(), V1, V2);
11095       }
11096
11097       // load (select (cond, null, P)) -> load P
11098       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11099         if (C->isNullValue()) {
11100           LI.setOperand(0, SI->getOperand(2));
11101           return &LI;
11102         }
11103
11104       // load (select (cond, P, null)) -> load P
11105       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11106         if (C->isNullValue()) {
11107           LI.setOperand(0, SI->getOperand(1));
11108           return &LI;
11109         }
11110     }
11111   }
11112   return 0;
11113 }
11114
11115 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11116 /// when possible.  This makes it generally easy to do alias analysis and/or
11117 /// SROA/mem2reg of the memory object.
11118 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11119   User *CI = cast<User>(SI.getOperand(1));
11120   Value *CastOp = CI->getOperand(0);
11121
11122   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11123   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11124   if (SrcTy == 0) return 0;
11125   
11126   const Type *SrcPTy = SrcTy->getElementType();
11127
11128   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11129     return 0;
11130   
11131   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11132   /// to its first element.  This allows us to handle things like:
11133   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11134   /// on 32-bit hosts.
11135   SmallVector<Value*, 4> NewGEPIndices;
11136   
11137   // If the source is an array, the code below will not succeed.  Check to
11138   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11139   // constants.
11140   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11141     // Index through pointer.
11142     Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11143     NewGEPIndices.push_back(Zero);
11144     
11145     while (1) {
11146       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11147         if (!STy->getNumElements()) /* Struct can be empty {} */
11148           break;
11149         NewGEPIndices.push_back(Zero);
11150         SrcPTy = STy->getElementType(0);
11151       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11152         NewGEPIndices.push_back(Zero);
11153         SrcPTy = ATy->getElementType();
11154       } else {
11155         break;
11156       }
11157     }
11158     
11159     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11160   }
11161
11162   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11163     return 0;
11164   
11165   // If the pointers point into different address spaces or if they point to
11166   // values with different sizes, we can't do the transformation.
11167   if (SrcTy->getAddressSpace() != 
11168         cast<PointerType>(CI->getType())->getAddressSpace() ||
11169       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11170       IC.getTargetData().getTypeSizeInBits(DestPTy))
11171     return 0;
11172
11173   // Okay, we are casting from one integer or pointer type to another of
11174   // the same size.  Instead of casting the pointer before 
11175   // the store, cast the value to be stored.
11176   Value *NewCast;
11177   Value *SIOp0 = SI.getOperand(0);
11178   Instruction::CastOps opcode = Instruction::BitCast;
11179   const Type* CastSrcTy = SIOp0->getType();
11180   const Type* CastDstTy = SrcPTy;
11181   if (isa<PointerType>(CastDstTy)) {
11182     if (CastSrcTy->isInteger())
11183       opcode = Instruction::IntToPtr;
11184   } else if (isa<IntegerType>(CastDstTy)) {
11185     if (isa<PointerType>(SIOp0->getType()))
11186       opcode = Instruction::PtrToInt;
11187   }
11188   
11189   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11190   // emit a GEP to index into its first field.
11191   if (!NewGEPIndices.empty()) {
11192     if (Constant *C = dyn_cast<Constant>(CastOp))
11193       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11194                                               NewGEPIndices.size());
11195     else
11196       CastOp = IC.InsertNewInstBefore(
11197               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11198                                         NewGEPIndices.end()), SI);
11199   }
11200   
11201   if (Constant *C = dyn_cast<Constant>(SIOp0))
11202     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11203   else
11204     NewCast = IC.InsertNewInstBefore(
11205       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11206       SI);
11207   return new StoreInst(NewCast, CastOp);
11208 }
11209
11210 /// equivalentAddressValues - Test if A and B will obviously have the same
11211 /// value. This includes recognizing that %t0 and %t1 will have the same
11212 /// value in code like this:
11213 ///   %t0 = getelementptr @a, 0, 3
11214 ///   store i32 0, i32* %t0
11215 ///   %t1 = getelementptr @a, 0, 3
11216 ///   %t2 = load i32* %t1
11217 ///
11218 static bool equivalentAddressValues(Value *A, Value *B) {
11219   // Test if the values are trivially equivalent.
11220   if (A == B) return true;
11221   
11222   // Test if the values come form identical arithmetic instructions.
11223   if (isa<BinaryOperator>(A) ||
11224       isa<CastInst>(A) ||
11225       isa<PHINode>(A) ||
11226       isa<GetElementPtrInst>(A))
11227     if (Instruction *BI = dyn_cast<Instruction>(B))
11228       if (cast<Instruction>(A)->isIdenticalTo(BI))
11229         return true;
11230   
11231   // Otherwise they may not be equivalent.
11232   return false;
11233 }
11234
11235 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11236   Value *Val = SI.getOperand(0);
11237   Value *Ptr = SI.getOperand(1);
11238
11239   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11240     EraseInstFromFunction(SI);
11241     ++NumCombined;
11242     return 0;
11243   }
11244   
11245   // If the RHS is an alloca with a single use, zapify the store, making the
11246   // alloca dead.
11247   if (Ptr->hasOneUse() && !SI.isVolatile()) {
11248     if (isa<AllocaInst>(Ptr)) {
11249       EraseInstFromFunction(SI);
11250       ++NumCombined;
11251       return 0;
11252     }
11253     
11254     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11255       if (isa<AllocaInst>(GEP->getOperand(0)) &&
11256           GEP->getOperand(0)->hasOneUse()) {
11257         EraseInstFromFunction(SI);
11258         ++NumCombined;
11259         return 0;
11260       }
11261   }
11262
11263   // Attempt to improve the alignment.
11264   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11265   if (KnownAlign >
11266       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11267                                 SI.getAlignment()))
11268     SI.setAlignment(KnownAlign);
11269
11270   // Do really simple DSE, to catch cases where there are several consequtive
11271   // stores to the same location, separated by a few arithmetic operations. This
11272   // situation often occurs with bitfield accesses.
11273   BasicBlock::iterator BBI = &SI;
11274   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11275        --ScanInsts) {
11276     --BBI;
11277     
11278     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11279       // Prev store isn't volatile, and stores to the same location?
11280       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11281                                                           SI.getOperand(1))) {
11282         ++NumDeadStore;
11283         ++BBI;
11284         EraseInstFromFunction(*PrevSI);
11285         continue;
11286       }
11287       break;
11288     }
11289     
11290     // If this is a load, we have to stop.  However, if the loaded value is from
11291     // the pointer we're loading and is producing the pointer we're storing,
11292     // then *this* store is dead (X = load P; store X -> P).
11293     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11294       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11295           !SI.isVolatile()) {
11296         EraseInstFromFunction(SI);
11297         ++NumCombined;
11298         return 0;
11299       }
11300       // Otherwise, this is a load from some other location.  Stores before it
11301       // may not be dead.
11302       break;
11303     }
11304     
11305     // Don't skip over loads or things that can modify memory.
11306     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11307       break;
11308   }
11309   
11310   
11311   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11312
11313   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11314   if (isa<ConstantPointerNull>(Ptr)) {
11315     if (!isa<UndefValue>(Val)) {
11316       SI.setOperand(0, UndefValue::get(Val->getType()));
11317       if (Instruction *U = dyn_cast<Instruction>(Val))
11318         AddToWorkList(U);  // Dropped a use.
11319       ++NumCombined;
11320     }
11321     return 0;  // Do not modify these!
11322   }
11323
11324   // store undef, Ptr -> noop
11325   if (isa<UndefValue>(Val)) {
11326     EraseInstFromFunction(SI);
11327     ++NumCombined;
11328     return 0;
11329   }
11330
11331   // If the pointer destination is a cast, see if we can fold the cast into the
11332   // source instead.
11333   if (isa<CastInst>(Ptr))
11334     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11335       return Res;
11336   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11337     if (CE->isCast())
11338       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11339         return Res;
11340
11341   
11342   // If this store is the last instruction in the basic block, and if the block
11343   // ends with an unconditional branch, try to move it to the successor block.
11344   BBI = &SI; ++BBI;
11345   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11346     if (BI->isUnconditional())
11347       if (SimplifyStoreAtEndOfBlock(SI))
11348         return 0;  // xform done!
11349   
11350   return 0;
11351 }
11352
11353 /// SimplifyStoreAtEndOfBlock - Turn things like:
11354 ///   if () { *P = v1; } else { *P = v2 }
11355 /// into a phi node with a store in the successor.
11356 ///
11357 /// Simplify things like:
11358 ///   *P = v1; if () { *P = v2; }
11359 /// into a phi node with a store in the successor.
11360 ///
11361 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11362   BasicBlock *StoreBB = SI.getParent();
11363   
11364   // Check to see if the successor block has exactly two incoming edges.  If
11365   // so, see if the other predecessor contains a store to the same location.
11366   // if so, insert a PHI node (if needed) and move the stores down.
11367   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11368   
11369   // Determine whether Dest has exactly two predecessors and, if so, compute
11370   // the other predecessor.
11371   pred_iterator PI = pred_begin(DestBB);
11372   BasicBlock *OtherBB = 0;
11373   if (*PI != StoreBB)
11374     OtherBB = *PI;
11375   ++PI;
11376   if (PI == pred_end(DestBB))
11377     return false;
11378   
11379   if (*PI != StoreBB) {
11380     if (OtherBB)
11381       return false;
11382     OtherBB = *PI;
11383   }
11384   if (++PI != pred_end(DestBB))
11385     return false;
11386
11387   // Bail out if all the relevant blocks aren't distinct (this can happen,
11388   // for example, if SI is in an infinite loop)
11389   if (StoreBB == DestBB || OtherBB == DestBB)
11390     return false;
11391
11392   // Verify that the other block ends in a branch and is not otherwise empty.
11393   BasicBlock::iterator BBI = OtherBB->getTerminator();
11394   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11395   if (!OtherBr || BBI == OtherBB->begin())
11396     return false;
11397   
11398   // If the other block ends in an unconditional branch, check for the 'if then
11399   // else' case.  there is an instruction before the branch.
11400   StoreInst *OtherStore = 0;
11401   if (OtherBr->isUnconditional()) {
11402     // If this isn't a store, or isn't a store to the same location, bail out.
11403     --BBI;
11404     OtherStore = dyn_cast<StoreInst>(BBI);
11405     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11406       return false;
11407   } else {
11408     // Otherwise, the other block ended with a conditional branch. If one of the
11409     // destinations is StoreBB, then we have the if/then case.
11410     if (OtherBr->getSuccessor(0) != StoreBB && 
11411         OtherBr->getSuccessor(1) != StoreBB)
11412       return false;
11413     
11414     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11415     // if/then triangle.  See if there is a store to the same ptr as SI that
11416     // lives in OtherBB.
11417     for (;; --BBI) {
11418       // Check to see if we find the matching store.
11419       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11420         if (OtherStore->getOperand(1) != SI.getOperand(1))
11421           return false;
11422         break;
11423       }
11424       // If we find something that may be using or overwriting the stored
11425       // value, or if we run out of instructions, we can't do the xform.
11426       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11427           BBI == OtherBB->begin())
11428         return false;
11429     }
11430     
11431     // In order to eliminate the store in OtherBr, we have to
11432     // make sure nothing reads or overwrites the stored value in
11433     // StoreBB.
11434     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11435       // FIXME: This should really be AA driven.
11436       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11437         return false;
11438     }
11439   }
11440   
11441   // Insert a PHI node now if we need it.
11442   Value *MergedVal = OtherStore->getOperand(0);
11443   if (MergedVal != SI.getOperand(0)) {
11444     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11445     PN->reserveOperandSpace(2);
11446     PN->addIncoming(SI.getOperand(0), SI.getParent());
11447     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11448     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11449   }
11450   
11451   // Advance to a place where it is safe to insert the new store and
11452   // insert it.
11453   BBI = DestBB->getFirstNonPHI();
11454   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11455                                     OtherStore->isVolatile()), *BBI);
11456   
11457   // Nuke the old stores.
11458   EraseInstFromFunction(SI);
11459   EraseInstFromFunction(*OtherStore);
11460   ++NumCombined;
11461   return true;
11462 }
11463
11464
11465 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11466   // Change br (not X), label True, label False to: br X, label False, True
11467   Value *X = 0;
11468   BasicBlock *TrueDest;
11469   BasicBlock *FalseDest;
11470   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11471       !isa<Constant>(X)) {
11472     // Swap Destinations and condition...
11473     BI.setCondition(X);
11474     BI.setSuccessor(0, FalseDest);
11475     BI.setSuccessor(1, TrueDest);
11476     return &BI;
11477   }
11478
11479   // Cannonicalize fcmp_one -> fcmp_oeq
11480   FCmpInst::Predicate FPred; Value *Y;
11481   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11482                              TrueDest, FalseDest)))
11483     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11484          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11485       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11486       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11487       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11488       NewSCC->takeName(I);
11489       // Swap Destinations and condition...
11490       BI.setCondition(NewSCC);
11491       BI.setSuccessor(0, FalseDest);
11492       BI.setSuccessor(1, TrueDest);
11493       RemoveFromWorkList(I);
11494       I->eraseFromParent();
11495       AddToWorkList(NewSCC);
11496       return &BI;
11497     }
11498
11499   // Cannonicalize icmp_ne -> icmp_eq
11500   ICmpInst::Predicate IPred;
11501   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11502                       TrueDest, FalseDest)))
11503     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11504          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11505          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11506       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11507       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11508       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11509       NewSCC->takeName(I);
11510       // Swap Destinations and condition...
11511       BI.setCondition(NewSCC);
11512       BI.setSuccessor(0, FalseDest);
11513       BI.setSuccessor(1, TrueDest);
11514       RemoveFromWorkList(I);
11515       I->eraseFromParent();;
11516       AddToWorkList(NewSCC);
11517       return &BI;
11518     }
11519
11520   return 0;
11521 }
11522
11523 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11524   Value *Cond = SI.getCondition();
11525   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11526     if (I->getOpcode() == Instruction::Add)
11527       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11528         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11529         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11530           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11531                                                 AddRHS));
11532         SI.setOperand(0, I->getOperand(0));
11533         AddToWorkList(I);
11534         return &SI;
11535       }
11536   }
11537   return 0;
11538 }
11539
11540 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11541   Value *Agg = EV.getAggregateOperand();
11542
11543   if (!EV.hasIndices())
11544     return ReplaceInstUsesWith(EV, Agg);
11545
11546   if (Constant *C = dyn_cast<Constant>(Agg)) {
11547     if (isa<UndefValue>(C))
11548       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11549       
11550     if (isa<ConstantAggregateZero>(C))
11551       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11552
11553     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11554       // Extract the element indexed by the first index out of the constant
11555       Value *V = C->getOperand(*EV.idx_begin());
11556       if (EV.getNumIndices() > 1)
11557         // Extract the remaining indices out of the constant indexed by the
11558         // first index
11559         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11560       else
11561         return ReplaceInstUsesWith(EV, V);
11562     }
11563     return 0; // Can't handle other constants
11564   } 
11565   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11566     // We're extracting from an insertvalue instruction, compare the indices
11567     const unsigned *exti, *exte, *insi, *inse;
11568     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11569          exte = EV.idx_end(), inse = IV->idx_end();
11570          exti != exte && insi != inse;
11571          ++exti, ++insi) {
11572       if (*insi != *exti)
11573         // The insert and extract both reference distinctly different elements.
11574         // This means the extract is not influenced by the insert, and we can
11575         // replace the aggregate operand of the extract with the aggregate
11576         // operand of the insert. i.e., replace
11577         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11578         // %E = extractvalue { i32, { i32 } } %I, 0
11579         // with
11580         // %E = extractvalue { i32, { i32 } } %A, 0
11581         return ExtractValueInst::Create(IV->getAggregateOperand(),
11582                                         EV.idx_begin(), EV.idx_end());
11583     }
11584     if (exti == exte && insi == inse)
11585       // Both iterators are at the end: Index lists are identical. Replace
11586       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11587       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11588       // with "i32 42"
11589       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11590     if (exti == exte) {
11591       // The extract list is a prefix of the insert list. i.e. replace
11592       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11593       // %E = extractvalue { i32, { i32 } } %I, 1
11594       // with
11595       // %X = extractvalue { i32, { i32 } } %A, 1
11596       // %E = insertvalue { i32 } %X, i32 42, 0
11597       // by switching the order of the insert and extract (though the
11598       // insertvalue should be left in, since it may have other uses).
11599       Value *NewEV = InsertNewInstBefore(
11600         ExtractValueInst::Create(IV->getAggregateOperand(),
11601                                  EV.idx_begin(), EV.idx_end()),
11602         EV);
11603       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11604                                      insi, inse);
11605     }
11606     if (insi == inse)
11607       // The insert list is a prefix of the extract list
11608       // We can simply remove the common indices from the extract and make it
11609       // operate on the inserted value instead of the insertvalue result.
11610       // i.e., replace
11611       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11612       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11613       // with
11614       // %E extractvalue { i32 } { i32 42 }, 0
11615       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11616                                       exti, exte);
11617   }
11618   // Can't simplify extracts from other values. Note that nested extracts are
11619   // already simplified implicitely by the above (extract ( extract (insert) )
11620   // will be translated into extract ( insert ( extract ) ) first and then just
11621   // the value inserted, if appropriate).
11622   return 0;
11623 }
11624
11625 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11626 /// is to leave as a vector operation.
11627 static bool CheapToScalarize(Value *V, bool isConstant) {
11628   if (isa<ConstantAggregateZero>(V)) 
11629     return true;
11630   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11631     if (isConstant) return true;
11632     // If all elts are the same, we can extract.
11633     Constant *Op0 = C->getOperand(0);
11634     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11635       if (C->getOperand(i) != Op0)
11636         return false;
11637     return true;
11638   }
11639   Instruction *I = dyn_cast<Instruction>(V);
11640   if (!I) return false;
11641   
11642   // Insert element gets simplified to the inserted element or is deleted if
11643   // this is constant idx extract element and its a constant idx insertelt.
11644   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11645       isa<ConstantInt>(I->getOperand(2)))
11646     return true;
11647   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11648     return true;
11649   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11650     if (BO->hasOneUse() &&
11651         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11652          CheapToScalarize(BO->getOperand(1), isConstant)))
11653       return true;
11654   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11655     if (CI->hasOneUse() &&
11656         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11657          CheapToScalarize(CI->getOperand(1), isConstant)))
11658       return true;
11659   
11660   return false;
11661 }
11662
11663 /// Read and decode a shufflevector mask.
11664 ///
11665 /// It turns undef elements into values that are larger than the number of
11666 /// elements in the input.
11667 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11668   unsigned NElts = SVI->getType()->getNumElements();
11669   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11670     return std::vector<unsigned>(NElts, 0);
11671   if (isa<UndefValue>(SVI->getOperand(2)))
11672     return std::vector<unsigned>(NElts, 2*NElts);
11673
11674   std::vector<unsigned> Result;
11675   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11676   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11677     if (isa<UndefValue>(*i))
11678       Result.push_back(NElts*2);  // undef -> 8
11679     else
11680       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
11681   return Result;
11682 }
11683
11684 /// FindScalarElement - Given a vector and an element number, see if the scalar
11685 /// value is already around as a register, for example if it were inserted then
11686 /// extracted from the vector.
11687 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11688   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11689   const VectorType *PTy = cast<VectorType>(V->getType());
11690   unsigned Width = PTy->getNumElements();
11691   if (EltNo >= Width)  // Out of range access.
11692     return UndefValue::get(PTy->getElementType());
11693   
11694   if (isa<UndefValue>(V))
11695     return UndefValue::get(PTy->getElementType());
11696   else if (isa<ConstantAggregateZero>(V))
11697     return Constant::getNullValue(PTy->getElementType());
11698   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11699     return CP->getOperand(EltNo);
11700   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11701     // If this is an insert to a variable element, we don't know what it is.
11702     if (!isa<ConstantInt>(III->getOperand(2))) 
11703       return 0;
11704     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11705     
11706     // If this is an insert to the element we are looking for, return the
11707     // inserted value.
11708     if (EltNo == IIElt) 
11709       return III->getOperand(1);
11710     
11711     // Otherwise, the insertelement doesn't modify the value, recurse on its
11712     // vector input.
11713     return FindScalarElement(III->getOperand(0), EltNo);
11714   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11715     unsigned LHSWidth =
11716       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11717     unsigned InEl = getShuffleMask(SVI)[EltNo];
11718     if (InEl < LHSWidth)
11719       return FindScalarElement(SVI->getOperand(0), InEl);
11720     else if (InEl < LHSWidth*2)
11721       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
11722     else
11723       return UndefValue::get(PTy->getElementType());
11724   }
11725   
11726   // Otherwise, we don't know.
11727   return 0;
11728 }
11729
11730 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11731   // If vector val is undef, replace extract with scalar undef.
11732   if (isa<UndefValue>(EI.getOperand(0)))
11733     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11734
11735   // If vector val is constant 0, replace extract with scalar 0.
11736   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11737     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11738   
11739   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11740     // If vector val is constant with all elements the same, replace EI with
11741     // that element. When the elements are not identical, we cannot replace yet
11742     // (we do that below, but only when the index is constant).
11743     Constant *op0 = C->getOperand(0);
11744     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11745       if (C->getOperand(i) != op0) {
11746         op0 = 0; 
11747         break;
11748       }
11749     if (op0)
11750       return ReplaceInstUsesWith(EI, op0);
11751   }
11752   
11753   // If extracting a specified index from the vector, see if we can recursively
11754   // find a previously computed scalar that was inserted into the vector.
11755   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11756     unsigned IndexVal = IdxC->getZExtValue();
11757     unsigned VectorWidth = 
11758       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11759       
11760     // If this is extracting an invalid index, turn this into undef, to avoid
11761     // crashing the code below.
11762     if (IndexVal >= VectorWidth)
11763       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11764     
11765     // This instruction only demands the single element from the input vector.
11766     // If the input vector has a single use, simplify it based on this use
11767     // property.
11768     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11769       uint64_t UndefElts;
11770       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11771                                                 1 << IndexVal,
11772                                                 UndefElts)) {
11773         EI.setOperand(0, V);
11774         return &EI;
11775       }
11776     }
11777     
11778     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11779       return ReplaceInstUsesWith(EI, Elt);
11780     
11781     // If the this extractelement is directly using a bitcast from a vector of
11782     // the same number of elements, see if we can find the source element from
11783     // it.  In this case, we will end up needing to bitcast the scalars.
11784     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11785       if (const VectorType *VT = 
11786               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11787         if (VT->getNumElements() == VectorWidth)
11788           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11789             return new BitCastInst(Elt, EI.getType());
11790     }
11791   }
11792   
11793   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11794     if (I->hasOneUse()) {
11795       // Push extractelement into predecessor operation if legal and
11796       // profitable to do so
11797       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11798         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11799         if (CheapToScalarize(BO, isConstantElt)) {
11800           ExtractElementInst *newEI0 = 
11801             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11802                                    EI.getName()+".lhs");
11803           ExtractElementInst *newEI1 =
11804             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11805                                    EI.getName()+".rhs");
11806           InsertNewInstBefore(newEI0, EI);
11807           InsertNewInstBefore(newEI1, EI);
11808           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11809         }
11810       } else if (isa<LoadInst>(I)) {
11811         unsigned AS = 
11812           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11813         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11814                                          PointerType::get(EI.getType(), AS),EI);
11815         GetElementPtrInst *GEP =
11816           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11817         InsertNewInstBefore(GEP, EI);
11818         return new LoadInst(GEP);
11819       }
11820     }
11821     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11822       // Extracting the inserted element?
11823       if (IE->getOperand(2) == EI.getOperand(1))
11824         return ReplaceInstUsesWith(EI, IE->getOperand(1));
11825       // If the inserted and extracted elements are constants, they must not
11826       // be the same value, extract from the pre-inserted value instead.
11827       if (isa<Constant>(IE->getOperand(2)) &&
11828           isa<Constant>(EI.getOperand(1))) {
11829         AddUsesToWorkList(EI);
11830         EI.setOperand(0, IE->getOperand(0));
11831         return &EI;
11832       }
11833     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11834       // If this is extracting an element from a shufflevector, figure out where
11835       // it came from and extract from the appropriate input element instead.
11836       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11837         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11838         Value *Src;
11839         unsigned LHSWidth =
11840           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11841
11842         if (SrcIdx < LHSWidth)
11843           Src = SVI->getOperand(0);
11844         else if (SrcIdx < LHSWidth*2) {
11845           SrcIdx -= LHSWidth;
11846           Src = SVI->getOperand(1);
11847         } else {
11848           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11849         }
11850         return new ExtractElementInst(Src, SrcIdx);
11851       }
11852     }
11853   }
11854   return 0;
11855 }
11856
11857 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11858 /// elements from either LHS or RHS, return the shuffle mask and true. 
11859 /// Otherwise, return false.
11860 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11861                                          std::vector<Constant*> &Mask) {
11862   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11863          "Invalid CollectSingleShuffleElements");
11864   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11865
11866   if (isa<UndefValue>(V)) {
11867     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11868     return true;
11869   } else if (V == LHS) {
11870     for (unsigned i = 0; i != NumElts; ++i)
11871       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11872     return true;
11873   } else if (V == RHS) {
11874     for (unsigned i = 0; i != NumElts; ++i)
11875       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11876     return true;
11877   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11878     // If this is an insert of an extract from some other vector, include it.
11879     Value *VecOp    = IEI->getOperand(0);
11880     Value *ScalarOp = IEI->getOperand(1);
11881     Value *IdxOp    = IEI->getOperand(2);
11882     
11883     if (!isa<ConstantInt>(IdxOp))
11884       return false;
11885     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11886     
11887     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
11888       // Okay, we can handle this if the vector we are insertinting into is
11889       // transitively ok.
11890       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11891         // If so, update the mask to reflect the inserted undef.
11892         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11893         return true;
11894       }      
11895     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11896       if (isa<ConstantInt>(EI->getOperand(1)) &&
11897           EI->getOperand(0)->getType() == V->getType()) {
11898         unsigned ExtractedIdx =
11899           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11900         
11901         // This must be extracting from either LHS or RHS.
11902         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11903           // Okay, we can handle this if the vector we are insertinting into is
11904           // transitively ok.
11905           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11906             // If so, update the mask to reflect the inserted value.
11907             if (EI->getOperand(0) == LHS) {
11908               Mask[InsertedIdx % NumElts] = 
11909                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11910             } else {
11911               assert(EI->getOperand(0) == RHS);
11912               Mask[InsertedIdx % NumElts] = 
11913                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11914               
11915             }
11916             return true;
11917           }
11918         }
11919       }
11920     }
11921   }
11922   // TODO: Handle shufflevector here!
11923   
11924   return false;
11925 }
11926
11927 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11928 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
11929 /// that computes V and the LHS value of the shuffle.
11930 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11931                                      Value *&RHS) {
11932   assert(isa<VectorType>(V->getType()) && 
11933          (RHS == 0 || V->getType() == RHS->getType()) &&
11934          "Invalid shuffle!");
11935   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11936
11937   if (isa<UndefValue>(V)) {
11938     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11939     return V;
11940   } else if (isa<ConstantAggregateZero>(V)) {
11941     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11942     return V;
11943   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11944     // If this is an insert of an extract from some other vector, include it.
11945     Value *VecOp    = IEI->getOperand(0);
11946     Value *ScalarOp = IEI->getOperand(1);
11947     Value *IdxOp    = IEI->getOperand(2);
11948     
11949     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11950       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11951           EI->getOperand(0)->getType() == V->getType()) {
11952         unsigned ExtractedIdx =
11953           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11954         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11955         
11956         // Either the extracted from or inserted into vector must be RHSVec,
11957         // otherwise we'd end up with a shuffle of three inputs.
11958         if (EI->getOperand(0) == RHS || RHS == 0) {
11959           RHS = EI->getOperand(0);
11960           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11961           Mask[InsertedIdx % NumElts] = 
11962             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11963           return V;
11964         }
11965         
11966         if (VecOp == RHS) {
11967           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11968           // Everything but the extracted element is replaced with the RHS.
11969           for (unsigned i = 0; i != NumElts; ++i) {
11970             if (i != InsertedIdx)
11971               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11972           }
11973           return V;
11974         }
11975         
11976         // If this insertelement is a chain that comes from exactly these two
11977         // vectors, return the vector and the effective shuffle.
11978         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11979           return EI->getOperand(0);
11980         
11981       }
11982     }
11983   }
11984   // TODO: Handle shufflevector here!
11985   
11986   // Otherwise, can't do anything fancy.  Return an identity vector.
11987   for (unsigned i = 0; i != NumElts; ++i)
11988     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11989   return V;
11990 }
11991
11992 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11993   Value *VecOp    = IE.getOperand(0);
11994   Value *ScalarOp = IE.getOperand(1);
11995   Value *IdxOp    = IE.getOperand(2);
11996   
11997   // Inserting an undef or into an undefined place, remove this.
11998   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11999     ReplaceInstUsesWith(IE, VecOp);
12000   
12001   // If the inserted element was extracted from some other vector, and if the 
12002   // indexes are constant, try to turn this into a shufflevector operation.
12003   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12004     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12005         EI->getOperand(0)->getType() == IE.getType()) {
12006       unsigned NumVectorElts = IE.getType()->getNumElements();
12007       unsigned ExtractedIdx =
12008         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12009       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12010       
12011       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12012         return ReplaceInstUsesWith(IE, VecOp);
12013       
12014       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12015         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12016       
12017       // If we are extracting a value from a vector, then inserting it right
12018       // back into the same place, just use the input vector.
12019       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12020         return ReplaceInstUsesWith(IE, VecOp);      
12021       
12022       // We could theoretically do this for ANY input.  However, doing so could
12023       // turn chains of insertelement instructions into a chain of shufflevector
12024       // instructions, and right now we do not merge shufflevectors.  As such,
12025       // only do this in a situation where it is clear that there is benefit.
12026       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12027         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12028         // the values of VecOp, except then one read from EIOp0.
12029         // Build a new shuffle mask.
12030         std::vector<Constant*> Mask;
12031         if (isa<UndefValue>(VecOp))
12032           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12033         else {
12034           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12035           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12036                                                        NumVectorElts));
12037         } 
12038         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12039         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12040                                      ConstantVector::get(Mask));
12041       }
12042       
12043       // If this insertelement isn't used by some other insertelement, turn it
12044       // (and any insertelements it points to), into one big shuffle.
12045       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12046         std::vector<Constant*> Mask;
12047         Value *RHS = 0;
12048         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12049         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12050         // We now have a shuffle of LHS, RHS, Mask.
12051         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12052       }
12053     }
12054   }
12055
12056   return 0;
12057 }
12058
12059
12060 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12061   Value *LHS = SVI.getOperand(0);
12062   Value *RHS = SVI.getOperand(1);
12063   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12064
12065   bool MadeChange = false;
12066
12067   // Undefined shuffle mask -> undefined value.
12068   if (isa<UndefValue>(SVI.getOperand(2)))
12069     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12070
12071   uint64_t UndefElts;
12072   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12073
12074   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12075     return 0;
12076
12077   uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
12078   if (VWidth <= 64 &&
12079       SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12080     LHS = SVI.getOperand(0);
12081     RHS = SVI.getOperand(1);
12082     MadeChange = true;
12083   }
12084   
12085   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12086   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12087   if (LHS == RHS || isa<UndefValue>(LHS)) {
12088     if (isa<UndefValue>(LHS) && LHS == RHS) {
12089       // shuffle(undef,undef,mask) -> undef.
12090       return ReplaceInstUsesWith(SVI, LHS);
12091     }
12092     
12093     // Remap any references to RHS to use LHS.
12094     std::vector<Constant*> Elts;
12095     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12096       if (Mask[i] >= 2*e)
12097         Elts.push_back(UndefValue::get(Type::Int32Ty));
12098       else {
12099         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12100             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12101           Mask[i] = 2*e;     // Turn into undef.
12102           Elts.push_back(UndefValue::get(Type::Int32Ty));
12103         } else {
12104           Mask[i] = Mask[i] % e;  // Force to LHS.
12105           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12106         }
12107       }
12108     }
12109     SVI.setOperand(0, SVI.getOperand(1));
12110     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12111     SVI.setOperand(2, ConstantVector::get(Elts));
12112     LHS = SVI.getOperand(0);
12113     RHS = SVI.getOperand(1);
12114     MadeChange = true;
12115   }
12116   
12117   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12118   bool isLHSID = true, isRHSID = true;
12119     
12120   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12121     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12122     // Is this an identity shuffle of the LHS value?
12123     isLHSID &= (Mask[i] == i);
12124       
12125     // Is this an identity shuffle of the RHS value?
12126     isRHSID &= (Mask[i]-e == i);
12127   }
12128
12129   // Eliminate identity shuffles.
12130   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12131   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12132   
12133   // If the LHS is a shufflevector itself, see if we can combine it with this
12134   // one without producing an unusual shuffle.  Here we are really conservative:
12135   // we are absolutely afraid of producing a shuffle mask not in the input
12136   // program, because the code gen may not be smart enough to turn a merged
12137   // shuffle into two specific shuffles: it may produce worse code.  As such,
12138   // we only merge two shuffles if the result is one of the two input shuffle
12139   // masks.  In this case, merging the shuffles just removes one instruction,
12140   // which we know is safe.  This is good for things like turning:
12141   // (splat(splat)) -> splat.
12142   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12143     if (isa<UndefValue>(RHS)) {
12144       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12145
12146       std::vector<unsigned> NewMask;
12147       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12148         if (Mask[i] >= 2*e)
12149           NewMask.push_back(2*e);
12150         else
12151           NewMask.push_back(LHSMask[Mask[i]]);
12152       
12153       // If the result mask is equal to the src shuffle or this shuffle mask, do
12154       // the replacement.
12155       if (NewMask == LHSMask || NewMask == Mask) {
12156         unsigned LHSInNElts =
12157           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12158         std::vector<Constant*> Elts;
12159         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12160           if (NewMask[i] >= LHSInNElts*2) {
12161             Elts.push_back(UndefValue::get(Type::Int32Ty));
12162           } else {
12163             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12164           }
12165         }
12166         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12167                                      LHSSVI->getOperand(1),
12168                                      ConstantVector::get(Elts));
12169       }
12170     }
12171   }
12172
12173   return MadeChange ? &SVI : 0;
12174 }
12175
12176
12177
12178
12179 /// TryToSinkInstruction - Try to move the specified instruction from its
12180 /// current block into the beginning of DestBlock, which can only happen if it's
12181 /// safe to move the instruction past all of the instructions between it and the
12182 /// end of its block.
12183 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12184   assert(I->hasOneUse() && "Invariants didn't hold!");
12185
12186   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12187   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12188     return false;
12189
12190   // Do not sink alloca instructions out of the entry block.
12191   if (isa<AllocaInst>(I) && I->getParent() ==
12192         &DestBlock->getParent()->getEntryBlock())
12193     return false;
12194
12195   // We can only sink load instructions if there is nothing between the load and
12196   // the end of block that could change the value.
12197   if (I->mayReadFromMemory()) {
12198     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12199          Scan != E; ++Scan)
12200       if (Scan->mayWriteToMemory())
12201         return false;
12202   }
12203
12204   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12205
12206   I->moveBefore(InsertPos);
12207   ++NumSunkInst;
12208   return true;
12209 }
12210
12211
12212 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12213 /// all reachable code to the worklist.
12214 ///
12215 /// This has a couple of tricks to make the code faster and more powerful.  In
12216 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12217 /// them to the worklist (this significantly speeds up instcombine on code where
12218 /// many instructions are dead or constant).  Additionally, if we find a branch
12219 /// whose condition is a known constant, we only visit the reachable successors.
12220 ///
12221 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12222                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12223                                        InstCombiner &IC,
12224                                        const TargetData *TD) {
12225   SmallVector<BasicBlock*, 256> Worklist;
12226   Worklist.push_back(BB);
12227
12228   while (!Worklist.empty()) {
12229     BB = Worklist.back();
12230     Worklist.pop_back();
12231     
12232     // We have now visited this block!  If we've already been here, ignore it.
12233     if (!Visited.insert(BB)) continue;
12234
12235     DbgInfoIntrinsic *DBI_Prev = NULL;
12236     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12237       Instruction *Inst = BBI++;
12238       
12239       // DCE instruction if trivially dead.
12240       if (isInstructionTriviallyDead(Inst)) {
12241         ++NumDeadInst;
12242         DOUT << "IC: DCE: " << *Inst;
12243         Inst->eraseFromParent();
12244         continue;
12245       }
12246       
12247       // ConstantProp instruction if trivially constant.
12248       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12249         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12250         Inst->replaceAllUsesWith(C);
12251         ++NumConstProp;
12252         Inst->eraseFromParent();
12253         continue;
12254       }
12255      
12256       // If there are two consecutive llvm.dbg.stoppoint calls then
12257       // it is likely that the optimizer deleted code in between these
12258       // two intrinsics. 
12259       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12260       if (DBI_Next) {
12261         if (DBI_Prev
12262             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12263             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12264           IC.RemoveFromWorkList(DBI_Prev);
12265           DBI_Prev->eraseFromParent();
12266         }
12267         DBI_Prev = DBI_Next;
12268       }
12269
12270       IC.AddToWorkList(Inst);
12271     }
12272
12273     // Recursively visit successors.  If this is a branch or switch on a
12274     // constant, only visit the reachable successor.
12275     TerminatorInst *TI = BB->getTerminator();
12276     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12277       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12278         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12279         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12280         Worklist.push_back(ReachableBB);
12281         continue;
12282       }
12283     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12284       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12285         // See if this is an explicit destination.
12286         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12287           if (SI->getCaseValue(i) == Cond) {
12288             BasicBlock *ReachableBB = SI->getSuccessor(i);
12289             Worklist.push_back(ReachableBB);
12290             continue;
12291           }
12292         
12293         // Otherwise it is the default destination.
12294         Worklist.push_back(SI->getSuccessor(0));
12295         continue;
12296       }
12297     }
12298     
12299     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12300       Worklist.push_back(TI->getSuccessor(i));
12301   }
12302 }
12303
12304 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12305   bool Changed = false;
12306   TD = &getAnalysis<TargetData>();
12307   
12308   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12309              << F.getNameStr() << "\n");
12310
12311   {
12312     // Do a depth-first traversal of the function, populate the worklist with
12313     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12314     // track of which blocks we visit.
12315     SmallPtrSet<BasicBlock*, 64> Visited;
12316     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12317
12318     // Do a quick scan over the function.  If we find any blocks that are
12319     // unreachable, remove any instructions inside of them.  This prevents
12320     // the instcombine code from having to deal with some bad special cases.
12321     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12322       if (!Visited.count(BB)) {
12323         Instruction *Term = BB->getTerminator();
12324         while (Term != BB->begin()) {   // Remove instrs bottom-up
12325           BasicBlock::iterator I = Term; --I;
12326
12327           DOUT << "IC: DCE: " << *I;
12328           ++NumDeadInst;
12329
12330           if (!I->use_empty())
12331             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12332           I->eraseFromParent();
12333           Changed = true;
12334         }
12335       }
12336   }
12337
12338   while (!Worklist.empty()) {
12339     Instruction *I = RemoveOneFromWorkList();
12340     if (I == 0) continue;  // skip null values.
12341
12342     // Check to see if we can DCE the instruction.
12343     if (isInstructionTriviallyDead(I)) {
12344       // Add operands to the worklist.
12345       if (I->getNumOperands() < 4)
12346         AddUsesToWorkList(*I);
12347       ++NumDeadInst;
12348
12349       DOUT << "IC: DCE: " << *I;
12350
12351       I->eraseFromParent();
12352       RemoveFromWorkList(I);
12353       Changed = true;
12354       continue;
12355     }
12356
12357     // Instruction isn't dead, see if we can constant propagate it.
12358     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12359       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12360
12361       // Add operands to the worklist.
12362       AddUsesToWorkList(*I);
12363       ReplaceInstUsesWith(*I, C);
12364
12365       ++NumConstProp;
12366       I->eraseFromParent();
12367       RemoveFromWorkList(I);
12368       Changed = true;
12369       continue;
12370     }
12371
12372     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12373       // See if we can constant fold its operands.
12374       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12375         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12376           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12377             if (NewC != CE) {
12378               i->set(NewC);
12379               Changed = true;
12380             }
12381     }
12382
12383     // See if we can trivially sink this instruction to a successor basic block.
12384     if (I->hasOneUse()) {
12385       BasicBlock *BB = I->getParent();
12386       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12387       if (UserParent != BB) {
12388         bool UserIsSuccessor = false;
12389         // See if the user is one of our successors.
12390         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12391           if (*SI == UserParent) {
12392             UserIsSuccessor = true;
12393             break;
12394           }
12395
12396         // If the user is one of our immediate successors, and if that successor
12397         // only has us as a predecessors (we'd have to split the critical edge
12398         // otherwise), we can keep going.
12399         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12400             next(pred_begin(UserParent)) == pred_end(UserParent))
12401           // Okay, the CFG is simple enough, try to sink this instruction.
12402           Changed |= TryToSinkInstruction(I, UserParent);
12403       }
12404     }
12405
12406     // Now that we have an instruction, try combining it to simplify it...
12407 #ifndef NDEBUG
12408     std::string OrigI;
12409 #endif
12410     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12411     if (Instruction *Result = visit(*I)) {
12412       ++NumCombined;
12413       // Should we replace the old instruction with a new one?
12414       if (Result != I) {
12415         DOUT << "IC: Old = " << *I
12416              << "    New = " << *Result;
12417
12418         // Everything uses the new instruction now.
12419         I->replaceAllUsesWith(Result);
12420
12421         // Push the new instruction and any users onto the worklist.
12422         AddToWorkList(Result);
12423         AddUsersToWorkList(*Result);
12424
12425         // Move the name to the new instruction first.
12426         Result->takeName(I);
12427
12428         // Insert the new instruction into the basic block...
12429         BasicBlock *InstParent = I->getParent();
12430         BasicBlock::iterator InsertPos = I;
12431
12432         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12433           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12434             ++InsertPos;
12435
12436         InstParent->getInstList().insert(InsertPos, Result);
12437
12438         // Make sure that we reprocess all operands now that we reduced their
12439         // use counts.
12440         AddUsesToWorkList(*I);
12441
12442         // Instructions can end up on the worklist more than once.  Make sure
12443         // we do not process an instruction that has been deleted.
12444         RemoveFromWorkList(I);
12445
12446         // Erase the old instruction.
12447         InstParent->getInstList().erase(I);
12448       } else {
12449 #ifndef NDEBUG
12450         DOUT << "IC: Mod = " << OrigI
12451              << "    New = " << *I;
12452 #endif
12453
12454         // If the instruction was modified, it's possible that it is now dead.
12455         // if so, remove it.
12456         if (isInstructionTriviallyDead(I)) {
12457           // Make sure we process all operands now that we are reducing their
12458           // use counts.
12459           AddUsesToWorkList(*I);
12460
12461           // Instructions may end up in the worklist more than once.  Erase all
12462           // occurrences of this instruction.
12463           RemoveFromWorkList(I);
12464           I->eraseFromParent();
12465         } else {
12466           AddToWorkList(I);
12467           AddUsersToWorkList(*I);
12468         }
12469       }
12470       Changed = true;
12471     }
12472   }
12473
12474   assert(WorklistMap.empty() && "Worklist empty, but map not?");
12475     
12476   // Do an explicit clear, this shrinks the map if needed.
12477   WorklistMap.clear();
12478   return Changed;
12479 }
12480
12481
12482 bool InstCombiner::runOnFunction(Function &F) {
12483   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12484   
12485   bool EverMadeChange = false;
12486
12487   // Iterate while there is work to do.
12488   unsigned Iteration = 0;
12489   while (DoOneIteration(F, Iteration++))
12490     EverMadeChange = true;
12491   return EverMadeChange;
12492 }
12493
12494 FunctionPass *llvm::createInstructionCombiningPass() {
12495   return new InstCombiner();
12496 }