two changes:
[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     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
254
255
256   public:
257     // InsertNewInstBefore - insert an instruction New before instruction Old
258     // in the program.  Add the new instruction to the worklist.
259     //
260     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
261       assert(New && New->getParent() == 0 &&
262              "New instruction already inserted into a basic block!");
263       BasicBlock *BB = Old.getParent();
264       BB->getInstList().insert(&Old, New);  // Insert inst
265       AddToWorkList(New);
266       return New;
267     }
268
269     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
270     /// This also adds the cast to the worklist.  Finally, this returns the
271     /// cast.
272     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
273                             Instruction &Pos) {
274       if (V->getType() == Ty) return V;
275
276       if (Constant *CV = dyn_cast<Constant>(V))
277         return ConstantExpr::getCast(opc, CV, Ty);
278       
279       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
280       AddToWorkList(C);
281       return C;
282     }
283         
284     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
285       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
286     }
287
288
289     // ReplaceInstUsesWith - This method is to be used when an instruction is
290     // found to be dead, replacable with another preexisting expression.  Here
291     // we add all uses of I to the worklist, replace all uses of I with the new
292     // value, then return I, so that the inst combiner will know that I was
293     // modified.
294     //
295     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
296       AddUsersToWorkList(I);         // Add all modified instrs to worklist
297       if (&I != V) {
298         I.replaceAllUsesWith(V);
299         return &I;
300       } else {
301         // If we are replacing the instruction with itself, this must be in a
302         // segment of unreachable code, so just clobber the instruction.
303         I.replaceAllUsesWith(UndefValue::get(I.getType()));
304         return &I;
305       }
306     }
307
308     // EraseInstFromFunction - When dealing with an instruction that has side
309     // effects or produces a void value, we can't rely on DCE to delete the
310     // instruction.  Instead, visit methods should return the value returned by
311     // this function.
312     Instruction *EraseInstFromFunction(Instruction &I) {
313       assert(I.use_empty() && "Cannot erase instruction that is used!");
314       AddUsesToWorkList(I);
315       RemoveFromWorkList(&I);
316       I.eraseFromParent();
317       return 0;  // Don't do anything with FI
318     }
319         
320     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
321                            APInt &KnownOne, unsigned Depth = 0) const {
322       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
323     }
324     
325     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
326                            unsigned Depth = 0) const {
327       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
328     }
329     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
330       return llvm::ComputeNumSignBits(Op, TD, Depth);
331     }
332
333   private:
334
335     /// SimplifyCommutative - This performs a few simplifications for 
336     /// commutative operators.
337     bool SimplifyCommutative(BinaryOperator &I);
338
339     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
340     /// most-complex to least-complex order.
341     bool SimplifyCompare(CmpInst &I);
342
343     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
344     /// based on the demanded bits.
345     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
346                                    APInt& KnownZero, APInt& KnownOne,
347                                    unsigned Depth);
348     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
349                               APInt& KnownZero, APInt& KnownOne,
350                               unsigned Depth=0);
351         
352     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
353     /// SimplifyDemandedBits knows about.  See if the instruction has any
354     /// properties that allow us to simplify its operands.
355     bool SimplifyDemandedInstructionBits(Instruction &Inst);
356         
357     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
358                                       APInt& UndefElts, unsigned Depth = 0);
359       
360     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
361     // PHI node as operand #0, see if we can fold the instruction into the PHI
362     // (which is only possible if all operands to the PHI are constants).
363     Instruction *FoldOpIntoPhi(Instruction &I);
364
365     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
366     // operator and they all are only used by the PHI, PHI together their
367     // inputs, and do the operation once, to the result of the PHI.
368     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
369     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
370     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
371
372     
373     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
374                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
375     
376     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
377                               bool isSub, Instruction &I);
378     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
379                                  bool isSigned, bool Inside, Instruction &IB);
380     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
381     Instruction *MatchBSwap(BinaryOperator &I);
382     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
383     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
384     Instruction *SimplifyMemSet(MemSetInst *MI);
385
386
387     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
388
389     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
390                                     unsigned CastOpc, int &NumCastsRemoved);
391     unsigned GetOrEnforceKnownAlignment(Value *V,
392                                         unsigned PrefAlign = 0);
393
394   };
395 }
396
397 char InstCombiner::ID = 0;
398 static RegisterPass<InstCombiner>
399 X("instcombine", "Combine redundant instructions");
400
401 // getComplexity:  Assign a complexity or rank value to LLVM Values...
402 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
403 static unsigned getComplexity(Value *V) {
404   if (isa<Instruction>(V)) {
405     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
406       return 3;
407     return 4;
408   }
409   if (isa<Argument>(V)) return 3;
410   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
411 }
412
413 // isOnlyUse - Return true if this instruction will be deleted if we stop using
414 // it.
415 static bool isOnlyUse(Value *V) {
416   return V->hasOneUse() || isa<Constant>(V);
417 }
418
419 // getPromotedType - Return the specified type promoted as it would be to pass
420 // though a va_arg area...
421 static const Type *getPromotedType(const Type *Ty) {
422   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
423     if (ITy->getBitWidth() < 32)
424       return Type::Int32Ty;
425   }
426   return Ty;
427 }
428
429 /// getBitCastOperand - If the specified operand is a CastInst, a constant
430 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
431 /// operand value, otherwise return null.
432 static Value *getBitCastOperand(Value *V) {
433   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
434     // BitCastInst?
435     return I->getOperand(0);
436   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
437     // GetElementPtrInst?
438     if (GEP->hasAllZeroIndices())
439       return GEP->getOperand(0);
440   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
441     if (CE->getOpcode() == Instruction::BitCast)
442       // BitCast ConstantExp?
443       return CE->getOperand(0);
444     else if (CE->getOpcode() == Instruction::GetElementPtr) {
445       // GetElementPtr ConstantExp?
446       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
447            I != E; ++I) {
448         ConstantInt *CI = dyn_cast<ConstantInt>(I);
449         if (!CI || !CI->isZero())
450           // Any non-zero indices? Not cast-like.
451           return 0;
452       }
453       // All-zero indices? This is just like casting.
454       return CE->getOperand(0);
455     }
456   }
457   return 0;
458 }
459
460 /// This function is a wrapper around CastInst::isEliminableCastPair. It
461 /// simply extracts arguments and returns what that function returns.
462 static Instruction::CastOps 
463 isEliminableCastPair(
464   const CastInst *CI, ///< The first cast instruction
465   unsigned opcode,       ///< The opcode of the second cast instruction
466   const Type *DstTy,     ///< The target type for the second cast instruction
467   TargetData *TD         ///< The target data for pointer size
468 ) {
469   
470   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
471   const Type *MidTy = CI->getType();                  // B from above
472
473   // Get the opcodes of the two Cast instructions
474   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
475   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
476
477   return Instruction::CastOps(
478       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
479                                      DstTy, TD->getIntPtrType()));
480 }
481
482 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
483 /// in any code being generated.  It does not require codegen if V is simple
484 /// enough or if the cast can be folded into other casts.
485 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
486                               const Type *Ty, TargetData *TD) {
487   if (V->getType() == Ty || isa<Constant>(V)) return false;
488   
489   // If this is another cast that can be eliminated, it isn't codegen either.
490   if (const CastInst *CI = dyn_cast<CastInst>(V))
491     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
492       return false;
493   return true;
494 }
495
496 // SimplifyCommutative - This performs a few simplifications for commutative
497 // operators:
498 //
499 //  1. Order operands such that they are listed from right (least complex) to
500 //     left (most complex).  This puts constants before unary operators before
501 //     binary operators.
502 //
503 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
504 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
505 //
506 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
507   bool Changed = false;
508   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
509     Changed = !I.swapOperands();
510
511   if (!I.isAssociative()) return Changed;
512   Instruction::BinaryOps Opcode = I.getOpcode();
513   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
514     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
515       if (isa<Constant>(I.getOperand(1))) {
516         Constant *Folded = ConstantExpr::get(I.getOpcode(),
517                                              cast<Constant>(I.getOperand(1)),
518                                              cast<Constant>(Op->getOperand(1)));
519         I.setOperand(0, Op->getOperand(0));
520         I.setOperand(1, Folded);
521         return true;
522       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
523         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
524             isOnlyUse(Op) && isOnlyUse(Op1)) {
525           Constant *C1 = cast<Constant>(Op->getOperand(1));
526           Constant *C2 = cast<Constant>(Op1->getOperand(1));
527
528           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
529           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
530           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
531                                                     Op1->getOperand(0),
532                                                     Op1->getName(), &I);
533           AddToWorkList(New);
534           I.setOperand(0, New);
535           I.setOperand(1, Folded);
536           return true;
537         }
538     }
539   return Changed;
540 }
541
542 /// SimplifyCompare - For a CmpInst this function just orders the operands
543 /// so that theyare listed from right (least complex) to left (most complex).
544 /// This puts constants before unary operators before binary operators.
545 bool InstCombiner::SimplifyCompare(CmpInst &I) {
546   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
547     return false;
548   I.swapOperands();
549   // Compare instructions are not associative so there's nothing else we can do.
550   return true;
551 }
552
553 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
554 // if the LHS is a constant zero (which is the 'negate' form).
555 //
556 static inline Value *dyn_castNegVal(Value *V) {
557   if (BinaryOperator::isNeg(V))
558     return BinaryOperator::getNegArgument(V);
559
560   // Constants can be considered to be negated values if they can be folded.
561   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
562     return ConstantExpr::getNeg(C);
563
564   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
565     if (C->getType()->getElementType()->isInteger())
566       return ConstantExpr::getNeg(C);
567
568   return 0;
569 }
570
571 static inline Value *dyn_castNotVal(Value *V) {
572   if (BinaryOperator::isNot(V))
573     return BinaryOperator::getNotArgument(V);
574
575   // Constants can be considered to be not'ed values...
576   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
577     return ConstantInt::get(~C->getValue());
578   return 0;
579 }
580
581 // dyn_castFoldableMul - If this value is a multiply that can be folded into
582 // other computations (because it has a constant operand), return the
583 // non-constant operand of the multiply, and set CST to point to the multiplier.
584 // Otherwise, return null.
585 //
586 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
587   if (V->hasOneUse() && V->getType()->isInteger())
588     if (Instruction *I = dyn_cast<Instruction>(V)) {
589       if (I->getOpcode() == Instruction::Mul)
590         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
591           return I->getOperand(0);
592       if (I->getOpcode() == Instruction::Shl)
593         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
594           // The multiplier is really 1 << CST.
595           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
596           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
597           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
598           return I->getOperand(0);
599         }
600     }
601   return 0;
602 }
603
604 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
605 /// expression, return it.
606 static User *dyn_castGetElementPtr(Value *V) {
607   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
608   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
609     if (CE->getOpcode() == Instruction::GetElementPtr)
610       return cast<User>(V);
611   return false;
612 }
613
614 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
615 /// opcode value. Otherwise return UserOp1.
616 static unsigned getOpcode(const Value *V) {
617   if (const Instruction *I = dyn_cast<Instruction>(V))
618     return I->getOpcode();
619   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
620     return CE->getOpcode();
621   // Use UserOp1 to mean there's no opcode.
622   return Instruction::UserOp1;
623 }
624
625 /// AddOne - Add one to a ConstantInt
626 static ConstantInt *AddOne(ConstantInt *C) {
627   APInt Val(C->getValue());
628   return ConstantInt::get(++Val);
629 }
630 /// SubOne - Subtract one from a ConstantInt
631 static ConstantInt *SubOne(ConstantInt *C) {
632   APInt Val(C->getValue());
633   return ConstantInt::get(--Val);
634 }
635 /// Add - Add two ConstantInts together
636 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
637   return ConstantInt::get(C1->getValue() + C2->getValue());
638 }
639 /// And - Bitwise AND two ConstantInts together
640 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
641   return ConstantInt::get(C1->getValue() & C2->getValue());
642 }
643 /// Subtract - Subtract one ConstantInt from another
644 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
645   return ConstantInt::get(C1->getValue() - C2->getValue());
646 }
647 /// Multiply - Multiply two ConstantInts together
648 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
649   return ConstantInt::get(C1->getValue() * C2->getValue());
650 }
651 /// MultiplyOverflows - True if the multiply can not be expressed in an int
652 /// this size.
653 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
654   uint32_t W = C1->getBitWidth();
655   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
656   if (sign) {
657     LHSExt.sext(W * 2);
658     RHSExt.sext(W * 2);
659   } else {
660     LHSExt.zext(W * 2);
661     RHSExt.zext(W * 2);
662   }
663
664   APInt MulExt = LHSExt * RHSExt;
665
666   if (sign) {
667     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
668     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
669     return MulExt.slt(Min) || MulExt.sgt(Max);
670   } else 
671     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
672 }
673
674
675 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
676 /// specified instruction is a constant integer.  If so, check to see if there
677 /// are any bits set in the constant that are not demanded.  If so, shrink the
678 /// constant and return true.
679 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
680                                    APInt Demanded) {
681   assert(I && "No instruction?");
682   assert(OpNo < I->getNumOperands() && "Operand index too large");
683
684   // If the operand is not a constant integer, nothing to do.
685   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
686   if (!OpC) return false;
687
688   // If there are no bits set that aren't demanded, nothing to do.
689   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
690   if ((~Demanded & OpC->getValue()) == 0)
691     return false;
692
693   // This instruction is producing bits that are not demanded. Shrink the RHS.
694   Demanded &= OpC->getValue();
695   I->setOperand(OpNo, ConstantInt::get(Demanded));
696   return true;
697 }
698
699 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
700 // set of known zero and one bits, compute the maximum and minimum values that
701 // could have the specified known zero and known one bits, returning them in
702 // min/max.
703 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
704                                                    const APInt& KnownZero,
705                                                    const APInt& KnownOne,
706                                                    APInt& Min, APInt& Max) {
707   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
708   assert(KnownZero.getBitWidth() == BitWidth && 
709          KnownOne.getBitWidth() == BitWidth &&
710          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
711          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
712   APInt UnknownBits = ~(KnownZero|KnownOne);
713
714   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
715   // bit if it is unknown.
716   Min = KnownOne;
717   Max = KnownOne|UnknownBits;
718   
719   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
720     Min.set(BitWidth-1);
721     Max.clear(BitWidth-1);
722   }
723 }
724
725 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
726 // a set of known zero and one bits, compute the maximum and minimum values that
727 // could have the specified known zero and known one bits, returning them in
728 // min/max.
729 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
730                                                      const APInt &KnownZero,
731                                                      const APInt &KnownOne,
732                                                      APInt &Min, APInt &Max) {
733   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
734   assert(KnownZero.getBitWidth() == BitWidth && 
735          KnownOne.getBitWidth() == BitWidth &&
736          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
737          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
738   APInt UnknownBits = ~(KnownZero|KnownOne);
739   
740   // The minimum value is when the unknown bits are all zeros.
741   Min = KnownOne;
742   // The maximum value is when the unknown bits are all ones.
743   Max = KnownOne|UnknownBits;
744 }
745
746 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
747 /// SimplifyDemandedBits knows about.  See if the instruction has any
748 /// properties that allow us to simplify its operands.
749 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
750   unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
751   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
752   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
753   
754   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
755                                      KnownZero, KnownOne, 0);
756   if (V == 0) return false;
757   if (V == &Inst) return true;
758   ReplaceInstUsesWith(Inst, V);
759   return true;
760 }
761
762 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
763 /// specified instruction operand if possible, updating it in place.  It returns
764 /// true if it made any change and false otherwise.
765 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
766                                         APInt &KnownZero, APInt &KnownOne,
767                                         unsigned Depth) {
768   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
769                                           KnownZero, KnownOne, Depth);
770   if (NewVal == 0) return false;
771   U.set(NewVal);
772   return true;
773 }
774
775
776 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
777 /// value based on the demanded bits.  When this function is called, it is known
778 /// that only the bits set in DemandedMask of the result of V are ever used
779 /// downstream. Consequently, depending on the mask and V, it may be possible
780 /// to replace V with a constant or one of its operands. In such cases, this
781 /// function does the replacement and returns true. In all other cases, it
782 /// returns false after analyzing the expression and setting KnownOne and known
783 /// to be one in the expression.  KnownZero contains all the bits that are known
784 /// to be zero in the expression. These are provided to potentially allow the
785 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
786 /// the expression. KnownOne and KnownZero always follow the invariant that 
787 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
788 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
789 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
790 /// and KnownOne must all be the same.
791 ///
792 /// This returns null if it did not change anything and it permits no
793 /// simplification.  This returns V itself if it did some simplification of V's
794 /// operands based on the information about what bits are demanded. This returns
795 /// some other non-null value if it found out that V is equal to another value
796 /// in the context where the specified bits are demanded, but not for all users.
797 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
798                                              APInt &KnownZero, APInt &KnownOne,
799                                              unsigned Depth) {
800   assert(V != 0 && "Null pointer of Value???");
801   assert(Depth <= 6 && "Limit Search Depth");
802   uint32_t BitWidth = DemandedMask.getBitWidth();
803   const IntegerType *VTy = cast<IntegerType>(V->getType());
804   assert(VTy->getBitWidth() == BitWidth && 
805          KnownZero.getBitWidth() == BitWidth && 
806          KnownOne.getBitWidth() == BitWidth &&
807          "Value *V, DemandedMask, KnownZero and KnownOne \
808           must have same BitWidth");
809   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
810     // We know all of the bits for a constant!
811     KnownOne = CI->getValue() & DemandedMask;
812     KnownZero = ~KnownOne & DemandedMask;
813     return 0;
814   }
815   
816   KnownZero.clear();
817   KnownOne.clear();
818   if (DemandedMask == 0) {   // Not demanding any bits from V.
819     if (isa<UndefValue>(V))
820       return 0;
821     return UndefValue::get(VTy);
822   }
823   
824   if (Depth == 6)        // Limit search depth.
825     return 0;
826   
827   Instruction *I = dyn_cast<Instruction>(V);
828   if (!I) return 0;        // Only analyze instructions.
829   
830   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
831   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
832
833   // If there are multiple uses of this value and we aren't at the root, then
834   // we can't do any simplifications of the operands, because DemandedMask
835   // only reflects the bits demanded by *one* of the users.
836   if (Depth != 0 && !I->hasOneUse()) {
837     // Despite the fact that we can't simplify this instruction in all User's
838     // context, we can at least compute the knownzero/knownone bits, and we can
839     // do simplifications that apply to *just* the one user if we know that
840     // this instruction has a simpler value in that context.
841     if (I->getOpcode() == Instruction::And) {
842       // If either the LHS or the RHS are Zero, the result is zero.
843       ComputeMaskedBits(I->getOperand(1), DemandedMask,
844                         RHSKnownZero, RHSKnownOne, Depth+1);
845       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
846                         LHSKnownZero, LHSKnownOne, Depth+1);
847       
848       // If all of the demanded bits are known 1 on one side, return the other.
849       // These bits cannot contribute to the result of the 'and' in this
850       // context.
851       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
852           (DemandedMask & ~LHSKnownZero))
853         return I->getOperand(0);
854       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
855           (DemandedMask & ~RHSKnownZero))
856         return I->getOperand(1);
857       
858       // If all of the demanded bits in the inputs are known zeros, return zero.
859       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
860         return Constant::getNullValue(VTy);
861       
862     } else if (I->getOpcode() == Instruction::Or) {
863       // We can simplify (X|Y) -> X or Y in the user's context if we know that
864       // only bits from X or Y are demanded.
865       
866       // If either the LHS or the RHS are One, the result is One.
867       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
868                         RHSKnownZero, RHSKnownOne, Depth+1);
869       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
870                         LHSKnownZero, LHSKnownOne, Depth+1);
871       
872       // If all of the demanded bits are known zero on one side, return the
873       // other.  These bits cannot contribute to the result of the 'or' in this
874       // context.
875       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
876           (DemandedMask & ~LHSKnownOne))
877         return I->getOperand(0);
878       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
879           (DemandedMask & ~RHSKnownOne))
880         return I->getOperand(1);
881       
882       // If all of the potentially set bits on one side are known to be set on
883       // the other side, just use the 'other' side.
884       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
885           (DemandedMask & (~RHSKnownZero)))
886         return I->getOperand(0);
887       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
888           (DemandedMask & (~LHSKnownZero)))
889         return I->getOperand(1);
890     }
891     
892     // Compute the KnownZero/KnownOne bits to simplify things downstream.
893     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
894     return 0;
895   }
896   
897   // If this is the root being simplified, allow it to have multiple uses,
898   // just set the DemandedMask to all bits so that we can try to simplify the
899   // operands.  This allows visitTruncInst (for example) to simplify the
900   // operand of a trunc without duplicating all the logic below.
901   if (Depth == 0 && !V->hasOneUse())
902     DemandedMask = APInt::getAllOnesValue(BitWidth);
903   
904   switch (I->getOpcode()) {
905   default:
906     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
907     break;
908   case Instruction::And:
909     // If either the LHS or the RHS are Zero, the result is zero.
910     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
911                              RHSKnownZero, RHSKnownOne, Depth+1) ||
912         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
913                              LHSKnownZero, LHSKnownOne, Depth+1))
914       return I;
915     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
916     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
917
918     // If all of the demanded bits are known 1 on one side, return the other.
919     // These bits cannot contribute to the result of the 'and'.
920     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
921         (DemandedMask & ~LHSKnownZero))
922       return I->getOperand(0);
923     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
924         (DemandedMask & ~RHSKnownZero))
925       return I->getOperand(1);
926     
927     // If all of the demanded bits in the inputs are known zeros, return zero.
928     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
929       return Constant::getNullValue(VTy);
930       
931     // If the RHS is a constant, see if we can simplify it.
932     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
933       return I;
934       
935     // Output known-1 bits are only known if set in both the LHS & RHS.
936     RHSKnownOne &= LHSKnownOne;
937     // Output known-0 are known to be clear if zero in either the LHS | RHS.
938     RHSKnownZero |= LHSKnownZero;
939     break;
940   case Instruction::Or:
941     // If either the LHS or the RHS are One, the result is One.
942     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
943                              RHSKnownZero, RHSKnownOne, Depth+1) ||
944         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
945                              LHSKnownZero, LHSKnownOne, Depth+1))
946       return I;
947     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
948     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
949     
950     // If all of the demanded bits are known zero on one side, return the other.
951     // These bits cannot contribute to the result of the 'or'.
952     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
953         (DemandedMask & ~LHSKnownOne))
954       return I->getOperand(0);
955     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
956         (DemandedMask & ~RHSKnownOne))
957       return I->getOperand(1);
958
959     // If all of the potentially set bits on one side are known to be set on
960     // the other side, just use the 'other' side.
961     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
962         (DemandedMask & (~RHSKnownZero)))
963       return I->getOperand(0);
964     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
965         (DemandedMask & (~LHSKnownZero)))
966       return I->getOperand(1);
967         
968     // If the RHS is a constant, see if we can simplify it.
969     if (ShrinkDemandedConstant(I, 1, DemandedMask))
970       return I;
971           
972     // Output known-0 bits are only known if clear in both the LHS & RHS.
973     RHSKnownZero &= LHSKnownZero;
974     // Output known-1 are known to be set if set in either the LHS | RHS.
975     RHSKnownOne |= LHSKnownOne;
976     break;
977   case Instruction::Xor: {
978     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
979                              RHSKnownZero, RHSKnownOne, Depth+1) ||
980         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
981                              LHSKnownZero, LHSKnownOne, Depth+1))
982       return I;
983     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
984     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
985     
986     // If all of the demanded bits are known zero on one side, return the other.
987     // These bits cannot contribute to the result of the 'xor'.
988     if ((DemandedMask & RHSKnownZero) == DemandedMask)
989       return I->getOperand(0);
990     if ((DemandedMask & LHSKnownZero) == DemandedMask)
991       return I->getOperand(1);
992     
993     // Output known-0 bits are known if clear or set in both the LHS & RHS.
994     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
995                          (RHSKnownOne & LHSKnownOne);
996     // Output known-1 are known to be set if set in only one of the LHS, RHS.
997     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
998                         (RHSKnownOne & LHSKnownZero);
999     
1000     // If all of the demanded bits are known to be zero on one side or the
1001     // other, turn this into an *inclusive* or.
1002     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1003     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1004       Instruction *Or =
1005         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1006                                  I->getName());
1007       return InsertNewInstBefore(Or, *I);
1008     }
1009     
1010     // If all of the demanded bits on one side are known, and all of the set
1011     // bits on that side are also known to be set on the other side, turn this
1012     // into an AND, as we know the bits will be cleared.
1013     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1014     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1015       // all known
1016       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1017         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1018         Instruction *And = 
1019           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1020         return InsertNewInstBefore(And, *I);
1021       }
1022     }
1023     
1024     // If the RHS is a constant, see if we can simplify it.
1025     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1026     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1027       return I;
1028     
1029     RHSKnownZero = KnownZeroOut;
1030     RHSKnownOne  = KnownOneOut;
1031     break;
1032   }
1033   case Instruction::Select:
1034     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1035                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1036         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1037                              LHSKnownZero, LHSKnownOne, Depth+1))
1038       return I;
1039     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1040     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1041     
1042     // If the operands are constants, see if we can simplify them.
1043     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1044         ShrinkDemandedConstant(I, 2, DemandedMask))
1045       return I;
1046     
1047     // Only known if known in both the LHS and RHS.
1048     RHSKnownOne &= LHSKnownOne;
1049     RHSKnownZero &= LHSKnownZero;
1050     break;
1051   case Instruction::Trunc: {
1052     unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1053     DemandedMask.zext(truncBf);
1054     RHSKnownZero.zext(truncBf);
1055     RHSKnownOne.zext(truncBf);
1056     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1057                              RHSKnownZero, RHSKnownOne, Depth+1))
1058       return I;
1059     DemandedMask.trunc(BitWidth);
1060     RHSKnownZero.trunc(BitWidth);
1061     RHSKnownOne.trunc(BitWidth);
1062     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1063     break;
1064   }
1065   case Instruction::BitCast:
1066     if (!I->getOperand(0)->getType()->isInteger())
1067       return false;  // vector->int or fp->int?
1068     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1069                              RHSKnownZero, RHSKnownOne, Depth+1))
1070       return I;
1071     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1072     break;
1073   case Instruction::ZExt: {
1074     // Compute the bits in the result that are not present in the input.
1075     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1076     
1077     DemandedMask.trunc(SrcBitWidth);
1078     RHSKnownZero.trunc(SrcBitWidth);
1079     RHSKnownOne.trunc(SrcBitWidth);
1080     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1081                              RHSKnownZero, RHSKnownOne, Depth+1))
1082       return I;
1083     DemandedMask.zext(BitWidth);
1084     RHSKnownZero.zext(BitWidth);
1085     RHSKnownOne.zext(BitWidth);
1086     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1087     // The top bits are known to be zero.
1088     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1089     break;
1090   }
1091   case Instruction::SExt: {
1092     // Compute the bits in the result that are not present in the input.
1093     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1094     
1095     APInt InputDemandedBits = DemandedMask & 
1096                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1097
1098     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1099     // If any of the sign extended bits are demanded, we know that the sign
1100     // bit is demanded.
1101     if ((NewBits & DemandedMask) != 0)
1102       InputDemandedBits.set(SrcBitWidth-1);
1103       
1104     InputDemandedBits.trunc(SrcBitWidth);
1105     RHSKnownZero.trunc(SrcBitWidth);
1106     RHSKnownOne.trunc(SrcBitWidth);
1107     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1108                              RHSKnownZero, RHSKnownOne, Depth+1))
1109       return I;
1110     InputDemandedBits.zext(BitWidth);
1111     RHSKnownZero.zext(BitWidth);
1112     RHSKnownOne.zext(BitWidth);
1113     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1114       
1115     // If the sign bit of the input is known set or clear, then we know the
1116     // top bits of the result.
1117
1118     // If the input sign bit is known zero, or if the NewBits are not demanded
1119     // convert this into a zero extension.
1120     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1121       // Convert to ZExt cast
1122       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1123       return InsertNewInstBefore(NewCast, *I);
1124     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1125       RHSKnownOne |= NewBits;
1126     }
1127     break;
1128   }
1129   case Instruction::Add: {
1130     // Figure out what the input bits are.  If the top bits of the and result
1131     // are not demanded, then the add doesn't demand them from its input
1132     // either.
1133     unsigned NLZ = DemandedMask.countLeadingZeros();
1134       
1135     // If there is a constant on the RHS, there are a variety of xformations
1136     // we can do.
1137     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1138       // If null, this should be simplified elsewhere.  Some of the xforms here
1139       // won't work if the RHS is zero.
1140       if (RHS->isZero())
1141         break;
1142       
1143       // If the top bit of the output is demanded, demand everything from the
1144       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1145       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1146
1147       // Find information about known zero/one bits in the input.
1148       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1149                                LHSKnownZero, LHSKnownOne, Depth+1))
1150         return I;
1151
1152       // If the RHS of the add has bits set that can't affect the input, reduce
1153       // the constant.
1154       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1155         return I;
1156       
1157       // Avoid excess work.
1158       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1159         break;
1160       
1161       // Turn it into OR if input bits are zero.
1162       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1163         Instruction *Or =
1164           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1165                                    I->getName());
1166         return InsertNewInstBefore(Or, *I);
1167       }
1168       
1169       // We can say something about the output known-zero and known-one bits,
1170       // depending on potential carries from the input constant and the
1171       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1172       // bits set and the RHS constant is 0x01001, then we know we have a known
1173       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1174       
1175       // To compute this, we first compute the potential carry bits.  These are
1176       // the bits which may be modified.  I'm not aware of a better way to do
1177       // this scan.
1178       const APInt &RHSVal = RHS->getValue();
1179       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1180       
1181       // Now that we know which bits have carries, compute the known-1/0 sets.
1182       
1183       // Bits are known one if they are known zero in one operand and one in the
1184       // other, and there is no input carry.
1185       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1186                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1187       
1188       // Bits are known zero if they are known zero in both operands and there
1189       // is no input carry.
1190       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1191     } else {
1192       // If the high-bits of this ADD are not demanded, then it does not demand
1193       // the high bits of its LHS or RHS.
1194       if (DemandedMask[BitWidth-1] == 0) {
1195         // Right fill the mask of bits for this ADD to demand the most
1196         // significant bit and all those below it.
1197         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1198         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1199                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1200             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1201                                  LHSKnownZero, LHSKnownOne, Depth+1))
1202           return I;
1203       }
1204     }
1205     break;
1206   }
1207   case Instruction::Sub:
1208     // If the high-bits of this SUB are not demanded, then it does not demand
1209     // the high bits of its LHS or RHS.
1210     if (DemandedMask[BitWidth-1] == 0) {
1211       // Right fill the mask of bits for this SUB to demand the most
1212       // significant bit and all those below it.
1213       uint32_t NLZ = DemandedMask.countLeadingZeros();
1214       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1215       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1216                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1217           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1218                                LHSKnownZero, LHSKnownOne, Depth+1))
1219         return I;
1220     }
1221     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1222     // the known zeros and ones.
1223     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1224     break;
1225   case Instruction::Shl:
1226     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1227       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1228       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1229       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1230                                RHSKnownZero, RHSKnownOne, Depth+1))
1231         return I;
1232       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1233       RHSKnownZero <<= ShiftAmt;
1234       RHSKnownOne  <<= ShiftAmt;
1235       // low bits known zero.
1236       if (ShiftAmt)
1237         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1238     }
1239     break;
1240   case Instruction::LShr:
1241     // For a logical shift right
1242     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1243       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1244       
1245       // Unsigned shift right.
1246       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1247       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1248                                RHSKnownZero, RHSKnownOne, Depth+1))
1249         return I;
1250       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1251       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1252       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1253       if (ShiftAmt) {
1254         // Compute the new bits that are at the top now.
1255         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1256         RHSKnownZero |= HighBits;  // high bits known zero.
1257       }
1258     }
1259     break;
1260   case Instruction::AShr:
1261     // If this is an arithmetic shift right and only the low-bit is set, we can
1262     // always convert this into a logical shr, even if the shift amount is
1263     // variable.  The low bit of the shift cannot be an input sign bit unless
1264     // the shift amount is >= the size of the datatype, which is undefined.
1265     if (DemandedMask == 1) {
1266       // Perform the logical shift right.
1267       Instruction *NewVal = BinaryOperator::CreateLShr(
1268                         I->getOperand(0), I->getOperand(1), I->getName());
1269       return InsertNewInstBefore(NewVal, *I);
1270     }    
1271
1272     // If the sign bit is the only bit demanded by this ashr, then there is no
1273     // need to do it, the shift doesn't change the high bit.
1274     if (DemandedMask.isSignBit())
1275       return I->getOperand(0);
1276     
1277     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1278       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1279       
1280       // Signed shift right.
1281       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1282       // If any of the "high bits" are demanded, we should set the sign bit as
1283       // demanded.
1284       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1285         DemandedMaskIn.set(BitWidth-1);
1286       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1287                                RHSKnownZero, RHSKnownOne, Depth+1))
1288         return I;
1289       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1290       // Compute the new bits that are at the top now.
1291       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1292       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1293       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1294         
1295       // Handle the sign bits.
1296       APInt SignBit(APInt::getSignBit(BitWidth));
1297       // Adjust to where it is now in the mask.
1298       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1299         
1300       // If the input sign bit is known to be zero, or if none of the top bits
1301       // are demanded, turn this into an unsigned shift right.
1302       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1303           (HighBits & ~DemandedMask) == HighBits) {
1304         // Perform the logical shift right.
1305         Instruction *NewVal = BinaryOperator::CreateLShr(
1306                           I->getOperand(0), SA, I->getName());
1307         return InsertNewInstBefore(NewVal, *I);
1308       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1309         RHSKnownOne |= HighBits;
1310       }
1311     }
1312     break;
1313   case Instruction::SRem:
1314     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1315       APInt RA = Rem->getValue().abs();
1316       if (RA.isPowerOf2()) {
1317         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1318           return I->getOperand(0);
1319
1320         APInt LowBits = RA - 1;
1321         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1322         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1323                                  LHSKnownZero, LHSKnownOne, Depth+1))
1324           return I;
1325
1326         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1327           LHSKnownZero |= ~LowBits;
1328
1329         KnownZero |= LHSKnownZero & DemandedMask;
1330
1331         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1332       }
1333     }
1334     break;
1335   case Instruction::URem: {
1336     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1337     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1338     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1339                              KnownZero2, KnownOne2, Depth+1) ||
1340         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1341                              KnownZero2, KnownOne2, Depth+1))
1342       return I;
1343
1344     unsigned Leaders = KnownZero2.countLeadingOnes();
1345     Leaders = std::max(Leaders,
1346                        KnownZero2.countLeadingOnes());
1347     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1348     break;
1349   }
1350   case Instruction::Call:
1351     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1352       switch (II->getIntrinsicID()) {
1353       default: break;
1354       case Intrinsic::bswap: {
1355         // If the only bits demanded come from one byte of the bswap result,
1356         // just shift the input byte into position to eliminate the bswap.
1357         unsigned NLZ = DemandedMask.countLeadingZeros();
1358         unsigned NTZ = DemandedMask.countTrailingZeros();
1359           
1360         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1361         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1362         // have 14 leading zeros, round to 8.
1363         NLZ &= ~7;
1364         NTZ &= ~7;
1365         // If we need exactly one byte, we can do this transformation.
1366         if (BitWidth-NLZ-NTZ == 8) {
1367           unsigned ResultBit = NTZ;
1368           unsigned InputBit = BitWidth-NTZ-8;
1369           
1370           // Replace this with either a left or right shift to get the byte into
1371           // the right place.
1372           Instruction *NewVal;
1373           if (InputBit > ResultBit)
1374             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1375                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1376           else
1377             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1378                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1379           NewVal->takeName(I);
1380           return InsertNewInstBefore(NewVal, *I);
1381         }
1382           
1383         // TODO: Could compute known zero/one bits based on the input.
1384         break;
1385       }
1386       }
1387     }
1388     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1389     break;
1390   }
1391   
1392   // If the client is only demanding bits that we know, return the known
1393   // constant.
1394   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1395     return ConstantInt::get(RHSKnownOne);
1396   return false;
1397 }
1398
1399
1400 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1401 /// any number of elements. DemandedElts contains the set of elements that are
1402 /// actually used by the caller.  This method analyzes which elements of the
1403 /// operand are undef and returns that information in UndefElts.
1404 ///
1405 /// If the information about demanded elements can be used to simplify the
1406 /// operation, the operation is simplified, then the resultant value is
1407 /// returned.  This returns null if no change was made.
1408 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1409                                                 APInt& UndefElts,
1410                                                 unsigned Depth) {
1411   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1412   APInt EltMask(APInt::getAllOnesValue(VWidth));
1413   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1414
1415   if (isa<UndefValue>(V)) {
1416     // If the entire vector is undefined, just return this info.
1417     UndefElts = EltMask;
1418     return 0;
1419   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1420     UndefElts = EltMask;
1421     return UndefValue::get(V->getType());
1422   }
1423
1424   UndefElts = 0;
1425   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1426     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1427     Constant *Undef = UndefValue::get(EltTy);
1428
1429     std::vector<Constant*> Elts;
1430     for (unsigned i = 0; i != VWidth; ++i)
1431       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1432         Elts.push_back(Undef);
1433         UndefElts.set(i);
1434       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1435         Elts.push_back(Undef);
1436         UndefElts.set(i);
1437       } else {                               // Otherwise, defined.
1438         Elts.push_back(CP->getOperand(i));
1439       }
1440
1441     // If we changed the constant, return it.
1442     Constant *NewCP = ConstantVector::get(Elts);
1443     return NewCP != CP ? NewCP : 0;
1444   } else if (isa<ConstantAggregateZero>(V)) {
1445     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1446     // set to undef.
1447     
1448     // Check if this is identity. If so, return 0 since we are not simplifying
1449     // anything.
1450     if (DemandedElts == ((1ULL << VWidth) -1))
1451       return 0;
1452     
1453     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1454     Constant *Zero = Constant::getNullValue(EltTy);
1455     Constant *Undef = UndefValue::get(EltTy);
1456     std::vector<Constant*> Elts;
1457     for (unsigned i = 0; i != VWidth; ++i) {
1458       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1459       Elts.push_back(Elt);
1460     }
1461     UndefElts = DemandedElts ^ EltMask;
1462     return ConstantVector::get(Elts);
1463   }
1464   
1465   // Limit search depth.
1466   if (Depth == 10)
1467     return false;
1468
1469   // If multiple users are using the root value, procede with
1470   // simplification conservatively assuming that all elements
1471   // are needed.
1472   if (!V->hasOneUse()) {
1473     // Quit if we find multiple users of a non-root value though.
1474     // They'll be handled when it's their turn to be visited by
1475     // the main instcombine process.
1476     if (Depth != 0)
1477       // TODO: Just compute the UndefElts information recursively.
1478       return false;
1479
1480     // Conservatively assume that all elements are needed.
1481     DemandedElts = EltMask;
1482   }
1483   
1484   Instruction *I = dyn_cast<Instruction>(V);
1485   if (!I) return false;        // Only analyze instructions.
1486   
1487   bool MadeChange = false;
1488   APInt UndefElts2(VWidth, 0);
1489   Value *TmpV;
1490   switch (I->getOpcode()) {
1491   default: break;
1492     
1493   case Instruction::InsertElement: {
1494     // If this is a variable index, we don't know which element it overwrites.
1495     // demand exactly the same input as we produce.
1496     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1497     if (Idx == 0) {
1498       // Note that we can't propagate undef elt info, because we don't know
1499       // which elt is getting updated.
1500       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1501                                         UndefElts2, Depth+1);
1502       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1503       break;
1504     }
1505     
1506     // If this is inserting an element that isn't demanded, remove this
1507     // insertelement.
1508     unsigned IdxNo = Idx->getZExtValue();
1509     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1510       return AddSoonDeadInstToWorklist(*I, 0);
1511     
1512     // Otherwise, the element inserted overwrites whatever was there, so the
1513     // input demanded set is simpler than the output set.
1514     APInt DemandedElts2 = DemandedElts;
1515     DemandedElts2.clear(IdxNo);
1516     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1517                                       UndefElts, Depth+1);
1518     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1519
1520     // The inserted element is defined.
1521     UndefElts.clear(IdxNo);
1522     break;
1523   }
1524   case Instruction::ShuffleVector: {
1525     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1526     uint64_t LHSVWidth =
1527       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1528     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1529     for (unsigned i = 0; i < VWidth; i++) {
1530       if (DemandedElts[i]) {
1531         unsigned MaskVal = Shuffle->getMaskValue(i);
1532         if (MaskVal != -1u) {
1533           assert(MaskVal < LHSVWidth * 2 &&
1534                  "shufflevector mask index out of range!");
1535           if (MaskVal < LHSVWidth)
1536             LeftDemanded.set(MaskVal);
1537           else
1538             RightDemanded.set(MaskVal - LHSVWidth);
1539         }
1540       }
1541     }
1542
1543     APInt UndefElts4(LHSVWidth, 0);
1544     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1545                                       UndefElts4, Depth+1);
1546     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1547
1548     APInt UndefElts3(LHSVWidth, 0);
1549     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1550                                       UndefElts3, Depth+1);
1551     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1552
1553     bool NewUndefElts = false;
1554     for (unsigned i = 0; i < VWidth; i++) {
1555       unsigned MaskVal = Shuffle->getMaskValue(i);
1556       if (MaskVal == -1u) {
1557         UndefElts.set(i);
1558       } else if (MaskVal < LHSVWidth) {
1559         if (UndefElts4[MaskVal]) {
1560           NewUndefElts = true;
1561           UndefElts.set(i);
1562         }
1563       } else {
1564         if (UndefElts3[MaskVal - LHSVWidth]) {
1565           NewUndefElts = true;
1566           UndefElts.set(i);
1567         }
1568       }
1569     }
1570
1571     if (NewUndefElts) {
1572       // Add additional discovered undefs.
1573       std::vector<Constant*> Elts;
1574       for (unsigned i = 0; i < VWidth; ++i) {
1575         if (UndefElts[i])
1576           Elts.push_back(UndefValue::get(Type::Int32Ty));
1577         else
1578           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1579                                           Shuffle->getMaskValue(i)));
1580       }
1581       I->setOperand(2, ConstantVector::get(Elts));
1582       MadeChange = true;
1583     }
1584     break;
1585   }
1586   case Instruction::BitCast: {
1587     // Vector->vector casts only.
1588     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1589     if (!VTy) break;
1590     unsigned InVWidth = VTy->getNumElements();
1591     APInt InputDemandedElts(InVWidth, 0);
1592     unsigned Ratio;
1593
1594     if (VWidth == InVWidth) {
1595       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1596       // elements as are demanded of us.
1597       Ratio = 1;
1598       InputDemandedElts = DemandedElts;
1599     } else if (VWidth > InVWidth) {
1600       // Untested so far.
1601       break;
1602       
1603       // If there are more elements in the result than there are in the source,
1604       // then an input element is live if any of the corresponding output
1605       // elements are live.
1606       Ratio = VWidth/InVWidth;
1607       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1608         if (DemandedElts[OutIdx])
1609           InputDemandedElts.set(OutIdx/Ratio);
1610       }
1611     } else {
1612       // Untested so far.
1613       break;
1614       
1615       // If there are more elements in the source than there are in the result,
1616       // then an input element is live if the corresponding output element is
1617       // live.
1618       Ratio = InVWidth/VWidth;
1619       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1620         if (DemandedElts[InIdx/Ratio])
1621           InputDemandedElts.set(InIdx);
1622     }
1623     
1624     // div/rem demand all inputs, because they don't want divide by zero.
1625     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1626                                       UndefElts2, Depth+1);
1627     if (TmpV) {
1628       I->setOperand(0, TmpV);
1629       MadeChange = true;
1630     }
1631     
1632     UndefElts = UndefElts2;
1633     if (VWidth > InVWidth) {
1634       assert(0 && "Unimp");
1635       // If there are more elements in the result than there are in the source,
1636       // then an output element is undef if the corresponding input element is
1637       // undef.
1638       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1639         if (UndefElts2[OutIdx/Ratio])
1640           UndefElts.set(OutIdx);
1641     } else if (VWidth < InVWidth) {
1642       assert(0 && "Unimp");
1643       // If there are more elements in the source than there are in the result,
1644       // then a result element is undef if all of the corresponding input
1645       // elements are undef.
1646       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1647       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1648         if (!UndefElts2[InIdx])            // Not undef?
1649           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1650     }
1651     break;
1652   }
1653   case Instruction::And:
1654   case Instruction::Or:
1655   case Instruction::Xor:
1656   case Instruction::Add:
1657   case Instruction::Sub:
1658   case Instruction::Mul:
1659     // div/rem demand all inputs, because they don't want divide by zero.
1660     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1661                                       UndefElts, Depth+1);
1662     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1663     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1664                                       UndefElts2, Depth+1);
1665     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1666       
1667     // Output elements are undefined if both are undefined.  Consider things
1668     // like undef&0.  The result is known zero, not undef.
1669     UndefElts &= UndefElts2;
1670     break;
1671     
1672   case Instruction::Call: {
1673     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1674     if (!II) break;
1675     switch (II->getIntrinsicID()) {
1676     default: break;
1677       
1678     // Binary vector operations that work column-wise.  A dest element is a
1679     // function of the corresponding input elements from the two inputs.
1680     case Intrinsic::x86_sse_sub_ss:
1681     case Intrinsic::x86_sse_mul_ss:
1682     case Intrinsic::x86_sse_min_ss:
1683     case Intrinsic::x86_sse_max_ss:
1684     case Intrinsic::x86_sse2_sub_sd:
1685     case Intrinsic::x86_sse2_mul_sd:
1686     case Intrinsic::x86_sse2_min_sd:
1687     case Intrinsic::x86_sse2_max_sd:
1688       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1689                                         UndefElts, Depth+1);
1690       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1691       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1692                                         UndefElts2, Depth+1);
1693       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1694
1695       // If only the low elt is demanded and this is a scalarizable intrinsic,
1696       // scalarize it now.
1697       if (DemandedElts == 1) {
1698         switch (II->getIntrinsicID()) {
1699         default: break;
1700         case Intrinsic::x86_sse_sub_ss:
1701         case Intrinsic::x86_sse_mul_ss:
1702         case Intrinsic::x86_sse2_sub_sd:
1703         case Intrinsic::x86_sse2_mul_sd:
1704           // TODO: Lower MIN/MAX/ABS/etc
1705           Value *LHS = II->getOperand(1);
1706           Value *RHS = II->getOperand(2);
1707           // Extract the element as scalars.
1708           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1709           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1710           
1711           switch (II->getIntrinsicID()) {
1712           default: assert(0 && "Case stmts out of sync!");
1713           case Intrinsic::x86_sse_sub_ss:
1714           case Intrinsic::x86_sse2_sub_sd:
1715             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1716                                                         II->getName()), *II);
1717             break;
1718           case Intrinsic::x86_sse_mul_ss:
1719           case Intrinsic::x86_sse2_mul_sd:
1720             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1721                                                          II->getName()), *II);
1722             break;
1723           }
1724           
1725           Instruction *New =
1726             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1727                                       II->getName());
1728           InsertNewInstBefore(New, *II);
1729           AddSoonDeadInstToWorklist(*II, 0);
1730           return New;
1731         }            
1732       }
1733         
1734       // Output elements are undefined if both are undefined.  Consider things
1735       // like undef&0.  The result is known zero, not undef.
1736       UndefElts &= UndefElts2;
1737       break;
1738     }
1739     break;
1740   }
1741   }
1742   return MadeChange ? I : 0;
1743 }
1744
1745
1746 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1747 /// function is designed to check a chain of associative operators for a
1748 /// potential to apply a certain optimization.  Since the optimization may be
1749 /// applicable if the expression was reassociated, this checks the chain, then
1750 /// reassociates the expression as necessary to expose the optimization
1751 /// opportunity.  This makes use of a special Functor, which must define
1752 /// 'shouldApply' and 'apply' methods.
1753 ///
1754 template<typename Functor>
1755 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1756   unsigned Opcode = Root.getOpcode();
1757   Value *LHS = Root.getOperand(0);
1758
1759   // Quick check, see if the immediate LHS matches...
1760   if (F.shouldApply(LHS))
1761     return F.apply(Root);
1762
1763   // Otherwise, if the LHS is not of the same opcode as the root, return.
1764   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1765   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1766     // Should we apply this transform to the RHS?
1767     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1768
1769     // If not to the RHS, check to see if we should apply to the LHS...
1770     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1771       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1772       ShouldApply = true;
1773     }
1774
1775     // If the functor wants to apply the optimization to the RHS of LHSI,
1776     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1777     if (ShouldApply) {
1778       // Now all of the instructions are in the current basic block, go ahead
1779       // and perform the reassociation.
1780       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1781
1782       // First move the selected RHS to the LHS of the root...
1783       Root.setOperand(0, LHSI->getOperand(1));
1784
1785       // Make what used to be the LHS of the root be the user of the root...
1786       Value *ExtraOperand = TmpLHSI->getOperand(1);
1787       if (&Root == TmpLHSI) {
1788         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1789         return 0;
1790       }
1791       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1792       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1793       BasicBlock::iterator ARI = &Root; ++ARI;
1794       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1795       ARI = Root;
1796
1797       // Now propagate the ExtraOperand down the chain of instructions until we
1798       // get to LHSI.
1799       while (TmpLHSI != LHSI) {
1800         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1801         // Move the instruction to immediately before the chain we are
1802         // constructing to avoid breaking dominance properties.
1803         NextLHSI->moveBefore(ARI);
1804         ARI = NextLHSI;
1805
1806         Value *NextOp = NextLHSI->getOperand(1);
1807         NextLHSI->setOperand(1, ExtraOperand);
1808         TmpLHSI = NextLHSI;
1809         ExtraOperand = NextOp;
1810       }
1811
1812       // Now that the instructions are reassociated, have the functor perform
1813       // the transformation...
1814       return F.apply(Root);
1815     }
1816
1817     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1818   }
1819   return 0;
1820 }
1821
1822 namespace {
1823
1824 // AddRHS - Implements: X + X --> X << 1
1825 struct AddRHS {
1826   Value *RHS;
1827   AddRHS(Value *rhs) : RHS(rhs) {}
1828   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1829   Instruction *apply(BinaryOperator &Add) const {
1830     return BinaryOperator::CreateShl(Add.getOperand(0),
1831                                      ConstantInt::get(Add.getType(), 1));
1832   }
1833 };
1834
1835 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1836 //                 iff C1&C2 == 0
1837 struct AddMaskingAnd {
1838   Constant *C2;
1839   AddMaskingAnd(Constant *c) : C2(c) {}
1840   bool shouldApply(Value *LHS) const {
1841     ConstantInt *C1;
1842     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1843            ConstantExpr::getAnd(C1, C2)->isNullValue();
1844   }
1845   Instruction *apply(BinaryOperator &Add) const {
1846     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1847   }
1848 };
1849
1850 }
1851
1852 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1853                                              InstCombiner *IC) {
1854   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1855     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1856   }
1857
1858   // Figure out if the constant is the left or the right argument.
1859   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1860   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1861
1862   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1863     if (ConstIsRHS)
1864       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1865     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1866   }
1867
1868   Value *Op0 = SO, *Op1 = ConstOperand;
1869   if (!ConstIsRHS)
1870     std::swap(Op0, Op1);
1871   Instruction *New;
1872   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1873     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1874   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1875     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1876                           SO->getName()+".cmp");
1877   else {
1878     assert(0 && "Unknown binary instruction type!");
1879     abort();
1880   }
1881   return IC->InsertNewInstBefore(New, I);
1882 }
1883
1884 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1885 // constant as the other operand, try to fold the binary operator into the
1886 // select arguments.  This also works for Cast instructions, which obviously do
1887 // not have a second operand.
1888 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1889                                      InstCombiner *IC) {
1890   // Don't modify shared select instructions
1891   if (!SI->hasOneUse()) return 0;
1892   Value *TV = SI->getOperand(1);
1893   Value *FV = SI->getOperand(2);
1894
1895   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1896     // Bool selects with constant operands can be folded to logical ops.
1897     if (SI->getType() == Type::Int1Ty) return 0;
1898
1899     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1900     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1901
1902     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1903                               SelectFalseVal);
1904   }
1905   return 0;
1906 }
1907
1908
1909 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1910 /// node as operand #0, see if we can fold the instruction into the PHI (which
1911 /// is only possible if all operands to the PHI are constants).
1912 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1913   PHINode *PN = cast<PHINode>(I.getOperand(0));
1914   unsigned NumPHIValues = PN->getNumIncomingValues();
1915   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1916
1917   // Check to see if all of the operands of the PHI are constants.  If there is
1918   // one non-constant value, remember the BB it is.  If there is more than one
1919   // or if *it* is a PHI, bail out.
1920   BasicBlock *NonConstBB = 0;
1921   for (unsigned i = 0; i != NumPHIValues; ++i)
1922     if (!isa<Constant>(PN->getIncomingValue(i))) {
1923       if (NonConstBB) return 0;  // More than one non-const value.
1924       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1925       NonConstBB = PN->getIncomingBlock(i);
1926       
1927       // If the incoming non-constant value is in I's block, we have an infinite
1928       // loop.
1929       if (NonConstBB == I.getParent())
1930         return 0;
1931     }
1932   
1933   // If there is exactly one non-constant value, we can insert a copy of the
1934   // operation in that block.  However, if this is a critical edge, we would be
1935   // inserting the computation one some other paths (e.g. inside a loop).  Only
1936   // do this if the pred block is unconditionally branching into the phi block.
1937   if (NonConstBB) {
1938     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1939     if (!BI || !BI->isUnconditional()) return 0;
1940   }
1941
1942   // Okay, we can do the transformation: create the new PHI node.
1943   PHINode *NewPN = PHINode::Create(I.getType(), "");
1944   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1945   InsertNewInstBefore(NewPN, *PN);
1946   NewPN->takeName(PN);
1947
1948   // Next, add all of the operands to the PHI.
1949   if (I.getNumOperands() == 2) {
1950     Constant *C = cast<Constant>(I.getOperand(1));
1951     for (unsigned i = 0; i != NumPHIValues; ++i) {
1952       Value *InV = 0;
1953       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1954         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1955           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1956         else
1957           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1958       } else {
1959         assert(PN->getIncomingBlock(i) == NonConstBB);
1960         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1961           InV = BinaryOperator::Create(BO->getOpcode(),
1962                                        PN->getIncomingValue(i), C, "phitmp",
1963                                        NonConstBB->getTerminator());
1964         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1965           InV = CmpInst::Create(CI->getOpcode(), 
1966                                 CI->getPredicate(),
1967                                 PN->getIncomingValue(i), C, "phitmp",
1968                                 NonConstBB->getTerminator());
1969         else
1970           assert(0 && "Unknown binop!");
1971         
1972         AddToWorkList(cast<Instruction>(InV));
1973       }
1974       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1975     }
1976   } else { 
1977     CastInst *CI = cast<CastInst>(&I);
1978     const Type *RetTy = CI->getType();
1979     for (unsigned i = 0; i != NumPHIValues; ++i) {
1980       Value *InV;
1981       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1982         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1983       } else {
1984         assert(PN->getIncomingBlock(i) == NonConstBB);
1985         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1986                                I.getType(), "phitmp", 
1987                                NonConstBB->getTerminator());
1988         AddToWorkList(cast<Instruction>(InV));
1989       }
1990       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1991     }
1992   }
1993   return ReplaceInstUsesWith(I, NewPN);
1994 }
1995
1996
1997 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1998 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1999 /// This basically requires proving that the add in the original type would not
2000 /// overflow to change the sign bit or have a carry out.
2001 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2002   // There are different heuristics we can use for this.  Here are some simple
2003   // ones.
2004   
2005   // Add has the property that adding any two 2's complement numbers can only 
2006   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2007   // have at least two sign bits, we know that the addition of the two values will
2008   // sign extend fine.
2009   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2010     return true;
2011   
2012   
2013   // If one of the operands only has one non-zero bit, and if the other operand
2014   // has a known-zero bit in a more significant place than it (not including the
2015   // sign bit) the ripple may go up to and fill the zero, but won't change the
2016   // sign.  For example, (X & ~4) + 1.
2017   
2018   // TODO: Implement.
2019   
2020   return false;
2021 }
2022
2023
2024 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2025   bool Changed = SimplifyCommutative(I);
2026   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2027
2028   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2029     // X + undef -> undef
2030     if (isa<UndefValue>(RHS))
2031       return ReplaceInstUsesWith(I, RHS);
2032
2033     // X + 0 --> X
2034     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2035       if (RHSC->isNullValue())
2036         return ReplaceInstUsesWith(I, LHS);
2037     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2038       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2039                               (I.getType())->getValueAPF()))
2040         return ReplaceInstUsesWith(I, LHS);
2041     }
2042
2043     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2044       // X + (signbit) --> X ^ signbit
2045       const APInt& Val = CI->getValue();
2046       uint32_t BitWidth = Val.getBitWidth();
2047       if (Val == APInt::getSignBit(BitWidth))
2048         return BinaryOperator::CreateXor(LHS, RHS);
2049       
2050       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2051       // (X & 254)+1 -> (X&254)|1
2052       if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
2053         return &I;
2054
2055       // zext(i1) - 1  ->  select i1, 0, -1
2056       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2057         if (CI->isAllOnesValue() &&
2058             ZI->getOperand(0)->getType() == Type::Int1Ty)
2059           return SelectInst::Create(ZI->getOperand(0),
2060                                     Constant::getNullValue(I.getType()),
2061                                     ConstantInt::getAllOnesValue(I.getType()));
2062     }
2063
2064     if (isa<PHINode>(LHS))
2065       if (Instruction *NV = FoldOpIntoPhi(I))
2066         return NV;
2067     
2068     ConstantInt *XorRHS = 0;
2069     Value *XorLHS = 0;
2070     if (isa<ConstantInt>(RHSC) &&
2071         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2072       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2073       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2074       
2075       uint32_t Size = TySizeBits / 2;
2076       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2077       APInt CFF80Val(-C0080Val);
2078       do {
2079         if (TySizeBits > Size) {
2080           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2081           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2082           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2083               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2084             // This is a sign extend if the top bits are known zero.
2085             if (!MaskedValueIsZero(XorLHS, 
2086                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2087               Size = 0;  // Not a sign ext, but can't be any others either.
2088             break;
2089           }
2090         }
2091         Size >>= 1;
2092         C0080Val = APIntOps::lshr(C0080Val, Size);
2093         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2094       } while (Size >= 1);
2095       
2096       // FIXME: This shouldn't be necessary. When the backends can handle types
2097       // with funny bit widths then this switch statement should be removed. It
2098       // is just here to get the size of the "middle" type back up to something
2099       // that the back ends can handle.
2100       const Type *MiddleType = 0;
2101       switch (Size) {
2102         default: break;
2103         case 32: MiddleType = Type::Int32Ty; break;
2104         case 16: MiddleType = Type::Int16Ty; break;
2105         case  8: MiddleType = Type::Int8Ty; break;
2106       }
2107       if (MiddleType) {
2108         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2109         InsertNewInstBefore(NewTrunc, I);
2110         return new SExtInst(NewTrunc, I.getType(), I.getName());
2111       }
2112     }
2113   }
2114
2115   if (I.getType() == Type::Int1Ty)
2116     return BinaryOperator::CreateXor(LHS, RHS);
2117
2118   // X + X --> X << 1
2119   if (I.getType()->isInteger()) {
2120     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2121
2122     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2123       if (RHSI->getOpcode() == Instruction::Sub)
2124         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2125           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2126     }
2127     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2128       if (LHSI->getOpcode() == Instruction::Sub)
2129         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2130           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2131     }
2132   }
2133
2134   // -A + B  -->  B - A
2135   // -A + -B  -->  -(A + B)
2136   if (Value *LHSV = dyn_castNegVal(LHS)) {
2137     if (LHS->getType()->isIntOrIntVector()) {
2138       if (Value *RHSV = dyn_castNegVal(RHS)) {
2139         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2140         InsertNewInstBefore(NewAdd, I);
2141         return BinaryOperator::CreateNeg(NewAdd);
2142       }
2143     }
2144     
2145     return BinaryOperator::CreateSub(RHS, LHSV);
2146   }
2147
2148   // A + -B  -->  A - B
2149   if (!isa<Constant>(RHS))
2150     if (Value *V = dyn_castNegVal(RHS))
2151       return BinaryOperator::CreateSub(LHS, V);
2152
2153
2154   ConstantInt *C2;
2155   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2156     if (X == RHS)   // X*C + X --> X * (C+1)
2157       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2158
2159     // X*C1 + X*C2 --> X * (C1+C2)
2160     ConstantInt *C1;
2161     if (X == dyn_castFoldableMul(RHS, C1))
2162       return BinaryOperator::CreateMul(X, Add(C1, C2));
2163   }
2164
2165   // X + X*C --> X * (C+1)
2166   if (dyn_castFoldableMul(RHS, C2) == LHS)
2167     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2168
2169   // X + ~X --> -1   since   ~X = -X-1
2170   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2171     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2172   
2173
2174   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2175   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2176     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2177       return R;
2178   
2179   // A+B --> A|B iff A and B have no bits set in common.
2180   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2181     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2182     APInt LHSKnownOne(IT->getBitWidth(), 0);
2183     APInt LHSKnownZero(IT->getBitWidth(), 0);
2184     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2185     if (LHSKnownZero != 0) {
2186       APInt RHSKnownOne(IT->getBitWidth(), 0);
2187       APInt RHSKnownZero(IT->getBitWidth(), 0);
2188       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2189       
2190       // No bits in common -> bitwise or.
2191       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2192         return BinaryOperator::CreateOr(LHS, RHS);
2193     }
2194   }
2195
2196   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2197   if (I.getType()->isIntOrIntVector()) {
2198     Value *W, *X, *Y, *Z;
2199     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2200         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2201       if (W != Y) {
2202         if (W == Z) {
2203           std::swap(Y, Z);
2204         } else if (Y == X) {
2205           std::swap(W, X);
2206         } else if (X == Z) {
2207           std::swap(Y, Z);
2208           std::swap(W, X);
2209         }
2210       }
2211
2212       if (W == Y) {
2213         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2214                                                             LHS->getName()), I);
2215         return BinaryOperator::CreateMul(W, NewAdd);
2216       }
2217     }
2218   }
2219
2220   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2221     Value *X = 0;
2222     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2223       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2224
2225     // (X & FF00) + xx00  -> (X+xx00) & FF00
2226     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2227       Constant *Anded = And(CRHS, C2);
2228       if (Anded == CRHS) {
2229         // See if all bits from the first bit set in the Add RHS up are included
2230         // in the mask.  First, get the rightmost bit.
2231         const APInt& AddRHSV = CRHS->getValue();
2232
2233         // Form a mask of all bits from the lowest bit added through the top.
2234         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2235
2236         // See if the and mask includes all of these bits.
2237         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2238
2239         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2240           // Okay, the xform is safe.  Insert the new add pronto.
2241           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2242                                                             LHS->getName()), I);
2243           return BinaryOperator::CreateAnd(NewAdd, C2);
2244         }
2245       }
2246     }
2247
2248     // Try to fold constant add into select arguments.
2249     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2250       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2251         return R;
2252   }
2253
2254   // add (cast *A to intptrtype) B -> 
2255   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2256   {
2257     CastInst *CI = dyn_cast<CastInst>(LHS);
2258     Value *Other = RHS;
2259     if (!CI) {
2260       CI = dyn_cast<CastInst>(RHS);
2261       Other = LHS;
2262     }
2263     if (CI && CI->getType()->isSized() && 
2264         (CI->getType()->getPrimitiveSizeInBits() == 
2265          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2266         && isa<PointerType>(CI->getOperand(0)->getType())) {
2267       unsigned AS =
2268         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2269       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2270                                       PointerType::get(Type::Int8Ty, AS), I);
2271       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2272       return new PtrToIntInst(I2, CI->getType());
2273     }
2274   }
2275   
2276   // add (select X 0 (sub n A)) A  -->  select X A n
2277   {
2278     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2279     Value *A = RHS;
2280     if (!SI) {
2281       SI = dyn_cast<SelectInst>(RHS);
2282       A = LHS;
2283     }
2284     if (SI && SI->hasOneUse()) {
2285       Value *TV = SI->getTrueValue();
2286       Value *FV = SI->getFalseValue();
2287       Value *N;
2288
2289       // Can we fold the add into the argument of the select?
2290       // We check both true and false select arguments for a matching subtract.
2291       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2292         // Fold the add into the true select value.
2293         return SelectInst::Create(SI->getCondition(), N, A);
2294       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2295         // Fold the add into the false select value.
2296         return SelectInst::Create(SI->getCondition(), A, N);
2297     }
2298   }
2299   
2300   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2301   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2302     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2303       return ReplaceInstUsesWith(I, LHS);
2304
2305   // Check for (add (sext x), y), see if we can merge this into an
2306   // integer add followed by a sext.
2307   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2308     // (add (sext x), cst) --> (sext (add x, cst'))
2309     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2310       Constant *CI = 
2311         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2312       if (LHSConv->hasOneUse() &&
2313           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2314           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2315         // Insert the new, smaller add.
2316         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2317                                                         CI, "addconv");
2318         InsertNewInstBefore(NewAdd, I);
2319         return new SExtInst(NewAdd, I.getType());
2320       }
2321     }
2322     
2323     // (add (sext x), (sext y)) --> (sext (add int x, y))
2324     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2325       // Only do this if x/y have the same type, if at last one of them has a
2326       // single use (so we don't increase the number of sexts), and if the
2327       // integer add will not overflow.
2328       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2329           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2330           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2331                                    RHSConv->getOperand(0))) {
2332         // Insert the new integer add.
2333         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2334                                                         RHSConv->getOperand(0),
2335                                                         "addconv");
2336         InsertNewInstBefore(NewAdd, I);
2337         return new SExtInst(NewAdd, I.getType());
2338       }
2339     }
2340   }
2341   
2342   // Check for (add double (sitofp x), y), see if we can merge this into an
2343   // integer add followed by a promotion.
2344   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2345     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2346     // ... if the constant fits in the integer value.  This is useful for things
2347     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2348     // requires a constant pool load, and generally allows the add to be better
2349     // instcombined.
2350     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2351       Constant *CI = 
2352       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2353       if (LHSConv->hasOneUse() &&
2354           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2355           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2356         // Insert the new integer add.
2357         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2358                                                         CI, "addconv");
2359         InsertNewInstBefore(NewAdd, I);
2360         return new SIToFPInst(NewAdd, I.getType());
2361       }
2362     }
2363     
2364     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2365     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2366       // Only do this if x/y have the same type, if at last one of them has a
2367       // single use (so we don't increase the number of int->fp conversions),
2368       // and if the integer add will not overflow.
2369       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2370           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2371           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2372                                    RHSConv->getOperand(0))) {
2373         // Insert the new integer add.
2374         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2375                                                         RHSConv->getOperand(0),
2376                                                         "addconv");
2377         InsertNewInstBefore(NewAdd, I);
2378         return new SIToFPInst(NewAdd, I.getType());
2379       }
2380     }
2381   }
2382   
2383   return Changed ? &I : 0;
2384 }
2385
2386 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2387   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2388
2389   if (Op0 == Op1 &&                        // sub X, X  -> 0
2390       !I.getType()->isFPOrFPVector())
2391     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2392
2393   // If this is a 'B = x-(-A)', change to B = x+A...
2394   if (Value *V = dyn_castNegVal(Op1))
2395     return BinaryOperator::CreateAdd(Op0, V);
2396
2397   if (isa<UndefValue>(Op0))
2398     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2399   if (isa<UndefValue>(Op1))
2400     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2401
2402   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2403     // Replace (-1 - A) with (~A)...
2404     if (C->isAllOnesValue())
2405       return BinaryOperator::CreateNot(Op1);
2406
2407     // C - ~X == X + (1+C)
2408     Value *X = 0;
2409     if (match(Op1, m_Not(m_Value(X))))
2410       return BinaryOperator::CreateAdd(X, AddOne(C));
2411
2412     // -(X >>u 31) -> (X >>s 31)
2413     // -(X >>s 31) -> (X >>u 31)
2414     if (C->isZero()) {
2415       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2416         if (SI->getOpcode() == Instruction::LShr) {
2417           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2418             // Check to see if we are shifting out everything but the sign bit.
2419             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2420                 SI->getType()->getPrimitiveSizeInBits()-1) {
2421               // Ok, the transformation is safe.  Insert AShr.
2422               return BinaryOperator::Create(Instruction::AShr, 
2423                                           SI->getOperand(0), CU, SI->getName());
2424             }
2425           }
2426         }
2427         else if (SI->getOpcode() == Instruction::AShr) {
2428           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2429             // Check to see if we are shifting out everything but the sign bit.
2430             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2431                 SI->getType()->getPrimitiveSizeInBits()-1) {
2432               // Ok, the transformation is safe.  Insert LShr. 
2433               return BinaryOperator::CreateLShr(
2434                                           SI->getOperand(0), CU, SI->getName());
2435             }
2436           }
2437         }
2438       }
2439     }
2440
2441     // Try to fold constant sub into select arguments.
2442     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2443       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2444         return R;
2445   }
2446
2447   if (I.getType() == Type::Int1Ty)
2448     return BinaryOperator::CreateXor(Op0, Op1);
2449
2450   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2451     if (Op1I->getOpcode() == Instruction::Add &&
2452         !Op0->getType()->isFPOrFPVector()) {
2453       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2454         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2455       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2456         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2457       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2458         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2459           // C1-(X+C2) --> (C1-C2)-X
2460           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2461                                            Op1I->getOperand(0));
2462       }
2463     }
2464
2465     if (Op1I->hasOneUse()) {
2466       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2467       // is not used by anyone else...
2468       //
2469       if (Op1I->getOpcode() == Instruction::Sub &&
2470           !Op1I->getType()->isFPOrFPVector()) {
2471         // Swap the two operands of the subexpr...
2472         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2473         Op1I->setOperand(0, IIOp1);
2474         Op1I->setOperand(1, IIOp0);
2475
2476         // Create the new top level add instruction...
2477         return BinaryOperator::CreateAdd(Op0, Op1);
2478       }
2479
2480       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2481       //
2482       if (Op1I->getOpcode() == Instruction::And &&
2483           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2484         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2485
2486         Value *NewNot =
2487           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2488         return BinaryOperator::CreateAnd(Op0, NewNot);
2489       }
2490
2491       // 0 - (X sdiv C)  -> (X sdiv -C)
2492       if (Op1I->getOpcode() == Instruction::SDiv)
2493         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2494           if (CSI->isZero())
2495             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2496               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2497                                                ConstantExpr::getNeg(DivRHS));
2498
2499       // X - X*C --> X * (1-C)
2500       ConstantInt *C2 = 0;
2501       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2502         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2503         return BinaryOperator::CreateMul(Op0, CP1);
2504       }
2505     }
2506   }
2507
2508   if (!Op0->getType()->isFPOrFPVector())
2509     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2510       if (Op0I->getOpcode() == Instruction::Add) {
2511         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2512           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2513         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2514           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2515       } else if (Op0I->getOpcode() == Instruction::Sub) {
2516         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2517           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2518       }
2519     }
2520
2521   ConstantInt *C1;
2522   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2523     if (X == Op1)  // X*C - X --> X * (C-1)
2524       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2525
2526     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2527     if (X == dyn_castFoldableMul(Op1, C2))
2528       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2529   }
2530   return 0;
2531 }
2532
2533 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2534 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2535 /// TrueIfSigned if the result of the comparison is true when the input value is
2536 /// signed.
2537 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2538                            bool &TrueIfSigned) {
2539   switch (pred) {
2540   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2541     TrueIfSigned = true;
2542     return RHS->isZero();
2543   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2544     TrueIfSigned = true;
2545     return RHS->isAllOnesValue();
2546   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2547     TrueIfSigned = false;
2548     return RHS->isAllOnesValue();
2549   case ICmpInst::ICMP_UGT:
2550     // True if LHS u> RHS and RHS == high-bit-mask - 1
2551     TrueIfSigned = true;
2552     return RHS->getValue() ==
2553       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2554   case ICmpInst::ICMP_UGE: 
2555     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2556     TrueIfSigned = true;
2557     return RHS->getValue().isSignBit();
2558   default:
2559     return false;
2560   }
2561 }
2562
2563 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2564   bool Changed = SimplifyCommutative(I);
2565   Value *Op0 = I.getOperand(0);
2566
2567   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2568     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2569
2570   // Simplify mul instructions with a constant RHS...
2571   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2572     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2573
2574       // ((X << C1)*C2) == (X * (C2 << C1))
2575       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2576         if (SI->getOpcode() == Instruction::Shl)
2577           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2578             return BinaryOperator::CreateMul(SI->getOperand(0),
2579                                              ConstantExpr::getShl(CI, ShOp));
2580
2581       if (CI->isZero())
2582         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2583       if (CI->equalsInt(1))                  // X * 1  == X
2584         return ReplaceInstUsesWith(I, Op0);
2585       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2586         return BinaryOperator::CreateNeg(Op0, I.getName());
2587
2588       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2589       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2590         return BinaryOperator::CreateShl(Op0,
2591                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2592       }
2593     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2594       if (Op1F->isNullValue())
2595         return ReplaceInstUsesWith(I, Op1);
2596
2597       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2598       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2599       if (Op1F->isExactlyValue(1.0))
2600         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2601     } else if (isa<VectorType>(Op1->getType())) {
2602       if (isa<ConstantAggregateZero>(Op1))
2603         return ReplaceInstUsesWith(I, Op1);
2604
2605       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2606         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2607           return BinaryOperator::CreateNeg(Op0, I.getName());
2608
2609         // As above, vector X*splat(1.0) -> X in all defined cases.
2610         if (Constant *Splat = Op1V->getSplatValue()) {
2611           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2612             if (F->isExactlyValue(1.0))
2613               return ReplaceInstUsesWith(I, Op0);
2614           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2615             if (CI->equalsInt(1))
2616               return ReplaceInstUsesWith(I, Op0);
2617         }
2618       }
2619     }
2620     
2621     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2622       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2623           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2624         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2625         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2626                                                      Op1, "tmp");
2627         InsertNewInstBefore(Add, I);
2628         Value *C1C2 = ConstantExpr::getMul(Op1, 
2629                                            cast<Constant>(Op0I->getOperand(1)));
2630         return BinaryOperator::CreateAdd(Add, C1C2);
2631         
2632       }
2633
2634     // Try to fold constant mul into select arguments.
2635     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2636       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2637         return R;
2638
2639     if (isa<PHINode>(Op0))
2640       if (Instruction *NV = FoldOpIntoPhi(I))
2641         return NV;
2642   }
2643
2644   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2645     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2646       return BinaryOperator::CreateMul(Op0v, Op1v);
2647
2648   // (X / Y) *  Y = X - (X % Y)
2649   // (X / Y) * -Y = (X % Y) - X
2650   {
2651     Value *Op1 = I.getOperand(1);
2652     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2653     if (!BO ||
2654         (BO->getOpcode() != Instruction::UDiv && 
2655          BO->getOpcode() != Instruction::SDiv)) {
2656       Op1 = Op0;
2657       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2658     }
2659     Value *Neg = dyn_castNegVal(Op1);
2660     if (BO && BO->hasOneUse() &&
2661         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2662         (BO->getOpcode() == Instruction::UDiv ||
2663          BO->getOpcode() == Instruction::SDiv)) {
2664       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2665
2666       Instruction *Rem;
2667       if (BO->getOpcode() == Instruction::UDiv)
2668         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2669       else
2670         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2671
2672       InsertNewInstBefore(Rem, I);
2673       Rem->takeName(BO);
2674
2675       if (Op1BO == Op1)
2676         return BinaryOperator::CreateSub(Op0BO, Rem);
2677       else
2678         return BinaryOperator::CreateSub(Rem, Op0BO);
2679     }
2680   }
2681
2682   if (I.getType() == Type::Int1Ty)
2683     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2684
2685   // If one of the operands of the multiply is a cast from a boolean value, then
2686   // we know the bool is either zero or one, so this is a 'masking' multiply.
2687   // See if we can simplify things based on how the boolean was originally
2688   // formed.
2689   CastInst *BoolCast = 0;
2690   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2691     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2692       BoolCast = CI;
2693   if (!BoolCast)
2694     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2695       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2696         BoolCast = CI;
2697   if (BoolCast) {
2698     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2699       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2700       const Type *SCOpTy = SCIOp0->getType();
2701       bool TIS = false;
2702       
2703       // If the icmp is true iff the sign bit of X is set, then convert this
2704       // multiply into a shift/and combination.
2705       if (isa<ConstantInt>(SCIOp1) &&
2706           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2707           TIS) {
2708         // Shift the X value right to turn it into "all signbits".
2709         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2710                                           SCOpTy->getPrimitiveSizeInBits()-1);
2711         Value *V =
2712           InsertNewInstBefore(
2713             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2714                                             BoolCast->getOperand(0)->getName()+
2715                                             ".mask"), I);
2716
2717         // If the multiply type is not the same as the source type, sign extend
2718         // or truncate to the multiply type.
2719         if (I.getType() != V->getType()) {
2720           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2721           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2722           Instruction::CastOps opcode = 
2723             (SrcBits == DstBits ? Instruction::BitCast : 
2724              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2725           V = InsertCastBefore(opcode, V, I.getType(), I);
2726         }
2727
2728         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2729         return BinaryOperator::CreateAnd(V, OtherOp);
2730       }
2731     }
2732   }
2733
2734   return Changed ? &I : 0;
2735 }
2736
2737 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2738 /// instruction.
2739 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2740   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2741   
2742   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2743   int NonNullOperand = -1;
2744   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2745     if (ST->isNullValue())
2746       NonNullOperand = 2;
2747   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2748   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2749     if (ST->isNullValue())
2750       NonNullOperand = 1;
2751   
2752   if (NonNullOperand == -1)
2753     return false;
2754   
2755   Value *SelectCond = SI->getOperand(0);
2756   
2757   // Change the div/rem to use 'Y' instead of the select.
2758   I.setOperand(1, SI->getOperand(NonNullOperand));
2759   
2760   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2761   // problem.  However, the select, or the condition of the select may have
2762   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2763   // propagate the known value for the select into other uses of it, and
2764   // propagate a known value of the condition into its other users.
2765   
2766   // If the select and condition only have a single use, don't bother with this,
2767   // early exit.
2768   if (SI->use_empty() && SelectCond->hasOneUse())
2769     return true;
2770   
2771   // Scan the current block backward, looking for other uses of SI.
2772   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2773   
2774   while (BBI != BBFront) {
2775     --BBI;
2776     // If we found a call to a function, we can't assume it will return, so
2777     // information from below it cannot be propagated above it.
2778     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2779       break;
2780     
2781     // Replace uses of the select or its condition with the known values.
2782     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2783          I != E; ++I) {
2784       if (*I == SI) {
2785         *I = SI->getOperand(NonNullOperand);
2786         AddToWorkList(BBI);
2787       } else if (*I == SelectCond) {
2788         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2789                                    ConstantInt::getFalse();
2790         AddToWorkList(BBI);
2791       }
2792     }
2793     
2794     // If we past the instruction, quit looking for it.
2795     if (&*BBI == SI)
2796       SI = 0;
2797     if (&*BBI == SelectCond)
2798       SelectCond = 0;
2799     
2800     // If we ran out of things to eliminate, break out of the loop.
2801     if (SelectCond == 0 && SI == 0)
2802       break;
2803     
2804   }
2805   return true;
2806 }
2807
2808
2809 /// This function implements the transforms on div instructions that work
2810 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2811 /// used by the visitors to those instructions.
2812 /// @brief Transforms common to all three div instructions
2813 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2814   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2815
2816   // undef / X -> 0        for integer.
2817   // undef / X -> undef    for FP (the undef could be a snan).
2818   if (isa<UndefValue>(Op0)) {
2819     if (Op0->getType()->isFPOrFPVector())
2820       return ReplaceInstUsesWith(I, Op0);
2821     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2822   }
2823
2824   // X / undef -> undef
2825   if (isa<UndefValue>(Op1))
2826     return ReplaceInstUsesWith(I, Op1);
2827
2828   return 0;
2829 }
2830
2831 /// This function implements the transforms common to both integer division
2832 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2833 /// division instructions.
2834 /// @brief Common integer divide transforms
2835 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2836   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2837
2838   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2839   if (Op0 == Op1) {
2840     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2841       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2842       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2843       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2844     }
2845
2846     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2847     return ReplaceInstUsesWith(I, CI);
2848   }
2849   
2850   if (Instruction *Common = commonDivTransforms(I))
2851     return Common;
2852   
2853   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2854   // This does not apply for fdiv.
2855   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2856     return &I;
2857
2858   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2859     // div X, 1 == X
2860     if (RHS->equalsInt(1))
2861       return ReplaceInstUsesWith(I, Op0);
2862
2863     // (X / C1) / C2  -> X / (C1*C2)
2864     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2865       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2866         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2867           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2868             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2869           else 
2870             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2871                                           Multiply(RHS, LHSRHS));
2872         }
2873
2874     if (!RHS->isZero()) { // avoid X udiv 0
2875       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2876         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2877           return R;
2878       if (isa<PHINode>(Op0))
2879         if (Instruction *NV = FoldOpIntoPhi(I))
2880           return NV;
2881     }
2882   }
2883
2884   // 0 / X == 0, we don't need to preserve faults!
2885   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2886     if (LHS->equalsInt(0))
2887       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2888
2889   // It can't be division by zero, hence it must be division by one.
2890   if (I.getType() == Type::Int1Ty)
2891     return ReplaceInstUsesWith(I, Op0);
2892
2893   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2894     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2895       // div X, 1 == X
2896       if (X->isOne())
2897         return ReplaceInstUsesWith(I, Op0);
2898   }
2899
2900   return 0;
2901 }
2902
2903 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2904   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2905
2906   // Handle the integer div common cases
2907   if (Instruction *Common = commonIDivTransforms(I))
2908     return Common;
2909
2910   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2911     // X udiv C^2 -> X >> C
2912     // Check to see if this is an unsigned division with an exact power of 2,
2913     // if so, convert to a right shift.
2914     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2915       return BinaryOperator::CreateLShr(Op0, 
2916                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2917
2918     // X udiv C, where C >= signbit
2919     if (C->getValue().isNegative()) {
2920       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2921                                       I);
2922       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2923                                 ConstantInt::get(I.getType(), 1));
2924     }
2925   }
2926
2927   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2928   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2929     if (RHSI->getOpcode() == Instruction::Shl &&
2930         isa<ConstantInt>(RHSI->getOperand(0))) {
2931       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2932       if (C1.isPowerOf2()) {
2933         Value *N = RHSI->getOperand(1);
2934         const Type *NTy = N->getType();
2935         if (uint32_t C2 = C1.logBase2()) {
2936           Constant *C2V = ConstantInt::get(NTy, C2);
2937           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2938         }
2939         return BinaryOperator::CreateLShr(Op0, N);
2940       }
2941     }
2942   }
2943   
2944   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2945   // where C1&C2 are powers of two.
2946   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2947     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2948       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2949         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2950         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2951           // Compute the shift amounts
2952           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2953           // Construct the "on true" case of the select
2954           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2955           Instruction *TSI = BinaryOperator::CreateLShr(
2956                                                  Op0, TC, SI->getName()+".t");
2957           TSI = InsertNewInstBefore(TSI, I);
2958   
2959           // Construct the "on false" case of the select
2960           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2961           Instruction *FSI = BinaryOperator::CreateLShr(
2962                                                  Op0, FC, SI->getName()+".f");
2963           FSI = InsertNewInstBefore(FSI, I);
2964
2965           // construct the select instruction and return it.
2966           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2967         }
2968       }
2969   return 0;
2970 }
2971
2972 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2973   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2974
2975   // Handle the integer div common cases
2976   if (Instruction *Common = commonIDivTransforms(I))
2977     return Common;
2978
2979   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2980     // sdiv X, -1 == -X
2981     if (RHS->isAllOnesValue())
2982       return BinaryOperator::CreateNeg(Op0);
2983   }
2984
2985   // If the sign bits of both operands are zero (i.e. we can prove they are
2986   // unsigned inputs), turn this into a udiv.
2987   if (I.getType()->isInteger()) {
2988     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2989     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2990       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2991       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2992     }
2993   }      
2994   
2995   return 0;
2996 }
2997
2998 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2999   return commonDivTransforms(I);
3000 }
3001
3002 /// This function implements the transforms on rem instructions that work
3003 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3004 /// is used by the visitors to those instructions.
3005 /// @brief Transforms common to all three rem instructions
3006 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3007   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3008
3009   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3010     if (I.getType()->isFPOrFPVector())
3011       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3012     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3013   }
3014   if (isa<UndefValue>(Op1))
3015     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3016
3017   // Handle cases involving: rem X, (select Cond, Y, Z)
3018   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3019     return &I;
3020
3021   return 0;
3022 }
3023
3024 /// This function implements the transforms common to both integer remainder
3025 /// instructions (urem and srem). It is called by the visitors to those integer
3026 /// remainder instructions.
3027 /// @brief Common integer remainder transforms
3028 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3029   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3030
3031   if (Instruction *common = commonRemTransforms(I))
3032     return common;
3033
3034   // 0 % X == 0 for integer, we don't need to preserve faults!
3035   if (Constant *LHS = dyn_cast<Constant>(Op0))
3036     if (LHS->isNullValue())
3037       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3038
3039   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3040     // X % 0 == undef, we don't need to preserve faults!
3041     if (RHS->equalsInt(0))
3042       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3043     
3044     if (RHS->equalsInt(1))  // X % 1 == 0
3045       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3046
3047     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3048       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3049         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3050           return R;
3051       } else if (isa<PHINode>(Op0I)) {
3052         if (Instruction *NV = FoldOpIntoPhi(I))
3053           return NV;
3054       }
3055
3056       // See if we can fold away this rem instruction.
3057       if (SimplifyDemandedInstructionBits(I))
3058         return &I;
3059     }
3060   }
3061
3062   return 0;
3063 }
3064
3065 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3066   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3067
3068   if (Instruction *common = commonIRemTransforms(I))
3069     return common;
3070   
3071   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3072     // X urem C^2 -> X and C
3073     // Check to see if this is an unsigned remainder with an exact power of 2,
3074     // if so, convert to a bitwise and.
3075     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3076       if (C->getValue().isPowerOf2())
3077         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3078   }
3079
3080   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3081     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3082     if (RHSI->getOpcode() == Instruction::Shl &&
3083         isa<ConstantInt>(RHSI->getOperand(0))) {
3084       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3085         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3086         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3087                                                                    "tmp"), I);
3088         return BinaryOperator::CreateAnd(Op0, Add);
3089       }
3090     }
3091   }
3092
3093   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3094   // where C1&C2 are powers of two.
3095   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3096     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3097       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3098         // STO == 0 and SFO == 0 handled above.
3099         if ((STO->getValue().isPowerOf2()) && 
3100             (SFO->getValue().isPowerOf2())) {
3101           Value *TrueAnd = InsertNewInstBefore(
3102             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3103           Value *FalseAnd = InsertNewInstBefore(
3104             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3105           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3106         }
3107       }
3108   }
3109   
3110   return 0;
3111 }
3112
3113 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3114   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3115
3116   // Handle the integer rem common cases
3117   if (Instruction *common = commonIRemTransforms(I))
3118     return common;
3119   
3120   if (Value *RHSNeg = dyn_castNegVal(Op1))
3121     if (!isa<Constant>(RHSNeg) ||
3122         (isa<ConstantInt>(RHSNeg) &&
3123          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3124       // X % -Y -> X % Y
3125       AddUsesToWorkList(I);
3126       I.setOperand(1, RHSNeg);
3127       return &I;
3128     }
3129
3130   // If the sign bits of both operands are zero (i.e. we can prove they are
3131   // unsigned inputs), turn this into a urem.
3132   if (I.getType()->isInteger()) {
3133     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3134     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3135       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3136       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3137     }
3138   }
3139
3140   // If it's a constant vector, flip any negative values positive.
3141   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3142     unsigned VWidth = RHSV->getNumOperands();
3143
3144     bool hasNegative = false;
3145     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3146       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3147         if (RHS->getValue().isNegative())
3148           hasNegative = true;
3149
3150     if (hasNegative) {
3151       std::vector<Constant *> Elts(VWidth);
3152       for (unsigned i = 0; i != VWidth; ++i) {
3153         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3154           if (RHS->getValue().isNegative())
3155             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3156           else
3157             Elts[i] = RHS;
3158         }
3159       }
3160
3161       Constant *NewRHSV = ConstantVector::get(Elts);
3162       if (NewRHSV != RHSV) {
3163         AddUsesToWorkList(I);
3164         I.setOperand(1, NewRHSV);
3165         return &I;
3166       }
3167     }
3168   }
3169
3170   return 0;
3171 }
3172
3173 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3174   return commonRemTransforms(I);
3175 }
3176
3177 // isOneBitSet - Return true if there is exactly one bit set in the specified
3178 // constant.
3179 static bool isOneBitSet(const ConstantInt *CI) {
3180   return CI->getValue().isPowerOf2();
3181 }
3182
3183 // isHighOnes - Return true if the constant is of the form 1+0+.
3184 // This is the same as lowones(~X).
3185 static bool isHighOnes(const ConstantInt *CI) {
3186   return (~CI->getValue() + 1).isPowerOf2();
3187 }
3188
3189 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3190 /// are carefully arranged to allow folding of expressions such as:
3191 ///
3192 ///      (A < B) | (A > B) --> (A != B)
3193 ///
3194 /// Note that this is only valid if the first and second predicates have the
3195 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3196 ///
3197 /// Three bits are used to represent the condition, as follows:
3198 ///   0  A > B
3199 ///   1  A == B
3200 ///   2  A < B
3201 ///
3202 /// <=>  Value  Definition
3203 /// 000     0   Always false
3204 /// 001     1   A >  B
3205 /// 010     2   A == B
3206 /// 011     3   A >= B
3207 /// 100     4   A <  B
3208 /// 101     5   A != B
3209 /// 110     6   A <= B
3210 /// 111     7   Always true
3211 ///  
3212 static unsigned getICmpCode(const ICmpInst *ICI) {
3213   switch (ICI->getPredicate()) {
3214     // False -> 0
3215   case ICmpInst::ICMP_UGT: return 1;  // 001
3216   case ICmpInst::ICMP_SGT: return 1;  // 001
3217   case ICmpInst::ICMP_EQ:  return 2;  // 010
3218   case ICmpInst::ICMP_UGE: return 3;  // 011
3219   case ICmpInst::ICMP_SGE: return 3;  // 011
3220   case ICmpInst::ICMP_ULT: return 4;  // 100
3221   case ICmpInst::ICMP_SLT: return 4;  // 100
3222   case ICmpInst::ICMP_NE:  return 5;  // 101
3223   case ICmpInst::ICMP_ULE: return 6;  // 110
3224   case ICmpInst::ICMP_SLE: return 6;  // 110
3225     // True -> 7
3226   default:
3227     assert(0 && "Invalid ICmp predicate!");
3228     return 0;
3229   }
3230 }
3231
3232 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3233 /// predicate into a three bit mask. It also returns whether it is an ordered
3234 /// predicate by reference.
3235 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3236   isOrdered = false;
3237   switch (CC) {
3238   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3239   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3240   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3241   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3242   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3243   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3244   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3245   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3246   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3247   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3248   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3249   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3250   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3251   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3252     // True -> 7
3253   default:
3254     // Not expecting FCMP_FALSE and FCMP_TRUE;
3255     assert(0 && "Unexpected FCmp predicate!");
3256     return 0;
3257   }
3258 }
3259
3260 /// getICmpValue - This is the complement of getICmpCode, which turns an
3261 /// opcode and two operands into either a constant true or false, or a brand 
3262 /// new ICmp instruction. The sign is passed in to determine which kind
3263 /// of predicate to use in the new icmp instruction.
3264 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3265   switch (code) {
3266   default: assert(0 && "Illegal ICmp code!");
3267   case  0: return ConstantInt::getFalse();
3268   case  1: 
3269     if (sign)
3270       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3271     else
3272       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3273   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3274   case  3: 
3275     if (sign)
3276       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3277     else
3278       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3279   case  4: 
3280     if (sign)
3281       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3282     else
3283       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3284   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3285   case  6: 
3286     if (sign)
3287       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3288     else
3289       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3290   case  7: return ConstantInt::getTrue();
3291   }
3292 }
3293
3294 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3295 /// opcode and two operands into either a FCmp instruction. isordered is passed
3296 /// in to determine which kind of predicate to use in the new fcmp instruction.
3297 static Value *getFCmpValue(bool isordered, unsigned code,
3298                            Value *LHS, Value *RHS) {
3299   switch (code) {
3300   default: assert(0 && "Illegal FCmp code!");
3301   case  0:
3302     if (isordered)
3303       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3304     else
3305       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3306   case  1: 
3307     if (isordered)
3308       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3309     else
3310       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3311   case  2: 
3312     if (isordered)
3313       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3314     else
3315       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3316   case  3: 
3317     if (isordered)
3318       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3319     else
3320       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3321   case  4: 
3322     if (isordered)
3323       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3324     else
3325       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3326   case  5: 
3327     if (isordered)
3328       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3329     else
3330       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3331   case  6: 
3332     if (isordered)
3333       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3334     else
3335       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3336   case  7: return ConstantInt::getTrue();
3337   }
3338 }
3339
3340 /// PredicatesFoldable - Return true if both predicates match sign or if at
3341 /// least one of them is an equality comparison (which is signless).
3342 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3343   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3344          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3345          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3346 }
3347
3348 namespace { 
3349 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3350 struct FoldICmpLogical {
3351   InstCombiner &IC;
3352   Value *LHS, *RHS;
3353   ICmpInst::Predicate pred;
3354   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3355     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3356       pred(ICI->getPredicate()) {}
3357   bool shouldApply(Value *V) const {
3358     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3359       if (PredicatesFoldable(pred, ICI->getPredicate()))
3360         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3361                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3362     return false;
3363   }
3364   Instruction *apply(Instruction &Log) const {
3365     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3366     if (ICI->getOperand(0) != LHS) {
3367       assert(ICI->getOperand(1) == LHS);
3368       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3369     }
3370
3371     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3372     unsigned LHSCode = getICmpCode(ICI);
3373     unsigned RHSCode = getICmpCode(RHSICI);
3374     unsigned Code;
3375     switch (Log.getOpcode()) {
3376     case Instruction::And: Code = LHSCode & RHSCode; break;
3377     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3378     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3379     default: assert(0 && "Illegal logical opcode!"); return 0;
3380     }
3381
3382     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3383                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3384       
3385     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3386     if (Instruction *I = dyn_cast<Instruction>(RV))
3387       return I;
3388     // Otherwise, it's a constant boolean value...
3389     return IC.ReplaceInstUsesWith(Log, RV);
3390   }
3391 };
3392 } // end anonymous namespace
3393
3394 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3395 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3396 // guaranteed to be a binary operator.
3397 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3398                                     ConstantInt *OpRHS,
3399                                     ConstantInt *AndRHS,
3400                                     BinaryOperator &TheAnd) {
3401   Value *X = Op->getOperand(0);
3402   Constant *Together = 0;
3403   if (!Op->isShift())
3404     Together = And(AndRHS, OpRHS);
3405
3406   switch (Op->getOpcode()) {
3407   case Instruction::Xor:
3408     if (Op->hasOneUse()) {
3409       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3410       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3411       InsertNewInstBefore(And, TheAnd);
3412       And->takeName(Op);
3413       return BinaryOperator::CreateXor(And, Together);
3414     }
3415     break;
3416   case Instruction::Or:
3417     if (Together == AndRHS) // (X | C) & C --> C
3418       return ReplaceInstUsesWith(TheAnd, AndRHS);
3419
3420     if (Op->hasOneUse() && Together != OpRHS) {
3421       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3422       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3423       InsertNewInstBefore(Or, TheAnd);
3424       Or->takeName(Op);
3425       return BinaryOperator::CreateAnd(Or, AndRHS);
3426     }
3427     break;
3428   case Instruction::Add:
3429     if (Op->hasOneUse()) {
3430       // Adding a one to a single bit bit-field should be turned into an XOR
3431       // of the bit.  First thing to check is to see if this AND is with a
3432       // single bit constant.
3433       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3434
3435       // If there is only one bit set...
3436       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3437         // Ok, at this point, we know that we are masking the result of the
3438         // ADD down to exactly one bit.  If the constant we are adding has
3439         // no bits set below this bit, then we can eliminate the ADD.
3440         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3441
3442         // Check to see if any bits below the one bit set in AndRHSV are set.
3443         if ((AddRHS & (AndRHSV-1)) == 0) {
3444           // If not, the only thing that can effect the output of the AND is
3445           // the bit specified by AndRHSV.  If that bit is set, the effect of
3446           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3447           // no effect.
3448           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3449             TheAnd.setOperand(0, X);
3450             return &TheAnd;
3451           } else {
3452             // Pull the XOR out of the AND.
3453             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3454             InsertNewInstBefore(NewAnd, TheAnd);
3455             NewAnd->takeName(Op);
3456             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3457           }
3458         }
3459       }
3460     }
3461     break;
3462
3463   case Instruction::Shl: {
3464     // We know that the AND will not produce any of the bits shifted in, so if
3465     // the anded constant includes them, clear them now!
3466     //
3467     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3468     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3469     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3470     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3471
3472     if (CI->getValue() == ShlMask) { 
3473     // Masking out bits that the shift already masks
3474       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3475     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3476       TheAnd.setOperand(1, CI);
3477       return &TheAnd;
3478     }
3479     break;
3480   }
3481   case Instruction::LShr:
3482   {
3483     // We know that the AND will not produce any of the bits shifted in, so if
3484     // the anded constant includes them, clear them now!  This only applies to
3485     // unsigned shifts, because a signed shr may bring in set bits!
3486     //
3487     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3488     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3489     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3490     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3491
3492     if (CI->getValue() == ShrMask) {   
3493     // Masking out bits that the shift already masks.
3494       return ReplaceInstUsesWith(TheAnd, Op);
3495     } else if (CI != AndRHS) {
3496       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3497       return &TheAnd;
3498     }
3499     break;
3500   }
3501   case Instruction::AShr:
3502     // Signed shr.
3503     // See if this is shifting in some sign extension, then masking it out
3504     // with an and.
3505     if (Op->hasOneUse()) {
3506       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3507       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3508       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3509       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3510       if (C == AndRHS) {          // Masking out bits shifted in.
3511         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3512         // Make the argument unsigned.
3513         Value *ShVal = Op->getOperand(0);
3514         ShVal = InsertNewInstBefore(
3515             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3516                                    Op->getName()), TheAnd);
3517         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3518       }
3519     }
3520     break;
3521   }
3522   return 0;
3523 }
3524
3525
3526 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3527 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3528 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3529 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3530 /// insert new instructions.
3531 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3532                                            bool isSigned, bool Inside, 
3533                                            Instruction &IB) {
3534   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3535             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3536          "Lo is not <= Hi in range emission code!");
3537     
3538   if (Inside) {
3539     if (Lo == Hi)  // Trivially false.
3540       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3541
3542     // V >= Min && V < Hi --> V < Hi
3543     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3544       ICmpInst::Predicate pred = (isSigned ? 
3545         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3546       return new ICmpInst(pred, V, Hi);
3547     }
3548
3549     // Emit V-Lo <u Hi-Lo
3550     Constant *NegLo = ConstantExpr::getNeg(Lo);
3551     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3552     InsertNewInstBefore(Add, IB);
3553     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3554     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3555   }
3556
3557   if (Lo == Hi)  // Trivially true.
3558     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3559
3560   // V < Min || V >= Hi -> V > Hi-1
3561   Hi = SubOne(cast<ConstantInt>(Hi));
3562   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3563     ICmpInst::Predicate pred = (isSigned ? 
3564         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3565     return new ICmpInst(pred, V, Hi);
3566   }
3567
3568   // Emit V-Lo >u Hi-1-Lo
3569   // Note that Hi has already had one subtracted from it, above.
3570   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3571   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3572   InsertNewInstBefore(Add, IB);
3573   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3574   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3575 }
3576
3577 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3578 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3579 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3580 // not, since all 1s are not contiguous.
3581 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3582   const APInt& V = Val->getValue();
3583   uint32_t BitWidth = Val->getType()->getBitWidth();
3584   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3585
3586   // look for the first zero bit after the run of ones
3587   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3588   // look for the first non-zero bit
3589   ME = V.getActiveBits(); 
3590   return true;
3591 }
3592
3593 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3594 /// where isSub determines whether the operator is a sub.  If we can fold one of
3595 /// the following xforms:
3596 /// 
3597 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3598 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3599 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3600 ///
3601 /// return (A +/- B).
3602 ///
3603 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3604                                         ConstantInt *Mask, bool isSub,
3605                                         Instruction &I) {
3606   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3607   if (!LHSI || LHSI->getNumOperands() != 2 ||
3608       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3609
3610   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3611
3612   switch (LHSI->getOpcode()) {
3613   default: return 0;
3614   case Instruction::And:
3615     if (And(N, Mask) == Mask) {
3616       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3617       if ((Mask->getValue().countLeadingZeros() + 
3618            Mask->getValue().countPopulation()) == 
3619           Mask->getValue().getBitWidth())
3620         break;
3621
3622       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3623       // part, we don't need any explicit masks to take them out of A.  If that
3624       // is all N is, ignore it.
3625       uint32_t MB = 0, ME = 0;
3626       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3627         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3628         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3629         if (MaskedValueIsZero(RHS, Mask))
3630           break;
3631       }
3632     }
3633     return 0;
3634   case Instruction::Or:
3635   case Instruction::Xor:
3636     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3637     if ((Mask->getValue().countLeadingZeros() + 
3638          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3639         && And(N, Mask)->isZero())
3640       break;
3641     return 0;
3642   }
3643   
3644   Instruction *New;
3645   if (isSub)
3646     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3647   else
3648     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3649   return InsertNewInstBefore(New, I);
3650 }
3651
3652 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3653 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3654                                           ICmpInst *LHS, ICmpInst *RHS) {
3655   Value *Val, *Val2;
3656   ConstantInt *LHSCst, *RHSCst;
3657   ICmpInst::Predicate LHSCC, RHSCC;
3658   
3659   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3660   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3661       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3662     return 0;
3663   
3664   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3665   // where C is a power of 2
3666   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3667       LHSCst->getValue().isPowerOf2()) {
3668     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3669     InsertNewInstBefore(NewOr, I);
3670     return new ICmpInst(LHSCC, NewOr, LHSCst);
3671   }
3672   
3673   // From here on, we only handle:
3674   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3675   if (Val != Val2) return 0;
3676   
3677   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3678   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3679       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3680       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3681       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3682     return 0;
3683   
3684   // We can't fold (ugt x, C) & (sgt x, C2).
3685   if (!PredicatesFoldable(LHSCC, RHSCC))
3686     return 0;
3687     
3688   // Ensure that the larger constant is on the RHS.
3689   bool ShouldSwap;
3690   if (ICmpInst::isSignedPredicate(LHSCC) ||
3691       (ICmpInst::isEquality(LHSCC) && 
3692        ICmpInst::isSignedPredicate(RHSCC)))
3693     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3694   else
3695     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3696     
3697   if (ShouldSwap) {
3698     std::swap(LHS, RHS);
3699     std::swap(LHSCst, RHSCst);
3700     std::swap(LHSCC, RHSCC);
3701   }
3702
3703   // At this point, we know we have have two icmp instructions
3704   // comparing a value against two constants and and'ing the result
3705   // together.  Because of the above check, we know that we only have
3706   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3707   // (from the FoldICmpLogical check above), that the two constants 
3708   // are not equal and that the larger constant is on the RHS
3709   assert(LHSCst != RHSCst && "Compares not folded above?");
3710
3711   switch (LHSCC) {
3712   default: assert(0 && "Unknown integer condition code!");
3713   case ICmpInst::ICMP_EQ:
3714     switch (RHSCC) {
3715     default: assert(0 && "Unknown integer condition code!");
3716     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3717     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3718     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3719       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3720     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3721     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3722     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3723       return ReplaceInstUsesWith(I, LHS);
3724     }
3725   case ICmpInst::ICMP_NE:
3726     switch (RHSCC) {
3727     default: assert(0 && "Unknown integer condition code!");
3728     case ICmpInst::ICMP_ULT:
3729       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3730         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3731       break;                        // (X != 13 & X u< 15) -> no change
3732     case ICmpInst::ICMP_SLT:
3733       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3734         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3735       break;                        // (X != 13 & X s< 15) -> no change
3736     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3737     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3738     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3739       return ReplaceInstUsesWith(I, RHS);
3740     case ICmpInst::ICMP_NE:
3741       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3742         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3743         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3744                                                      Val->getName()+".off");
3745         InsertNewInstBefore(Add, I);
3746         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3747                             ConstantInt::get(Add->getType(), 1));
3748       }
3749       break;                        // (X != 13 & X != 15) -> no change
3750     }
3751     break;
3752   case ICmpInst::ICMP_ULT:
3753     switch (RHSCC) {
3754     default: assert(0 && "Unknown integer condition code!");
3755     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3756     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3757       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3758     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3759       break;
3760     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3761     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3762       return ReplaceInstUsesWith(I, LHS);
3763     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3764       break;
3765     }
3766     break;
3767   case ICmpInst::ICMP_SLT:
3768     switch (RHSCC) {
3769     default: assert(0 && "Unknown integer condition code!");
3770     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3771     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3772       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3773     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3774       break;
3775     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3776     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3777       return ReplaceInstUsesWith(I, LHS);
3778     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3779       break;
3780     }
3781     break;
3782   case ICmpInst::ICMP_UGT:
3783     switch (RHSCC) {
3784     default: assert(0 && "Unknown integer condition code!");
3785     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3786     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3787       return ReplaceInstUsesWith(I, RHS);
3788     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3789       break;
3790     case ICmpInst::ICMP_NE:
3791       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3792         return new ICmpInst(LHSCC, Val, RHSCst);
3793       break;                        // (X u> 13 & X != 15) -> no change
3794     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3795       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3796     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3797       break;
3798     }
3799     break;
3800   case ICmpInst::ICMP_SGT:
3801     switch (RHSCC) {
3802     default: assert(0 && "Unknown integer condition code!");
3803     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3804     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3805       return ReplaceInstUsesWith(I, RHS);
3806     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3807       break;
3808     case ICmpInst::ICMP_NE:
3809       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3810         return new ICmpInst(LHSCC, Val, RHSCst);
3811       break;                        // (X s> 13 & X != 15) -> no change
3812     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3813       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3814     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3815       break;
3816     }
3817     break;
3818   }
3819  
3820   return 0;
3821 }
3822
3823
3824 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3825   bool Changed = SimplifyCommutative(I);
3826   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3827
3828   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3829     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3830
3831   // and X, X = X
3832   if (Op0 == Op1)
3833     return ReplaceInstUsesWith(I, Op1);
3834
3835   // See if we can simplify any instructions used by the instruction whose sole 
3836   // purpose is to compute bits we don't care about.
3837   if (!isa<VectorType>(I.getType())) {
3838     if (SimplifyDemandedInstructionBits(I))
3839       return &I;
3840   } else {
3841     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3842       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3843         return ReplaceInstUsesWith(I, I.getOperand(0));
3844     } else if (isa<ConstantAggregateZero>(Op1)) {
3845       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3846     }
3847   }
3848   
3849   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3850     const APInt& AndRHSMask = AndRHS->getValue();
3851     APInt NotAndRHS(~AndRHSMask);
3852
3853     // Optimize a variety of ((val OP C1) & C2) combinations...
3854     if (isa<BinaryOperator>(Op0)) {
3855       Instruction *Op0I = cast<Instruction>(Op0);
3856       Value *Op0LHS = Op0I->getOperand(0);
3857       Value *Op0RHS = Op0I->getOperand(1);
3858       switch (Op0I->getOpcode()) {
3859       case Instruction::Xor:
3860       case Instruction::Or:
3861         // If the mask is only needed on one incoming arm, push it up.
3862         if (Op0I->hasOneUse()) {
3863           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3864             // Not masking anything out for the LHS, move to RHS.
3865             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3866                                                    Op0RHS->getName()+".masked");
3867             InsertNewInstBefore(NewRHS, I);
3868             return BinaryOperator::Create(
3869                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3870           }
3871           if (!isa<Constant>(Op0RHS) &&
3872               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3873             // Not masking anything out for the RHS, move to LHS.
3874             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3875                                                    Op0LHS->getName()+".masked");
3876             InsertNewInstBefore(NewLHS, I);
3877             return BinaryOperator::Create(
3878                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3879           }
3880         }
3881
3882         break;
3883       case Instruction::Add:
3884         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3885         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3886         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3887         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3888           return BinaryOperator::CreateAnd(V, AndRHS);
3889         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3890           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3891         break;
3892
3893       case Instruction::Sub:
3894         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3895         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3896         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3897         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3898           return BinaryOperator::CreateAnd(V, AndRHS);
3899
3900         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3901         // has 1's for all bits that the subtraction with A might affect.
3902         if (Op0I->hasOneUse()) {
3903           uint32_t BitWidth = AndRHSMask.getBitWidth();
3904           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3905           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3906
3907           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3908           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3909               MaskedValueIsZero(Op0LHS, Mask)) {
3910             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3911             InsertNewInstBefore(NewNeg, I);
3912             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3913           }
3914         }
3915         break;
3916
3917       case Instruction::Shl:
3918       case Instruction::LShr:
3919         // (1 << x) & 1 --> zext(x == 0)
3920         // (1 >> x) & 1 --> zext(x == 0)
3921         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3922           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3923                                            Constant::getNullValue(I.getType()));
3924           InsertNewInstBefore(NewICmp, I);
3925           return new ZExtInst(NewICmp, I.getType());
3926         }
3927         break;
3928       }
3929
3930       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3931         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3932           return Res;
3933     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3934       // If this is an integer truncation or change from signed-to-unsigned, and
3935       // if the source is an and/or with immediate, transform it.  This
3936       // frequently occurs for bitfield accesses.
3937       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3938         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3939             CastOp->getNumOperands() == 2)
3940           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3941             if (CastOp->getOpcode() == Instruction::And) {
3942               // Change: and (cast (and X, C1) to T), C2
3943               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3944               // This will fold the two constants together, which may allow 
3945               // other simplifications.
3946               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3947                 CastOp->getOperand(0), I.getType(), 
3948                 CastOp->getName()+".shrunk");
3949               NewCast = InsertNewInstBefore(NewCast, I);
3950               // trunc_or_bitcast(C1)&C2
3951               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3952               C3 = ConstantExpr::getAnd(C3, AndRHS);
3953               return BinaryOperator::CreateAnd(NewCast, C3);
3954             } else if (CastOp->getOpcode() == Instruction::Or) {
3955               // Change: and (cast (or X, C1) to T), C2
3956               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3957               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3958               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3959                 return ReplaceInstUsesWith(I, AndRHS);
3960             }
3961           }
3962       }
3963     }
3964
3965     // Try to fold constant and into select arguments.
3966     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3967       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3968         return R;
3969     if (isa<PHINode>(Op0))
3970       if (Instruction *NV = FoldOpIntoPhi(I))
3971         return NV;
3972   }
3973
3974   Value *Op0NotVal = dyn_castNotVal(Op0);
3975   Value *Op1NotVal = dyn_castNotVal(Op1);
3976
3977   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3978     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3979
3980   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3981   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3982     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3983                                                I.getName()+".demorgan");
3984     InsertNewInstBefore(Or, I);
3985     return BinaryOperator::CreateNot(Or);
3986   }
3987   
3988   {
3989     Value *A = 0, *B = 0, *C = 0, *D = 0;
3990     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3991       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3992         return ReplaceInstUsesWith(I, Op1);
3993     
3994       // (A|B) & ~(A&B) -> A^B
3995       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3996         if ((A == C && B == D) || (A == D && B == C))
3997           return BinaryOperator::CreateXor(A, B);
3998       }
3999     }
4000     
4001     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4002       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4003         return ReplaceInstUsesWith(I, Op0);
4004
4005       // ~(A&B) & (A|B) -> A^B
4006       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4007         if ((A == C && B == D) || (A == D && B == C))
4008           return BinaryOperator::CreateXor(A, B);
4009       }
4010     }
4011     
4012     if (Op0->hasOneUse() &&
4013         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4014       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4015         I.swapOperands();     // Simplify below
4016         std::swap(Op0, Op1);
4017       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4018         cast<BinaryOperator>(Op0)->swapOperands();
4019         I.swapOperands();     // Simplify below
4020         std::swap(Op0, Op1);
4021       }
4022     }
4023
4024     if (Op1->hasOneUse() &&
4025         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4026       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4027         cast<BinaryOperator>(Op1)->swapOperands();
4028         std::swap(A, B);
4029       }
4030       if (A == Op0) {                                // A&(A^B) -> A & ~B
4031         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4032         InsertNewInstBefore(NotB, I);
4033         return BinaryOperator::CreateAnd(A, NotB);
4034       }
4035     }
4036
4037     // (A&((~A)|B)) -> A&B
4038     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4039         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4040       return BinaryOperator::CreateAnd(A, Op1);
4041     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4042         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4043       return BinaryOperator::CreateAnd(A, Op0);
4044   }
4045   
4046   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4047     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4048     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4049       return R;
4050
4051     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4052       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4053         return Res;
4054   }
4055
4056   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4057   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4058     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4059       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4060         const Type *SrcTy = Op0C->getOperand(0)->getType();
4061         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4062             // Only do this if the casts both really cause code to be generated.
4063             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4064                               I.getType(), TD) &&
4065             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4066                               I.getType(), TD)) {
4067           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4068                                                          Op1C->getOperand(0),
4069                                                          I.getName());
4070           InsertNewInstBefore(NewOp, I);
4071           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4072         }
4073       }
4074     
4075   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4076   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4077     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4078       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4079           SI0->getOperand(1) == SI1->getOperand(1) &&
4080           (SI0->hasOneUse() || SI1->hasOneUse())) {
4081         Instruction *NewOp =
4082           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4083                                                         SI1->getOperand(0),
4084                                                         SI0->getName()), I);
4085         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4086                                       SI1->getOperand(1));
4087       }
4088   }
4089
4090   // If and'ing two fcmp, try combine them into one.
4091   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4092     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4093       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4094           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4095         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4096         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4097           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4098             // If either of the constants are nans, then the whole thing returns
4099             // false.
4100             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4101               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4102             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4103                                 RHS->getOperand(0));
4104           }
4105       } else {
4106         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4107         FCmpInst::Predicate Op0CC, Op1CC;
4108         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4109             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4110           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4111             // Swap RHS operands to match LHS.
4112             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4113             std::swap(Op1LHS, Op1RHS);
4114           }
4115           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4116             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4117             if (Op0CC == Op1CC)
4118               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4119             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4120                      Op1CC == FCmpInst::FCMP_FALSE)
4121               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4122             else if (Op0CC == FCmpInst::FCMP_TRUE)
4123               return ReplaceInstUsesWith(I, Op1);
4124             else if (Op1CC == FCmpInst::FCMP_TRUE)
4125               return ReplaceInstUsesWith(I, Op0);
4126             bool Op0Ordered;
4127             bool Op1Ordered;
4128             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4129             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4130             if (Op1Pred == 0) {
4131               std::swap(Op0, Op1);
4132               std::swap(Op0Pred, Op1Pred);
4133               std::swap(Op0Ordered, Op1Ordered);
4134             }
4135             if (Op0Pred == 0) {
4136               // uno && ueq -> uno && (uno || eq) -> ueq
4137               // ord && olt -> ord && (ord && lt) -> olt
4138               if (Op0Ordered == Op1Ordered)
4139                 return ReplaceInstUsesWith(I, Op1);
4140               // uno && oeq -> uno && (ord && eq) -> false
4141               // uno && ord -> false
4142               if (!Op0Ordered)
4143                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4144               // ord && ueq -> ord && (uno || eq) -> oeq
4145               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4146                                                     Op0LHS, Op0RHS));
4147             }
4148           }
4149         }
4150       }
4151     }
4152   }
4153
4154   return Changed ? &I : 0;
4155 }
4156
4157 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4158 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4159 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4160 /// the expression came from the corresponding "byte swapped" byte in some other
4161 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4162 /// we know that the expression deposits the low byte of %X into the high byte
4163 /// of the bswap result and that all other bytes are zero.  This expression is
4164 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4165 /// match.
4166 ///
4167 /// This function returns true if the match was unsuccessful and false if so.
4168 /// On entry to the function the "OverallLeftShift" is a signed integer value
4169 /// indicating the number of bytes that the subexpression is later shifted.  For
4170 /// example, if the expression is later right shifted by 16 bits, the
4171 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4172 /// byte of ByteValues is actually being set.
4173 ///
4174 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4175 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4176 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4177 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4178 /// always in the local (OverallLeftShift) coordinate space.
4179 ///
4180 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4181                               SmallVector<Value*, 8> &ByteValues) {
4182   if (Instruction *I = dyn_cast<Instruction>(V)) {
4183     // If this is an or instruction, it may be an inner node of the bswap.
4184     if (I->getOpcode() == Instruction::Or) {
4185       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4186                                ByteValues) ||
4187              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4188                                ByteValues);
4189     }
4190   
4191     // If this is a logical shift by a constant multiple of 8, recurse with
4192     // OverallLeftShift and ByteMask adjusted.
4193     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4194       unsigned ShAmt = 
4195         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4196       // Ensure the shift amount is defined and of a byte value.
4197       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4198         return true;
4199
4200       unsigned ByteShift = ShAmt >> 3;
4201       if (I->getOpcode() == Instruction::Shl) {
4202         // X << 2 -> collect(X, +2)
4203         OverallLeftShift += ByteShift;
4204         ByteMask >>= ByteShift;
4205       } else {
4206         // X >>u 2 -> collect(X, -2)
4207         OverallLeftShift -= ByteShift;
4208         ByteMask <<= ByteShift;
4209         ByteMask &= (~0U >> (32-ByteValues.size()));
4210       }
4211
4212       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4213       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4214
4215       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4216                                ByteValues);
4217     }
4218
4219     // If this is a logical 'and' with a mask that clears bytes, clear the
4220     // corresponding bytes in ByteMask.
4221     if (I->getOpcode() == Instruction::And &&
4222         isa<ConstantInt>(I->getOperand(1))) {
4223       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4224       unsigned NumBytes = ByteValues.size();
4225       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4226       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4227       
4228       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4229         // If this byte is masked out by a later operation, we don't care what
4230         // the and mask is.
4231         if ((ByteMask & (1 << i)) == 0)
4232           continue;
4233         
4234         // If the AndMask is all zeros for this byte, clear the bit.
4235         APInt MaskB = AndMask & Byte;
4236         if (MaskB == 0) {
4237           ByteMask &= ~(1U << i);
4238           continue;
4239         }
4240         
4241         // If the AndMask is not all ones for this byte, it's not a bytezap.
4242         if (MaskB != Byte)
4243           return true;
4244
4245         // Otherwise, this byte is kept.
4246       }
4247
4248       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4249                                ByteValues);
4250     }
4251   }
4252   
4253   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4254   // the input value to the bswap.  Some observations: 1) if more than one byte
4255   // is demanded from this input, then it could not be successfully assembled
4256   // into a byteswap.  At least one of the two bytes would not be aligned with
4257   // their ultimate destination.
4258   if (!isPowerOf2_32(ByteMask)) return true;
4259   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4260   
4261   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4262   // is demanded, it needs to go into byte 0 of the result.  This means that the
4263   // byte needs to be shifted until it lands in the right byte bucket.  The
4264   // shift amount depends on the position: if the byte is coming from the high
4265   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4266   // low part, it must be shifted left.
4267   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4268   if (InputByteNo < ByteValues.size()/2) {
4269     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4270       return true;
4271   } else {
4272     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4273       return true;
4274   }
4275   
4276   // If the destination byte value is already defined, the values are or'd
4277   // together, which isn't a bswap (unless it's an or of the same bits).
4278   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4279     return true;
4280   ByteValues[DestByteNo] = V;
4281   return false;
4282 }
4283
4284 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4285 /// If so, insert the new bswap intrinsic and return it.
4286 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4287   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4288   if (!ITy || ITy->getBitWidth() % 16 || 
4289       // ByteMask only allows up to 32-byte values.
4290       ITy->getBitWidth() > 32*8) 
4291     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4292   
4293   /// ByteValues - For each byte of the result, we keep track of which value
4294   /// defines each byte.
4295   SmallVector<Value*, 8> ByteValues;
4296   ByteValues.resize(ITy->getBitWidth()/8);
4297     
4298   // Try to find all the pieces corresponding to the bswap.
4299   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4300   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4301     return 0;
4302   
4303   // Check to see if all of the bytes come from the same value.
4304   Value *V = ByteValues[0];
4305   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4306   
4307   // Check to make sure that all of the bytes come from the same value.
4308   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4309     if (ByteValues[i] != V)
4310       return 0;
4311   const Type *Tys[] = { ITy };
4312   Module *M = I.getParent()->getParent()->getParent();
4313   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4314   return CallInst::Create(F, V);
4315 }
4316
4317 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4318 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4319 /// we can simplify this expression to "cond ? C : D or B".
4320 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4321                                          Value *C, Value *D) {
4322   // If A is not a select of -1/0, this cannot match.
4323   Value *Cond = 0;
4324   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4325     return 0;
4326
4327   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4328   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4329     return SelectInst::Create(Cond, C, B);
4330   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4331     return SelectInst::Create(Cond, C, B);
4332   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4333   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4334     return SelectInst::Create(Cond, C, D);
4335   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4336     return SelectInst::Create(Cond, C, D);
4337   return 0;
4338 }
4339
4340 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4341 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4342                                          ICmpInst *LHS, ICmpInst *RHS) {
4343   Value *Val, *Val2;
4344   ConstantInt *LHSCst, *RHSCst;
4345   ICmpInst::Predicate LHSCC, RHSCC;
4346   
4347   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4348   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4349       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4350     return 0;
4351   
4352   // From here on, we only handle:
4353   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4354   if (Val != Val2) return 0;
4355   
4356   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4357   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4358       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4359       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4360       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4361     return 0;
4362   
4363   // We can't fold (ugt x, C) | (sgt x, C2).
4364   if (!PredicatesFoldable(LHSCC, RHSCC))
4365     return 0;
4366   
4367   // Ensure that the larger constant is on the RHS.
4368   bool ShouldSwap;
4369   if (ICmpInst::isSignedPredicate(LHSCC) ||
4370       (ICmpInst::isEquality(LHSCC) && 
4371        ICmpInst::isSignedPredicate(RHSCC)))
4372     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4373   else
4374     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4375   
4376   if (ShouldSwap) {
4377     std::swap(LHS, RHS);
4378     std::swap(LHSCst, RHSCst);
4379     std::swap(LHSCC, RHSCC);
4380   }
4381   
4382   // At this point, we know we have have two icmp instructions
4383   // comparing a value against two constants and or'ing the result
4384   // together.  Because of the above check, we know that we only have
4385   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4386   // FoldICmpLogical check above), that the two constants are not
4387   // equal.
4388   assert(LHSCst != RHSCst && "Compares not folded above?");
4389
4390   switch (LHSCC) {
4391   default: assert(0 && "Unknown integer condition code!");
4392   case ICmpInst::ICMP_EQ:
4393     switch (RHSCC) {
4394     default: assert(0 && "Unknown integer condition code!");
4395     case ICmpInst::ICMP_EQ:
4396       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4397         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4398         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4399                                                      Val->getName()+".off");
4400         InsertNewInstBefore(Add, I);
4401         AddCST = Subtract(AddOne(RHSCst), LHSCst);
4402         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4403       }
4404       break;                         // (X == 13 | X == 15) -> no change
4405     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4406     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4407       break;
4408     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4409     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4410     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4411       return ReplaceInstUsesWith(I, RHS);
4412     }
4413     break;
4414   case ICmpInst::ICMP_NE:
4415     switch (RHSCC) {
4416     default: assert(0 && "Unknown integer condition code!");
4417     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4418     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4419     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4420       return ReplaceInstUsesWith(I, LHS);
4421     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4422     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4423     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4424       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4425     }
4426     break;
4427   case ICmpInst::ICMP_ULT:
4428     switch (RHSCC) {
4429     default: assert(0 && "Unknown integer condition code!");
4430     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4431       break;
4432     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4433       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4434       // this can cause overflow.
4435       if (RHSCst->isMaxValue(false))
4436         return ReplaceInstUsesWith(I, LHS);
4437       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4438     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4439       break;
4440     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4441     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4442       return ReplaceInstUsesWith(I, RHS);
4443     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4444       break;
4445     }
4446     break;
4447   case ICmpInst::ICMP_SLT:
4448     switch (RHSCC) {
4449     default: assert(0 && "Unknown integer condition code!");
4450     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4451       break;
4452     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4453       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4454       // this can cause overflow.
4455       if (RHSCst->isMaxValue(true))
4456         return ReplaceInstUsesWith(I, LHS);
4457       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4458     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4459       break;
4460     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4461     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4462       return ReplaceInstUsesWith(I, RHS);
4463     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4464       break;
4465     }
4466     break;
4467   case ICmpInst::ICMP_UGT:
4468     switch (RHSCC) {
4469     default: assert(0 && "Unknown integer condition code!");
4470     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4471     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4472       return ReplaceInstUsesWith(I, LHS);
4473     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4474       break;
4475     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4476     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4477       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4478     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4479       break;
4480     }
4481     break;
4482   case ICmpInst::ICMP_SGT:
4483     switch (RHSCC) {
4484     default: assert(0 && "Unknown integer condition code!");
4485     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4486     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4487       return ReplaceInstUsesWith(I, LHS);
4488     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4489       break;
4490     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4491     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4492       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4493     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4494       break;
4495     }
4496     break;
4497   }
4498   return 0;
4499 }
4500
4501 /// FoldOrWithConstants - This helper function folds:
4502 ///
4503 ///     ((A | B) & C1) | (B & C2)
4504 ///
4505 /// into:
4506 /// 
4507 ///     (A & C1) | B
4508 ///
4509 /// when the XOR of the two constants is "all ones" (-1).
4510 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4511                                                Value *A, Value *B, Value *C) {
4512   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4513   if (!CI1) return 0;
4514
4515   Value *V1 = 0;
4516   ConstantInt *CI2 = 0;
4517   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4518
4519   APInt Xor = CI1->getValue() ^ CI2->getValue();
4520   if (!Xor.isAllOnesValue()) return 0;
4521
4522   if (V1 == A || V1 == B) {
4523     Instruction *NewOp =
4524       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4525     return BinaryOperator::CreateOr(NewOp, V1);
4526   }
4527
4528   return 0;
4529 }
4530
4531 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4532   bool Changed = SimplifyCommutative(I);
4533   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4534
4535   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4536     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4537
4538   // or X, X = X
4539   if (Op0 == Op1)
4540     return ReplaceInstUsesWith(I, Op0);
4541
4542   // See if we can simplify any instructions used by the instruction whose sole 
4543   // purpose is to compute bits we don't care about.
4544   if (!isa<VectorType>(I.getType())) {
4545     if (SimplifyDemandedInstructionBits(I))
4546       return &I;
4547   } else if (isa<ConstantAggregateZero>(Op1)) {
4548     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4549   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4550     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4551       return ReplaceInstUsesWith(I, I.getOperand(1));
4552   }
4553     
4554
4555   
4556   // or X, -1 == -1
4557   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4558     ConstantInt *C1 = 0; Value *X = 0;
4559     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4560     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4561       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4562       InsertNewInstBefore(Or, I);
4563       Or->takeName(Op0);
4564       return BinaryOperator::CreateAnd(Or, 
4565                ConstantInt::get(RHS->getValue() | C1->getValue()));
4566     }
4567
4568     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4569     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4570       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4571       InsertNewInstBefore(Or, I);
4572       Or->takeName(Op0);
4573       return BinaryOperator::CreateXor(Or,
4574                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4575     }
4576
4577     // Try to fold constant and into select arguments.
4578     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4579       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4580         return R;
4581     if (isa<PHINode>(Op0))
4582       if (Instruction *NV = FoldOpIntoPhi(I))
4583         return NV;
4584   }
4585
4586   Value *A = 0, *B = 0;
4587   ConstantInt *C1 = 0, *C2 = 0;
4588
4589   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4590     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4591       return ReplaceInstUsesWith(I, Op1);
4592   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4593     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4594       return ReplaceInstUsesWith(I, Op0);
4595
4596   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4597   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4598   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4599       match(Op1, m_Or(m_Value(), m_Value())) ||
4600       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4601        match(Op1, m_Shift(m_Value(), m_Value())))) {
4602     if (Instruction *BSwap = MatchBSwap(I))
4603       return BSwap;
4604   }
4605   
4606   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4607   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4608       MaskedValueIsZero(Op1, C1->getValue())) {
4609     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4610     InsertNewInstBefore(NOr, I);
4611     NOr->takeName(Op0);
4612     return BinaryOperator::CreateXor(NOr, C1);
4613   }
4614
4615   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4616   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4617       MaskedValueIsZero(Op0, C1->getValue())) {
4618     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4619     InsertNewInstBefore(NOr, I);
4620     NOr->takeName(Op0);
4621     return BinaryOperator::CreateXor(NOr, C1);
4622   }
4623
4624   // (A & C)|(B & D)
4625   Value *C = 0, *D = 0;
4626   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4627       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4628     Value *V1 = 0, *V2 = 0, *V3 = 0;
4629     C1 = dyn_cast<ConstantInt>(C);
4630     C2 = dyn_cast<ConstantInt>(D);
4631     if (C1 && C2) {  // (A & C1)|(B & C2)
4632       // If we have: ((V + N) & C1) | (V & C2)
4633       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4634       // replace with V+N.
4635       if (C1->getValue() == ~C2->getValue()) {
4636         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4637             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4638           // Add commutes, try both ways.
4639           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4640             return ReplaceInstUsesWith(I, A);
4641           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4642             return ReplaceInstUsesWith(I, A);
4643         }
4644         // Or commutes, try both ways.
4645         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4646             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4647           // Add commutes, try both ways.
4648           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4649             return ReplaceInstUsesWith(I, B);
4650           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4651             return ReplaceInstUsesWith(I, B);
4652         }
4653       }
4654       V1 = 0; V2 = 0; V3 = 0;
4655     }
4656     
4657     // Check to see if we have any common things being and'ed.  If so, find the
4658     // terms for V1 & (V2|V3).
4659     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4660       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4661         V1 = A, V2 = C, V3 = D;
4662       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4663         V1 = A, V2 = B, V3 = C;
4664       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4665         V1 = C, V2 = A, V3 = D;
4666       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4667         V1 = C, V2 = A, V3 = B;
4668       
4669       if (V1) {
4670         Value *Or =
4671           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4672         return BinaryOperator::CreateAnd(V1, Or);
4673       }
4674     }
4675
4676     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4677     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4678       return Match;
4679     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4680       return Match;
4681     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4682       return Match;
4683     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4684       return Match;
4685
4686     // ((A&~B)|(~A&B)) -> A^B
4687     if ((match(C, m_Not(m_Specific(D))) &&
4688          match(B, m_Not(m_Specific(A)))))
4689       return BinaryOperator::CreateXor(A, D);
4690     // ((~B&A)|(~A&B)) -> A^B
4691     if ((match(A, m_Not(m_Specific(D))) &&
4692          match(B, m_Not(m_Specific(C)))))
4693       return BinaryOperator::CreateXor(C, D);
4694     // ((A&~B)|(B&~A)) -> A^B
4695     if ((match(C, m_Not(m_Specific(B))) &&
4696          match(D, m_Not(m_Specific(A)))))
4697       return BinaryOperator::CreateXor(A, B);
4698     // ((~B&A)|(B&~A)) -> A^B
4699     if ((match(A, m_Not(m_Specific(B))) &&
4700          match(D, m_Not(m_Specific(C)))))
4701       return BinaryOperator::CreateXor(C, B);
4702   }
4703   
4704   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4705   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4706     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4707       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4708           SI0->getOperand(1) == SI1->getOperand(1) &&
4709           (SI0->hasOneUse() || SI1->hasOneUse())) {
4710         Instruction *NewOp =
4711         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4712                                                      SI1->getOperand(0),
4713                                                      SI0->getName()), I);
4714         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4715                                       SI1->getOperand(1));
4716       }
4717   }
4718
4719   // ((A|B)&1)|(B&-2) -> (A&1) | B
4720   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4721       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4722     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4723     if (Ret) return Ret;
4724   }
4725   // (B&-2)|((A|B)&1) -> (A&1) | B
4726   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4727       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4728     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4729     if (Ret) return Ret;
4730   }
4731
4732   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4733     if (A == Op1)   // ~A | A == -1
4734       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4735   } else {
4736     A = 0;
4737   }
4738   // Note, A is still live here!
4739   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4740     if (Op0 == B)
4741       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4742
4743     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4744     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4745       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4746                                               I.getName()+".demorgan"), I);
4747       return BinaryOperator::CreateNot(And);
4748     }
4749   }
4750
4751   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4752   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4753     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4754       return R;
4755
4756     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4757       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4758         return Res;
4759   }
4760     
4761   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4762   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4763     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4764       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4765         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4766             !isa<ICmpInst>(Op1C->getOperand(0))) {
4767           const Type *SrcTy = Op0C->getOperand(0)->getType();
4768           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4769               // Only do this if the casts both really cause code to be
4770               // generated.
4771               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4772                                 I.getType(), TD) &&
4773               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4774                                 I.getType(), TD)) {
4775             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4776                                                           Op1C->getOperand(0),
4777                                                           I.getName());
4778             InsertNewInstBefore(NewOp, I);
4779             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4780           }
4781         }
4782       }
4783   }
4784   
4785     
4786   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4787   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4788     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4789       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4790           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4791           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4792         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4793           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4794             // If either of the constants are nans, then the whole thing returns
4795             // true.
4796             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4797               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4798             
4799             // Otherwise, no need to compare the two constants, compare the
4800             // rest.
4801             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4802                                 RHS->getOperand(0));
4803           }
4804       } else {
4805         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4806         FCmpInst::Predicate Op0CC, Op1CC;
4807         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4808             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4809           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4810             // Swap RHS operands to match LHS.
4811             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4812             std::swap(Op1LHS, Op1RHS);
4813           }
4814           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4815             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4816             if (Op0CC == Op1CC)
4817               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4818             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4819                      Op1CC == FCmpInst::FCMP_TRUE)
4820               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4821             else if (Op0CC == FCmpInst::FCMP_FALSE)
4822               return ReplaceInstUsesWith(I, Op1);
4823             else if (Op1CC == FCmpInst::FCMP_FALSE)
4824               return ReplaceInstUsesWith(I, Op0);
4825             bool Op0Ordered;
4826             bool Op1Ordered;
4827             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4828             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4829             if (Op0Ordered == Op1Ordered) {
4830               // If both are ordered or unordered, return a new fcmp with
4831               // or'ed predicates.
4832               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4833                                        Op0LHS, Op0RHS);
4834               if (Instruction *I = dyn_cast<Instruction>(RV))
4835                 return I;
4836               // Otherwise, it's a constant boolean value...
4837               return ReplaceInstUsesWith(I, RV);
4838             }
4839           }
4840         }
4841       }
4842     }
4843   }
4844
4845   return Changed ? &I : 0;
4846 }
4847
4848 namespace {
4849
4850 // XorSelf - Implements: X ^ X --> 0
4851 struct XorSelf {
4852   Value *RHS;
4853   XorSelf(Value *rhs) : RHS(rhs) {}
4854   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4855   Instruction *apply(BinaryOperator &Xor) const {
4856     return &Xor;
4857   }
4858 };
4859
4860 }
4861
4862 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4863   bool Changed = SimplifyCommutative(I);
4864   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4865
4866   if (isa<UndefValue>(Op1)) {
4867     if (isa<UndefValue>(Op0))
4868       // Handle undef ^ undef -> 0 special case. This is a common
4869       // idiom (misuse).
4870       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4871     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4872   }
4873
4874   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4875   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4876     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4877     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4878   }
4879   
4880   // See if we can simplify any instructions used by the instruction whose sole 
4881   // purpose is to compute bits we don't care about.
4882   if (!isa<VectorType>(I.getType())) {
4883     if (SimplifyDemandedInstructionBits(I))
4884       return &I;
4885   } else if (isa<ConstantAggregateZero>(Op1)) {
4886     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4887   }
4888
4889   // Is this a ~ operation?
4890   if (Value *NotOp = dyn_castNotVal(&I)) {
4891     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4892     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4893     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4894       if (Op0I->getOpcode() == Instruction::And || 
4895           Op0I->getOpcode() == Instruction::Or) {
4896         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4897         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4898           Instruction *NotY =
4899             BinaryOperator::CreateNot(Op0I->getOperand(1),
4900                                       Op0I->getOperand(1)->getName()+".not");
4901           InsertNewInstBefore(NotY, I);
4902           if (Op0I->getOpcode() == Instruction::And)
4903             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4904           else
4905             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4906         }
4907       }
4908     }
4909   }
4910   
4911   
4912   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4913     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4914       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4915       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4916         return new ICmpInst(ICI->getInversePredicate(),
4917                             ICI->getOperand(0), ICI->getOperand(1));
4918
4919       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4920         return new FCmpInst(FCI->getInversePredicate(),
4921                             FCI->getOperand(0), FCI->getOperand(1));
4922     }
4923
4924     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4925     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4926       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4927         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4928           Instruction::CastOps Opcode = Op0C->getOpcode();
4929           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4930             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4931                                              Op0C->getDestTy())) {
4932               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4933                                      CI->getOpcode(), CI->getInversePredicate(),
4934                                      CI->getOperand(0), CI->getOperand(1)), I);
4935               NewCI->takeName(CI);
4936               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4937             }
4938           }
4939         }
4940       }
4941     }
4942
4943     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4944       // ~(c-X) == X-c-1 == X+(-c-1)
4945       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4946         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4947           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4948           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4949                                               ConstantInt::get(I.getType(), 1));
4950           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4951         }
4952           
4953       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4954         if (Op0I->getOpcode() == Instruction::Add) {
4955           // ~(X-c) --> (-c-1)-X
4956           if (RHS->isAllOnesValue()) {
4957             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4958             return BinaryOperator::CreateSub(
4959                            ConstantExpr::getSub(NegOp0CI,
4960                                              ConstantInt::get(I.getType(), 1)),
4961                                           Op0I->getOperand(0));
4962           } else if (RHS->getValue().isSignBit()) {
4963             // (X + C) ^ signbit -> (X + C + signbit)
4964             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4965             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4966
4967           }
4968         } else if (Op0I->getOpcode() == Instruction::Or) {
4969           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4970           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4971             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4972             // Anything in both C1 and C2 is known to be zero, remove it from
4973             // NewRHS.
4974             Constant *CommonBits = And(Op0CI, RHS);
4975             NewRHS = ConstantExpr::getAnd(NewRHS, 
4976                                           ConstantExpr::getNot(CommonBits));
4977             AddToWorkList(Op0I);
4978             I.setOperand(0, Op0I->getOperand(0));
4979             I.setOperand(1, NewRHS);
4980             return &I;
4981           }
4982         }
4983       }
4984     }
4985
4986     // Try to fold constant and into select arguments.
4987     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4988       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4989         return R;
4990     if (isa<PHINode>(Op0))
4991       if (Instruction *NV = FoldOpIntoPhi(I))
4992         return NV;
4993   }
4994
4995   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4996     if (X == Op1)
4997       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4998
4999   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5000     if (X == Op0)
5001       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5002
5003   
5004   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5005   if (Op1I) {
5006     Value *A, *B;
5007     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5008       if (A == Op0) {              // B^(B|A) == (A|B)^B
5009         Op1I->swapOperands();
5010         I.swapOperands();
5011         std::swap(Op0, Op1);
5012       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5013         I.swapOperands();     // Simplified below.
5014         std::swap(Op0, Op1);
5015       }
5016     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5017       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5018     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5019       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5020     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5021       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5022         Op1I->swapOperands();
5023         std::swap(A, B);
5024       }
5025       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5026         I.swapOperands();     // Simplified below.
5027         std::swap(Op0, Op1);
5028       }
5029     }
5030   }
5031   
5032   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5033   if (Op0I) {
5034     Value *A, *B;
5035     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5036       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5037         std::swap(A, B);
5038       if (B == Op1) {                                // (A|B)^B == A & ~B
5039         Instruction *NotB =
5040           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5041         return BinaryOperator::CreateAnd(A, NotB);
5042       }
5043     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5044       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5045     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5046       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5047     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5048       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5049         std::swap(A, B);
5050       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5051           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5052         Instruction *N =
5053           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5054         return BinaryOperator::CreateAnd(N, Op1);
5055       }
5056     }
5057   }
5058   
5059   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5060   if (Op0I && Op1I && Op0I->isShift() && 
5061       Op0I->getOpcode() == Op1I->getOpcode() && 
5062       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5063       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5064     Instruction *NewOp =
5065       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5066                                                     Op1I->getOperand(0),
5067                                                     Op0I->getName()), I);
5068     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5069                                   Op1I->getOperand(1));
5070   }
5071     
5072   if (Op0I && Op1I) {
5073     Value *A, *B, *C, *D;
5074     // (A & B)^(A | B) -> A ^ B
5075     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5076         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5077       if ((A == C && B == D) || (A == D && B == C)) 
5078         return BinaryOperator::CreateXor(A, B);
5079     }
5080     // (A | B)^(A & B) -> A ^ B
5081     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5082         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5083       if ((A == C && B == D) || (A == D && B == C)) 
5084         return BinaryOperator::CreateXor(A, B);
5085     }
5086     
5087     // (A & B)^(C & D)
5088     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5089         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5090         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5091       // (X & Y)^(X & Y) -> (Y^Z) & X
5092       Value *X = 0, *Y = 0, *Z = 0;
5093       if (A == C)
5094         X = A, Y = B, Z = D;
5095       else if (A == D)
5096         X = A, Y = B, Z = C;
5097       else if (B == C)
5098         X = B, Y = A, Z = D;
5099       else if (B == D)
5100         X = B, Y = A, Z = C;
5101       
5102       if (X) {
5103         Instruction *NewOp =
5104         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5105         return BinaryOperator::CreateAnd(NewOp, X);
5106       }
5107     }
5108   }
5109     
5110   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5111   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5112     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5113       return R;
5114
5115   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5116   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5117     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5118       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5119         const Type *SrcTy = Op0C->getOperand(0)->getType();
5120         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5121             // Only do this if the casts both really cause code to be generated.
5122             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5123                               I.getType(), TD) &&
5124             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5125                               I.getType(), TD)) {
5126           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5127                                                          Op1C->getOperand(0),
5128                                                          I.getName());
5129           InsertNewInstBefore(NewOp, I);
5130           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5131         }
5132       }
5133   }
5134
5135   return Changed ? &I : 0;
5136 }
5137
5138 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5139 /// overflowed for this type.
5140 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5141                             ConstantInt *In2, bool IsSigned = false) {
5142   Result = cast<ConstantInt>(Add(In1, In2));
5143
5144   if (IsSigned)
5145     if (In2->getValue().isNegative())
5146       return Result->getValue().sgt(In1->getValue());
5147     else
5148       return Result->getValue().slt(In1->getValue());
5149   else
5150     return Result->getValue().ult(In1->getValue());
5151 }
5152
5153 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5154 /// overflowed for this type.
5155 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5156                             ConstantInt *In2, bool IsSigned = false) {
5157   Result = cast<ConstantInt>(Subtract(In1, In2));
5158
5159   if (IsSigned)
5160     if (In2->getValue().isNegative())
5161       return Result->getValue().slt(In1->getValue());
5162     else
5163       return Result->getValue().sgt(In1->getValue());
5164   else
5165     return Result->getValue().ugt(In1->getValue());
5166 }
5167
5168 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5169 /// code necessary to compute the offset from the base pointer (without adding
5170 /// in the base pointer).  Return the result as a signed integer of intptr size.
5171 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5172   TargetData &TD = IC.getTargetData();
5173   gep_type_iterator GTI = gep_type_begin(GEP);
5174   const Type *IntPtrTy = TD.getIntPtrType();
5175   Value *Result = Constant::getNullValue(IntPtrTy);
5176
5177   // Build a mask for high order bits.
5178   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5179   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5180
5181   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5182        ++i, ++GTI) {
5183     Value *Op = *i;
5184     uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
5185     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5186       if (OpC->isZero()) continue;
5187       
5188       // Handle a struct index, which adds its field offset to the pointer.
5189       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5190         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5191         
5192         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5193           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5194         else
5195           Result = IC.InsertNewInstBefore(
5196                    BinaryOperator::CreateAdd(Result,
5197                                              ConstantInt::get(IntPtrTy, Size),
5198                                              GEP->getName()+".offs"), I);
5199         continue;
5200       }
5201       
5202       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5203       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5204       Scale = ConstantExpr::getMul(OC, Scale);
5205       if (Constant *RC = dyn_cast<Constant>(Result))
5206         Result = ConstantExpr::getAdd(RC, Scale);
5207       else {
5208         // Emit an add instruction.
5209         Result = IC.InsertNewInstBefore(
5210            BinaryOperator::CreateAdd(Result, Scale,
5211                                      GEP->getName()+".offs"), I);
5212       }
5213       continue;
5214     }
5215     // Convert to correct type.
5216     if (Op->getType() != IntPtrTy) {
5217       if (Constant *OpC = dyn_cast<Constant>(Op))
5218         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5219       else
5220         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5221                                                  Op->getName()+".c"), I);
5222     }
5223     if (Size != 1) {
5224       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5225       if (Constant *OpC = dyn_cast<Constant>(Op))
5226         Op = ConstantExpr::getMul(OpC, Scale);
5227       else    // We'll let instcombine(mul) convert this to a shl if possible.
5228         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5229                                                   GEP->getName()+".idx"), I);
5230     }
5231
5232     // Emit an add instruction.
5233     if (isa<Constant>(Op) && isa<Constant>(Result))
5234       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5235                                     cast<Constant>(Result));
5236     else
5237       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5238                                                   GEP->getName()+".offs"), I);
5239   }
5240   return Result;
5241 }
5242
5243
5244 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5245 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5246 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5247 /// complex, and scales are involved.  The above expression would also be legal
5248 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5249 /// later form is less amenable to optimization though, and we are allowed to
5250 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5251 ///
5252 /// If we can't emit an optimized form for this expression, this returns null.
5253 /// 
5254 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5255                                           InstCombiner &IC) {
5256   TargetData &TD = IC.getTargetData();
5257   gep_type_iterator GTI = gep_type_begin(GEP);
5258
5259   // Check to see if this gep only has a single variable index.  If so, and if
5260   // any constant indices are a multiple of its scale, then we can compute this
5261   // in terms of the scale of the variable index.  For example, if the GEP
5262   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5263   // because the expression will cross zero at the same point.
5264   unsigned i, e = GEP->getNumOperands();
5265   int64_t Offset = 0;
5266   for (i = 1; i != e; ++i, ++GTI) {
5267     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5268       // Compute the aggregate offset of constant indices.
5269       if (CI->isZero()) continue;
5270
5271       // Handle a struct index, which adds its field offset to the pointer.
5272       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5273         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5274       } else {
5275         uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
5276         Offset += Size*CI->getSExtValue();
5277       }
5278     } else {
5279       // Found our variable index.
5280       break;
5281     }
5282   }
5283   
5284   // If there are no variable indices, we must have a constant offset, just
5285   // evaluate it the general way.
5286   if (i == e) return 0;
5287   
5288   Value *VariableIdx = GEP->getOperand(i);
5289   // Determine the scale factor of the variable element.  For example, this is
5290   // 4 if the variable index is into an array of i32.
5291   uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
5292   
5293   // Verify that there are no other variable indices.  If so, emit the hard way.
5294   for (++i, ++GTI; i != e; ++i, ++GTI) {
5295     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5296     if (!CI) return 0;
5297    
5298     // Compute the aggregate offset of constant indices.
5299     if (CI->isZero()) continue;
5300     
5301     // Handle a struct index, which adds its field offset to the pointer.
5302     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5303       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5304     } else {
5305       uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
5306       Offset += Size*CI->getSExtValue();
5307     }
5308   }
5309   
5310   // Okay, we know we have a single variable index, which must be a
5311   // pointer/array/vector index.  If there is no offset, life is simple, return
5312   // the index.
5313   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5314   if (Offset == 0) {
5315     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5316     // we don't need to bother extending: the extension won't affect where the
5317     // computation crosses zero.
5318     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5319       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5320                                   VariableIdx->getNameStart(), &I);
5321     return VariableIdx;
5322   }
5323   
5324   // Otherwise, there is an index.  The computation we will do will be modulo
5325   // the pointer size, so get it.
5326   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5327   
5328   Offset &= PtrSizeMask;
5329   VariableScale &= PtrSizeMask;
5330
5331   // To do this transformation, any constant index must be a multiple of the
5332   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5333   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5334   // multiple of the variable scale.
5335   int64_t NewOffs = Offset / (int64_t)VariableScale;
5336   if (Offset != NewOffs*(int64_t)VariableScale)
5337     return 0;
5338
5339   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5340   const Type *IntPtrTy = TD.getIntPtrType();
5341   if (VariableIdx->getType() != IntPtrTy)
5342     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5343                                               true /*SExt*/, 
5344                                               VariableIdx->getNameStart(), &I);
5345   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5346   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5347 }
5348
5349
5350 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5351 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5352 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5353                                        ICmpInst::Predicate Cond,
5354                                        Instruction &I) {
5355   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5356
5357   // Look through bitcasts.
5358   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5359     RHS = BCI->getOperand(0);
5360
5361   Value *PtrBase = GEPLHS->getOperand(0);
5362   if (PtrBase == RHS) {
5363     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5364     // This transformation (ignoring the base and scales) is valid because we
5365     // know pointers can't overflow.  See if we can output an optimized form.
5366     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5367     
5368     // If not, synthesize the offset the hard way.
5369     if (Offset == 0)
5370       Offset = EmitGEPOffset(GEPLHS, I, *this);
5371     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5372                         Constant::getNullValue(Offset->getType()));
5373   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5374     // If the base pointers are different, but the indices are the same, just
5375     // compare the base pointer.
5376     if (PtrBase != GEPRHS->getOperand(0)) {
5377       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5378       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5379                         GEPRHS->getOperand(0)->getType();
5380       if (IndicesTheSame)
5381         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5382           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5383             IndicesTheSame = false;
5384             break;
5385           }
5386
5387       // If all indices are the same, just compare the base pointers.
5388       if (IndicesTheSame)
5389         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5390                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5391
5392       // Otherwise, the base pointers are different and the indices are
5393       // different, bail out.
5394       return 0;
5395     }
5396
5397     // If one of the GEPs has all zero indices, recurse.
5398     bool AllZeros = true;
5399     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5400       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5401           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5402         AllZeros = false;
5403         break;
5404       }
5405     if (AllZeros)
5406       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5407                           ICmpInst::getSwappedPredicate(Cond), I);
5408
5409     // If the other GEP has all zero indices, recurse.
5410     AllZeros = true;
5411     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5412       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5413           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5414         AllZeros = false;
5415         break;
5416       }
5417     if (AllZeros)
5418       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5419
5420     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5421       // If the GEPs only differ by one index, compare it.
5422       unsigned NumDifferences = 0;  // Keep track of # differences.
5423       unsigned DiffOperand = 0;     // The operand that differs.
5424       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5425         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5426           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5427                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5428             // Irreconcilable differences.
5429             NumDifferences = 2;
5430             break;
5431           } else {
5432             if (NumDifferences++) break;
5433             DiffOperand = i;
5434           }
5435         }
5436
5437       if (NumDifferences == 0)   // SAME GEP?
5438         return ReplaceInstUsesWith(I, // No comparison is needed here.
5439                                    ConstantInt::get(Type::Int1Ty,
5440                                              ICmpInst::isTrueWhenEqual(Cond)));
5441
5442       else if (NumDifferences == 1) {
5443         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5444         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5445         // Make sure we do a signed comparison here.
5446         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5447       }
5448     }
5449
5450     // Only lower this if the icmp is the only user of the GEP or if we expect
5451     // the result to fold to a constant!
5452     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5453         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5454       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5455       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5456       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5457       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5458     }
5459   }
5460   return 0;
5461 }
5462
5463 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5464 ///
5465 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5466                                                 Instruction *LHSI,
5467                                                 Constant *RHSC) {
5468   if (!isa<ConstantFP>(RHSC)) return 0;
5469   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5470   
5471   // Get the width of the mantissa.  We don't want to hack on conversions that
5472   // might lose information from the integer, e.g. "i64 -> float"
5473   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5474   if (MantissaWidth == -1) return 0;  // Unknown.
5475   
5476   // Check to see that the input is converted from an integer type that is small
5477   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5478   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5479   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5480   
5481   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5482   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5483   if (LHSUnsigned)
5484     ++InputSize;
5485   
5486   // If the conversion would lose info, don't hack on this.
5487   if ((int)InputSize > MantissaWidth)
5488     return 0;
5489   
5490   // Otherwise, we can potentially simplify the comparison.  We know that it
5491   // will always come through as an integer value and we know the constant is
5492   // not a NAN (it would have been previously simplified).
5493   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5494   
5495   ICmpInst::Predicate Pred;
5496   switch (I.getPredicate()) {
5497   default: assert(0 && "Unexpected predicate!");
5498   case FCmpInst::FCMP_UEQ:
5499   case FCmpInst::FCMP_OEQ:
5500     Pred = ICmpInst::ICMP_EQ;
5501     break;
5502   case FCmpInst::FCMP_UGT:
5503   case FCmpInst::FCMP_OGT:
5504     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5505     break;
5506   case FCmpInst::FCMP_UGE:
5507   case FCmpInst::FCMP_OGE:
5508     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5509     break;
5510   case FCmpInst::FCMP_ULT:
5511   case FCmpInst::FCMP_OLT:
5512     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5513     break;
5514   case FCmpInst::FCMP_ULE:
5515   case FCmpInst::FCMP_OLE:
5516     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5517     break;
5518   case FCmpInst::FCMP_UNE:
5519   case FCmpInst::FCMP_ONE:
5520     Pred = ICmpInst::ICMP_NE;
5521     break;
5522   case FCmpInst::FCMP_ORD:
5523     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5524   case FCmpInst::FCMP_UNO:
5525     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5526   }
5527   
5528   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5529   
5530   // Now we know that the APFloat is a normal number, zero or inf.
5531   
5532   // See if the FP constant is too large for the integer.  For example,
5533   // comparing an i8 to 300.0.
5534   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5535   
5536   if (!LHSUnsigned) {
5537     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5538     // and large values.
5539     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5540     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5541                           APFloat::rmNearestTiesToEven);
5542     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5543       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5544           Pred == ICmpInst::ICMP_SLE)
5545         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5546       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5547     }
5548   } else {
5549     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5550     // +INF and large values.
5551     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5552     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5553                           APFloat::rmNearestTiesToEven);
5554     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5555       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5556           Pred == ICmpInst::ICMP_ULE)
5557         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5558       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5559     }
5560   }
5561   
5562   if (!LHSUnsigned) {
5563     // See if the RHS value is < SignedMin.
5564     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5565     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5566                           APFloat::rmNearestTiesToEven);
5567     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5568       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5569           Pred == ICmpInst::ICMP_SGE)
5570         return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5571       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5572     }
5573   }
5574
5575   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5576   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5577   // casting the FP value to the integer value and back, checking for equality.
5578   // Don't do this for zero, because -0.0 is not fractional.
5579   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5580   if (!RHS.isZero() &&
5581       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5582     // If we had a comparison against a fractional value, we have to adjust the
5583     // compare predicate and sometimes the value.  RHSC is rounded towards zero
5584     // at this point.
5585     switch (Pred) {
5586     default: assert(0 && "Unexpected integer comparison!");
5587     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5588       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5589     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5590       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5591     case ICmpInst::ICMP_ULE:
5592       // (float)int <= 4.4   --> int <= 4
5593       // (float)int <= -4.4  --> false
5594       if (RHS.isNegative())
5595         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5596       break;
5597     case ICmpInst::ICMP_SLE:
5598       // (float)int <= 4.4   --> int <= 4
5599       // (float)int <= -4.4  --> int < -4
5600       if (RHS.isNegative())
5601         Pred = ICmpInst::ICMP_SLT;
5602       break;
5603     case ICmpInst::ICMP_ULT:
5604       // (float)int < -4.4   --> false
5605       // (float)int < 4.4    --> int <= 4
5606       if (RHS.isNegative())
5607         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5608       Pred = ICmpInst::ICMP_ULE;
5609       break;
5610     case ICmpInst::ICMP_SLT:
5611       // (float)int < -4.4   --> int < -4
5612       // (float)int < 4.4    --> int <= 4
5613       if (!RHS.isNegative())
5614         Pred = ICmpInst::ICMP_SLE;
5615       break;
5616     case ICmpInst::ICMP_UGT:
5617       // (float)int > 4.4    --> int > 4
5618       // (float)int > -4.4   --> true
5619       if (RHS.isNegative())
5620         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5621       break;
5622     case ICmpInst::ICMP_SGT:
5623       // (float)int > 4.4    --> int > 4
5624       // (float)int > -4.4   --> int >= -4
5625       if (RHS.isNegative())
5626         Pred = ICmpInst::ICMP_SGE;
5627       break;
5628     case ICmpInst::ICMP_UGE:
5629       // (float)int >= -4.4   --> true
5630       // (float)int >= 4.4    --> int > 4
5631       if (!RHS.isNegative())
5632         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5633       Pred = ICmpInst::ICMP_UGT;
5634       break;
5635     case ICmpInst::ICMP_SGE:
5636       // (float)int >= -4.4   --> int >= -4
5637       // (float)int >= 4.4    --> int > 4
5638       if (!RHS.isNegative())
5639         Pred = ICmpInst::ICMP_SGT;
5640       break;
5641     }
5642   }
5643
5644   // Lower this FP comparison into an appropriate integer version of the
5645   // comparison.
5646   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5647 }
5648
5649 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5650   bool Changed = SimplifyCompare(I);
5651   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5652
5653   // Fold trivial predicates.
5654   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5655     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5656   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5657     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5658   
5659   // Simplify 'fcmp pred X, X'
5660   if (Op0 == Op1) {
5661     switch (I.getPredicate()) {
5662     default: assert(0 && "Unknown predicate!");
5663     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5664     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5665     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5666       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5667     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5668     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5669     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5670       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5671       
5672     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5673     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5674     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5675     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5676       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5677       I.setPredicate(FCmpInst::FCMP_UNO);
5678       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5679       return &I;
5680       
5681     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5682     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5683     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5684     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5685       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5686       I.setPredicate(FCmpInst::FCMP_ORD);
5687       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5688       return &I;
5689     }
5690   }
5691     
5692   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5693     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5694
5695   // Handle fcmp with constant RHS
5696   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5697     // If the constant is a nan, see if we can fold the comparison based on it.
5698     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5699       if (CFP->getValueAPF().isNaN()) {
5700         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5701           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5702         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5703                "Comparison must be either ordered or unordered!");
5704         // True if unordered.
5705         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5706       }
5707     }
5708     
5709     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5710       switch (LHSI->getOpcode()) {
5711       case Instruction::PHI:
5712         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5713         // block.  If in the same block, we're encouraging jump threading.  If
5714         // not, we are just pessimizing the code by making an i1 phi.
5715         if (LHSI->getParent() == I.getParent())
5716           if (Instruction *NV = FoldOpIntoPhi(I))
5717             return NV;
5718         break;
5719       case Instruction::SIToFP:
5720       case Instruction::UIToFP:
5721         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5722           return NV;
5723         break;
5724       case Instruction::Select:
5725         // If either operand of the select is a constant, we can fold the
5726         // comparison into the select arms, which will cause one to be
5727         // constant folded and the select turned into a bitwise or.
5728         Value *Op1 = 0, *Op2 = 0;
5729         if (LHSI->hasOneUse()) {
5730           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5731             // Fold the known value into the constant operand.
5732             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5733             // Insert a new FCmp of the other select operand.
5734             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5735                                                       LHSI->getOperand(2), RHSC,
5736                                                       I.getName()), I);
5737           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5738             // Fold the known value into the constant operand.
5739             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5740             // Insert a new FCmp of the other select operand.
5741             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5742                                                       LHSI->getOperand(1), RHSC,
5743                                                       I.getName()), I);
5744           }
5745         }
5746
5747         if (Op1)
5748           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5749         break;
5750       }
5751   }
5752
5753   return Changed ? &I : 0;
5754 }
5755
5756 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5757   bool Changed = SimplifyCompare(I);
5758   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5759   const Type *Ty = Op0->getType();
5760
5761   // icmp X, X
5762   if (Op0 == Op1)
5763     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5764                                                    I.isTrueWhenEqual()));
5765
5766   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5767     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5768   
5769   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5770   // addresses never equal each other!  We already know that Op0 != Op1.
5771   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5772        isa<ConstantPointerNull>(Op0)) &&
5773       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5774        isa<ConstantPointerNull>(Op1)))
5775     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5776                                                    !I.isTrueWhenEqual()));
5777
5778   // icmp's with boolean values can always be turned into bitwise operations
5779   if (Ty == Type::Int1Ty) {
5780     switch (I.getPredicate()) {
5781     default: assert(0 && "Invalid icmp instruction!");
5782     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5783       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5784       InsertNewInstBefore(Xor, I);
5785       return BinaryOperator::CreateNot(Xor);
5786     }
5787     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5788       return BinaryOperator::CreateXor(Op0, Op1);
5789
5790     case ICmpInst::ICMP_UGT:
5791       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5792       // FALL THROUGH
5793     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5794       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5795       InsertNewInstBefore(Not, I);
5796       return BinaryOperator::CreateAnd(Not, Op1);
5797     }
5798     case ICmpInst::ICMP_SGT:
5799       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5800       // FALL THROUGH
5801     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5802       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5803       InsertNewInstBefore(Not, I);
5804       return BinaryOperator::CreateAnd(Not, Op0);
5805     }
5806     case ICmpInst::ICMP_UGE:
5807       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5808       // FALL THROUGH
5809     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5810       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5811       InsertNewInstBefore(Not, I);
5812       return BinaryOperator::CreateOr(Not, Op1);
5813     }
5814     case ICmpInst::ICMP_SGE:
5815       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5816       // FALL THROUGH
5817     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5818       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5819       InsertNewInstBefore(Not, I);
5820       return BinaryOperator::CreateOr(Not, Op0);
5821     }
5822     }
5823   }
5824
5825   // See if we are doing a comparison with a constant.
5826   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5827     Value *A = 0, *B = 0;
5828     
5829     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5830     if (I.isEquality() && CI->isNullValue() &&
5831         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5832       // (icmp cond A B) if cond is equality
5833       return new ICmpInst(I.getPredicate(), A, B);
5834     }
5835     
5836     // If we have an icmp le or icmp ge instruction, turn it into the
5837     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5838     // them being folded in the code below.
5839     switch (I.getPredicate()) {
5840     default: break;
5841     case ICmpInst::ICMP_ULE:
5842       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5843         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5844       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5845     case ICmpInst::ICMP_SLE:
5846       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5847         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5848       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5849     case ICmpInst::ICMP_UGE:
5850       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5851         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5852       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5853     case ICmpInst::ICMP_SGE:
5854       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5855         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5856       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5857     }
5858     
5859     // See if we can fold the comparison based on range information we can get
5860     // by checking whether bits are known to be zero or one in the input.
5861     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5862     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5863     
5864     // If this comparison is a normal comparison, it demands all
5865     // bits, if it is a sign bit comparison, it only demands the sign bit.
5866     bool UnusedBit;
5867     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5868     
5869     if (SimplifyDemandedBits(I.getOperandUse(0), 
5870                              isSignBit ? APInt::getSignBit(BitWidth)
5871                                        : APInt::getAllOnesValue(BitWidth),
5872                              KnownZero, KnownOne, 0))
5873       return &I;
5874         
5875     // Given the known and unknown bits, compute a range that the LHS could be
5876     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5877     // EQ and NE we use unsigned values.
5878     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5879     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5880       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5881     else
5882       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5883     
5884     // If Min and Max are known to be the same, then SimplifyDemandedBits
5885     // figured out that the LHS is a constant.  Just constant fold this now so
5886     // that code below can assume that Min != Max.
5887     if (Min == Max)
5888       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5889                                                           ConstantInt::get(Min),
5890                                                           CI));
5891     
5892     // Based on the range information we know about the LHS, see if we can
5893     // simplify this comparison.  For example, (x&4) < 8  is always true.
5894     const APInt &RHSVal = CI->getValue();
5895     switch (I.getPredicate()) {  // LE/GE have been folded already.
5896     default: assert(0 && "Unknown icmp opcode!");
5897     case ICmpInst::ICMP_EQ:
5898       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5899         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5900       break;
5901     case ICmpInst::ICMP_NE:
5902       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5903         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5904       break;
5905     case ICmpInst::ICMP_ULT:
5906       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5907         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5908       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5909         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5910       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5911         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5912       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5913         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5914         
5915       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5916       if (CI->isMinValue(true))
5917         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5918                             ConstantInt::getAllOnesValue(Op0->getType()));
5919       break;
5920     case ICmpInst::ICMP_UGT:
5921       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5922         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5923       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5924         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5925         
5926       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5927         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5928       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5929         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5930       
5931       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5932       if (CI->isMaxValue(true))
5933         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5934                             ConstantInt::getNullValue(Op0->getType()));
5935       break;
5936     case ICmpInst::ICMP_SLT:
5937       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5938         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5939       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5940         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5941       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5942         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5943       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5944         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5945       break;
5946     case ICmpInst::ICMP_SGT: 
5947       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5948         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5949       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5950         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5951         
5952       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5953         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5954       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5955         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5956       break;
5957     }
5958   }
5959
5960   // Test if the ICmpInst instruction is used exclusively by a select as
5961   // part of a minimum or maximum operation. If so, refrain from doing
5962   // any other folding. This helps out other analyses which understand
5963   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5964   // and CodeGen. And in this case, at least one of the comparison
5965   // operands has at least one user besides the compare (the select),
5966   // which would often largely negate the benefit of folding anyway.
5967   if (I.hasOneUse())
5968     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5969       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5970           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5971         return 0;
5972
5973   // See if we are doing a comparison between a constant and an instruction that
5974   // can be folded into the comparison.
5975   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5976     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5977     // instruction, see if that instruction also has constants so that the 
5978     // instruction can be folded into the icmp 
5979     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5980       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5981         return Res;
5982   }
5983
5984   // Handle icmp with constant (but not simple integer constant) RHS
5985   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5986     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5987       switch (LHSI->getOpcode()) {
5988       case Instruction::GetElementPtr:
5989         if (RHSC->isNullValue()) {
5990           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5991           bool isAllZeros = true;
5992           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5993             if (!isa<Constant>(LHSI->getOperand(i)) ||
5994                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5995               isAllZeros = false;
5996               break;
5997             }
5998           if (isAllZeros)
5999             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6000                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6001         }
6002         break;
6003
6004       case Instruction::PHI:
6005         // Only fold icmp into the PHI if the phi and fcmp are in the same
6006         // block.  If in the same block, we're encouraging jump threading.  If
6007         // not, we are just pessimizing the code by making an i1 phi.
6008         if (LHSI->getParent() == I.getParent())
6009           if (Instruction *NV = FoldOpIntoPhi(I))
6010             return NV;
6011         break;
6012       case Instruction::Select: {
6013         // If either operand of the select is a constant, we can fold the
6014         // comparison into the select arms, which will cause one to be
6015         // constant folded and the select turned into a bitwise or.
6016         Value *Op1 = 0, *Op2 = 0;
6017         if (LHSI->hasOneUse()) {
6018           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6019             // Fold the known value into the constant operand.
6020             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6021             // Insert a new ICmp of the other select operand.
6022             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6023                                                    LHSI->getOperand(2), RHSC,
6024                                                    I.getName()), I);
6025           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6026             // Fold the known value into the constant operand.
6027             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6028             // Insert a new ICmp of the other select operand.
6029             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6030                                                    LHSI->getOperand(1), RHSC,
6031                                                    I.getName()), I);
6032           }
6033         }
6034
6035         if (Op1)
6036           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6037         break;
6038       }
6039       case Instruction::Malloc:
6040         // If we have (malloc != null), and if the malloc has a single use, we
6041         // can assume it is successful and remove the malloc.
6042         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6043           AddToWorkList(LHSI);
6044           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6045                                                          !I.isTrueWhenEqual()));
6046         }
6047         break;
6048       }
6049   }
6050
6051   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6052   if (User *GEP = dyn_castGetElementPtr(Op0))
6053     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6054       return NI;
6055   if (User *GEP = dyn_castGetElementPtr(Op1))
6056     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6057                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6058       return NI;
6059
6060   // Test to see if the operands of the icmp are casted versions of other
6061   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6062   // now.
6063   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6064     if (isa<PointerType>(Op0->getType()) && 
6065         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6066       // We keep moving the cast from the left operand over to the right
6067       // operand, where it can often be eliminated completely.
6068       Op0 = CI->getOperand(0);
6069
6070       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6071       // so eliminate it as well.
6072       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6073         Op1 = CI2->getOperand(0);
6074
6075       // If Op1 is a constant, we can fold the cast into the constant.
6076       if (Op0->getType() != Op1->getType()) {
6077         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6078           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6079         } else {
6080           // Otherwise, cast the RHS right before the icmp
6081           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6082         }
6083       }
6084       return new ICmpInst(I.getPredicate(), Op0, Op1);
6085     }
6086   }
6087   
6088   if (isa<CastInst>(Op0)) {
6089     // Handle the special case of: icmp (cast bool to X), <cst>
6090     // This comes up when you have code like
6091     //   int X = A < B;
6092     //   if (X) ...
6093     // For generality, we handle any zero-extension of any operand comparison
6094     // with a constant or another cast from the same type.
6095     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6096       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6097         return R;
6098   }
6099   
6100   // See if it's the same type of instruction on the left and right.
6101   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6102     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6103       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6104           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6105         switch (Op0I->getOpcode()) {
6106         default: break;
6107         case Instruction::Add:
6108         case Instruction::Sub:
6109         case Instruction::Xor:
6110           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6111             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6112                                 Op1I->getOperand(0));
6113           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6114           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6115             if (CI->getValue().isSignBit()) {
6116               ICmpInst::Predicate Pred = I.isSignedPredicate()
6117                                              ? I.getUnsignedPredicate()
6118                                              : I.getSignedPredicate();
6119               return new ICmpInst(Pred, Op0I->getOperand(0),
6120                                   Op1I->getOperand(0));
6121             }
6122             
6123             if (CI->getValue().isMaxSignedValue()) {
6124               ICmpInst::Predicate Pred = I.isSignedPredicate()
6125                                              ? I.getUnsignedPredicate()
6126                                              : I.getSignedPredicate();
6127               Pred = I.getSwappedPredicate(Pred);
6128               return new ICmpInst(Pred, Op0I->getOperand(0),
6129                                   Op1I->getOperand(0));
6130             }
6131           }
6132           break;
6133         case Instruction::Mul:
6134           if (!I.isEquality())
6135             break;
6136
6137           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6138             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6139             // Mask = -1 >> count-trailing-zeros(Cst).
6140             if (!CI->isZero() && !CI->isOne()) {
6141               const APInt &AP = CI->getValue();
6142               ConstantInt *Mask = ConstantInt::get(
6143                                       APInt::getLowBitsSet(AP.getBitWidth(),
6144                                                            AP.getBitWidth() -
6145                                                       AP.countTrailingZeros()));
6146               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6147                                                             Mask);
6148               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6149                                                             Mask);
6150               InsertNewInstBefore(And1, I);
6151               InsertNewInstBefore(And2, I);
6152               return new ICmpInst(I.getPredicate(), And1, And2);
6153             }
6154           }
6155           break;
6156         }
6157       }
6158     }
6159   }
6160   
6161   // ~x < ~y --> y < x
6162   { Value *A, *B;
6163     if (match(Op0, m_Not(m_Value(A))) &&
6164         match(Op1, m_Not(m_Value(B))))
6165       return new ICmpInst(I.getPredicate(), B, A);
6166   }
6167   
6168   if (I.isEquality()) {
6169     Value *A, *B, *C, *D;
6170     
6171     // -x == -y --> x == y
6172     if (match(Op0, m_Neg(m_Value(A))) &&
6173         match(Op1, m_Neg(m_Value(B))))
6174       return new ICmpInst(I.getPredicate(), A, B);
6175     
6176     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6177       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6178         Value *OtherVal = A == Op1 ? B : A;
6179         return new ICmpInst(I.getPredicate(), OtherVal,
6180                             Constant::getNullValue(A->getType()));
6181       }
6182
6183       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6184         // A^c1 == C^c2 --> A == C^(c1^c2)
6185         ConstantInt *C1, *C2;
6186         if (match(B, m_ConstantInt(C1)) &&
6187             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6188           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6189           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6190           return new ICmpInst(I.getPredicate(), A,
6191                               InsertNewInstBefore(Xor, I));
6192         }
6193         
6194         // A^B == A^D -> B == D
6195         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6196         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6197         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6198         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6199       }
6200     }
6201     
6202     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6203         (A == Op0 || B == Op0)) {
6204       // A == (A^B)  ->  B == 0
6205       Value *OtherVal = A == Op0 ? B : A;
6206       return new ICmpInst(I.getPredicate(), OtherVal,
6207                           Constant::getNullValue(A->getType()));
6208     }
6209
6210     // (A-B) == A  ->  B == 0
6211     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6212       return new ICmpInst(I.getPredicate(), B, 
6213                           Constant::getNullValue(B->getType()));
6214
6215     // A == (A-B)  ->  B == 0
6216     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6217       return new ICmpInst(I.getPredicate(), B,
6218                           Constant::getNullValue(B->getType()));
6219     
6220     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6221     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6222         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6223         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6224       Value *X = 0, *Y = 0, *Z = 0;
6225       
6226       if (A == C) {
6227         X = B; Y = D; Z = A;
6228       } else if (A == D) {
6229         X = B; Y = C; Z = A;
6230       } else if (B == C) {
6231         X = A; Y = D; Z = B;
6232       } else if (B == D) {
6233         X = A; Y = C; Z = B;
6234       }
6235       
6236       if (X) {   // Build (X^Y) & Z
6237         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6238         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6239         I.setOperand(0, Op1);
6240         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6241         return &I;
6242       }
6243     }
6244   }
6245   return Changed ? &I : 0;
6246 }
6247
6248
6249 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6250 /// and CmpRHS are both known to be integer constants.
6251 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6252                                           ConstantInt *DivRHS) {
6253   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6254   const APInt &CmpRHSV = CmpRHS->getValue();
6255   
6256   // FIXME: If the operand types don't match the type of the divide 
6257   // then don't attempt this transform. The code below doesn't have the
6258   // logic to deal with a signed divide and an unsigned compare (and
6259   // vice versa). This is because (x /s C1) <s C2  produces different 
6260   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6261   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6262   // work. :(  The if statement below tests that condition and bails 
6263   // if it finds it. 
6264   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6265   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6266     return 0;
6267   if (DivRHS->isZero())
6268     return 0; // The ProdOV computation fails on divide by zero.
6269   if (DivIsSigned && DivRHS->isAllOnesValue())
6270     return 0; // The overflow computation also screws up here
6271   if (DivRHS->isOne())
6272     return 0; // Not worth bothering, and eliminates some funny cases
6273               // with INT_MIN.
6274
6275   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6276   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6277   // C2 (CI). By solving for X we can turn this into a range check 
6278   // instead of computing a divide. 
6279   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6280
6281   // Determine if the product overflows by seeing if the product is
6282   // not equal to the divide. Make sure we do the same kind of divide
6283   // as in the LHS instruction that we're folding. 
6284   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6285                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6286
6287   // Get the ICmp opcode
6288   ICmpInst::Predicate Pred = ICI.getPredicate();
6289
6290   // Figure out the interval that is being checked.  For example, a comparison
6291   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6292   // Compute this interval based on the constants involved and the signedness of
6293   // the compare/divide.  This computes a half-open interval, keeping track of
6294   // whether either value in the interval overflows.  After analysis each
6295   // overflow variable is set to 0 if it's corresponding bound variable is valid
6296   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6297   int LoOverflow = 0, HiOverflow = 0;
6298   ConstantInt *LoBound = 0, *HiBound = 0;
6299   
6300   if (!DivIsSigned) {  // udiv
6301     // e.g. X/5 op 3  --> [15, 20)
6302     LoBound = Prod;
6303     HiOverflow = LoOverflow = ProdOV;
6304     if (!HiOverflow)
6305       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6306   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6307     if (CmpRHSV == 0) {       // (X / pos) op 0
6308       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6309       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6310       HiBound = DivRHS;
6311     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6312       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6313       HiOverflow = LoOverflow = ProdOV;
6314       if (!HiOverflow)
6315         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6316     } else {                       // (X / pos) op neg
6317       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6318       HiBound = AddOne(Prod);
6319       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6320       if (!LoOverflow) {
6321         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6322         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6323                                      true) ? -1 : 0;
6324        }
6325     }
6326   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6327     if (CmpRHSV == 0) {       // (X / neg) op 0
6328       // e.g. X/-5 op 0  --> [-4, 5)
6329       LoBound = AddOne(DivRHS);
6330       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6331       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6332         HiOverflow = 1;            // [INTMIN+1, overflow)
6333         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6334       }
6335     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6336       // e.g. X/-5 op 3  --> [-19, -14)
6337       HiBound = AddOne(Prod);
6338       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6339       if (!LoOverflow)
6340         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6341     } else {                       // (X / neg) op neg
6342       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6343       LoOverflow = HiOverflow = ProdOV;
6344       if (!HiOverflow)
6345         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6346     }
6347     
6348     // Dividing by a negative swaps the condition.  LT <-> GT
6349     Pred = ICmpInst::getSwappedPredicate(Pred);
6350   }
6351
6352   Value *X = DivI->getOperand(0);
6353   switch (Pred) {
6354   default: assert(0 && "Unhandled icmp opcode!");
6355   case ICmpInst::ICMP_EQ:
6356     if (LoOverflow && HiOverflow)
6357       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6358     else if (HiOverflow)
6359       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6360                           ICmpInst::ICMP_UGE, X, LoBound);
6361     else if (LoOverflow)
6362       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6363                           ICmpInst::ICMP_ULT, X, HiBound);
6364     else
6365       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6366   case ICmpInst::ICMP_NE:
6367     if (LoOverflow && HiOverflow)
6368       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6369     else if (HiOverflow)
6370       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6371                           ICmpInst::ICMP_ULT, X, LoBound);
6372     else if (LoOverflow)
6373       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6374                           ICmpInst::ICMP_UGE, X, HiBound);
6375     else
6376       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6377   case ICmpInst::ICMP_ULT:
6378   case ICmpInst::ICMP_SLT:
6379     if (LoOverflow == +1)   // Low bound is greater than input range.
6380       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6381     if (LoOverflow == -1)   // Low bound is less than input range.
6382       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6383     return new ICmpInst(Pred, X, LoBound);
6384   case ICmpInst::ICMP_UGT:
6385   case ICmpInst::ICMP_SGT:
6386     if (HiOverflow == +1)       // High bound greater than input range.
6387       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6388     else if (HiOverflow == -1)  // High bound less than input range.
6389       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6390     if (Pred == ICmpInst::ICMP_UGT)
6391       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6392     else
6393       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6394   }
6395 }
6396
6397
6398 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6399 ///
6400 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6401                                                           Instruction *LHSI,
6402                                                           ConstantInt *RHS) {
6403   const APInt &RHSV = RHS->getValue();
6404   
6405   switch (LHSI->getOpcode()) {
6406   case Instruction::Trunc:
6407     if (ICI.isEquality() && LHSI->hasOneUse()) {
6408       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6409       // of the high bits truncated out of x are known.
6410       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6411              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6412       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6413       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6414       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6415       
6416       // If all the high bits are known, we can do this xform.
6417       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6418         // Pull in the high bits from known-ones set.
6419         APInt NewRHS(RHS->getValue());
6420         NewRHS.zext(SrcBits);
6421         NewRHS |= KnownOne;
6422         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6423                             ConstantInt::get(NewRHS));
6424       }
6425     }
6426     break;
6427       
6428   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6429     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6430       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6431       // fold the xor.
6432       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6433           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6434         Value *CompareVal = LHSI->getOperand(0);
6435         
6436         // If the sign bit of the XorCST is not set, there is no change to
6437         // the operation, just stop using the Xor.
6438         if (!XorCST->getValue().isNegative()) {
6439           ICI.setOperand(0, CompareVal);
6440           AddToWorkList(LHSI);
6441           return &ICI;
6442         }
6443         
6444         // Was the old condition true if the operand is positive?
6445         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6446         
6447         // If so, the new one isn't.
6448         isTrueIfPositive ^= true;
6449         
6450         if (isTrueIfPositive)
6451           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6452         else
6453           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6454       }
6455
6456       if (LHSI->hasOneUse()) {
6457         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6458         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6459           const APInt &SignBit = XorCST->getValue();
6460           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6461                                          ? ICI.getUnsignedPredicate()
6462                                          : ICI.getSignedPredicate();
6463           return new ICmpInst(Pred, LHSI->getOperand(0),
6464                               ConstantInt::get(RHSV ^ SignBit));
6465         }
6466
6467         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6468         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6469           const APInt &NotSignBit = XorCST->getValue();
6470           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6471                                          ? ICI.getUnsignedPredicate()
6472                                          : ICI.getSignedPredicate();
6473           Pred = ICI.getSwappedPredicate(Pred);
6474           return new ICmpInst(Pred, LHSI->getOperand(0),
6475                               ConstantInt::get(RHSV ^ NotSignBit));
6476         }
6477       }
6478     }
6479     break;
6480   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6481     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6482         LHSI->getOperand(0)->hasOneUse()) {
6483       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6484       
6485       // If the LHS is an AND of a truncating cast, we can widen the
6486       // and/compare to be the input width without changing the value
6487       // produced, eliminating a cast.
6488       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6489         // We can do this transformation if either the AND constant does not
6490         // have its sign bit set or if it is an equality comparison. 
6491         // Extending a relational comparison when we're checking the sign
6492         // bit would not work.
6493         if (Cast->hasOneUse() &&
6494             (ICI.isEquality() ||
6495              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6496           uint32_t BitWidth = 
6497             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6498           APInt NewCST = AndCST->getValue();
6499           NewCST.zext(BitWidth);
6500           APInt NewCI = RHSV;
6501           NewCI.zext(BitWidth);
6502           Instruction *NewAnd = 
6503             BinaryOperator::CreateAnd(Cast->getOperand(0),
6504                                       ConstantInt::get(NewCST),LHSI->getName());
6505           InsertNewInstBefore(NewAnd, ICI);
6506           return new ICmpInst(ICI.getPredicate(), NewAnd,
6507                               ConstantInt::get(NewCI));
6508         }
6509       }
6510       
6511       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6512       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6513       // happens a LOT in code produced by the C front-end, for bitfield
6514       // access.
6515       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6516       if (Shift && !Shift->isShift())
6517         Shift = 0;
6518       
6519       ConstantInt *ShAmt;
6520       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6521       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6522       const Type *AndTy = AndCST->getType();          // Type of the and.
6523       
6524       // We can fold this as long as we can't shift unknown bits
6525       // into the mask.  This can only happen with signed shift
6526       // rights, as they sign-extend.
6527       if (ShAmt) {
6528         bool CanFold = Shift->isLogicalShift();
6529         if (!CanFold) {
6530           // To test for the bad case of the signed shr, see if any
6531           // of the bits shifted in could be tested after the mask.
6532           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6533           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6534           
6535           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6536           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6537                AndCST->getValue()) == 0)
6538             CanFold = true;
6539         }
6540         
6541         if (CanFold) {
6542           Constant *NewCst;
6543           if (Shift->getOpcode() == Instruction::Shl)
6544             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6545           else
6546             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6547           
6548           // Check to see if we are shifting out any of the bits being
6549           // compared.
6550           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6551             // If we shifted bits out, the fold is not going to work out.
6552             // As a special case, check to see if this means that the
6553             // result is always true or false now.
6554             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6555               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6556             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6557               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6558           } else {
6559             ICI.setOperand(1, NewCst);
6560             Constant *NewAndCST;
6561             if (Shift->getOpcode() == Instruction::Shl)
6562               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6563             else
6564               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6565             LHSI->setOperand(1, NewAndCST);
6566             LHSI->setOperand(0, Shift->getOperand(0));
6567             AddToWorkList(Shift); // Shift is dead.
6568             AddUsesToWorkList(ICI);
6569             return &ICI;
6570           }
6571         }
6572       }
6573       
6574       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6575       // preferable because it allows the C<<Y expression to be hoisted out
6576       // of a loop if Y is invariant and X is not.
6577       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6578           ICI.isEquality() && !Shift->isArithmeticShift()/* &&
6579           isa<Instruction>(Shift->getOperand(0))*/) {
6580         // Compute C << Y.
6581         Value *NS;
6582         if (Shift->getOpcode() == Instruction::LShr) {
6583           NS = BinaryOperator::CreateShl(AndCST, 
6584                                          Shift->getOperand(1), "tmp");
6585         } else {
6586           // Insert a logical shift.
6587           NS = BinaryOperator::CreateLShr(AndCST,
6588                                           Shift->getOperand(1), "tmp");
6589         }
6590         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6591         
6592         // Compute X & (C << Y).
6593         Instruction *NewAnd = 
6594           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6595         InsertNewInstBefore(NewAnd, ICI);
6596         
6597         ICI.setOperand(0, NewAnd);
6598         return &ICI;
6599       }
6600     }
6601     break;
6602     
6603   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6604     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6605     if (!ShAmt) break;
6606     
6607     uint32_t TypeBits = RHSV.getBitWidth();
6608     
6609     // Check that the shift amount is in range.  If not, don't perform
6610     // undefined shifts.  When the shift is visited it will be
6611     // simplified.
6612     if (ShAmt->uge(TypeBits))
6613       break;
6614     
6615     if (ICI.isEquality()) {
6616       // If we are comparing against bits always shifted out, the
6617       // comparison cannot succeed.
6618       Constant *Comp =
6619         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6620       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6621         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6622         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6623         return ReplaceInstUsesWith(ICI, Cst);
6624       }
6625       
6626       if (LHSI->hasOneUse()) {
6627         // Otherwise strength reduce the shift into an and.
6628         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6629         Constant *Mask =
6630           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6631         
6632         Instruction *AndI =
6633           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6634                                     Mask, LHSI->getName()+".mask");
6635         Value *And = InsertNewInstBefore(AndI, ICI);
6636         return new ICmpInst(ICI.getPredicate(), And,
6637                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6638       }
6639     }
6640     
6641     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6642     bool TrueIfSigned = false;
6643     if (LHSI->hasOneUse() &&
6644         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6645       // (X << 31) <s 0  --> (X&1) != 0
6646       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6647                                            (TypeBits-ShAmt->getZExtValue()-1));
6648       Instruction *AndI =
6649         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6650                                   Mask, LHSI->getName()+".mask");
6651       Value *And = InsertNewInstBefore(AndI, ICI);
6652       
6653       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6654                           And, Constant::getNullValue(And->getType()));
6655     }
6656     break;
6657   }
6658     
6659   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6660   case Instruction::AShr: {
6661     // Only handle equality comparisons of shift-by-constant.
6662     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6663     if (!ShAmt || !ICI.isEquality()) break;
6664
6665     // Check that the shift amount is in range.  If not, don't perform
6666     // undefined shifts.  When the shift is visited it will be
6667     // simplified.
6668     uint32_t TypeBits = RHSV.getBitWidth();
6669     if (ShAmt->uge(TypeBits))
6670       break;
6671     
6672     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6673       
6674     // If we are comparing against bits always shifted out, the
6675     // comparison cannot succeed.
6676     APInt Comp = RHSV << ShAmtVal;
6677     if (LHSI->getOpcode() == Instruction::LShr)
6678       Comp = Comp.lshr(ShAmtVal);
6679     else
6680       Comp = Comp.ashr(ShAmtVal);
6681     
6682     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6683       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6684       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6685       return ReplaceInstUsesWith(ICI, Cst);
6686     }
6687     
6688     // Otherwise, check to see if the bits shifted out are known to be zero.
6689     // If so, we can compare against the unshifted value:
6690     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6691     if (LHSI->hasOneUse() &&
6692         MaskedValueIsZero(LHSI->getOperand(0), 
6693                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6694       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6695                           ConstantExpr::getShl(RHS, ShAmt));
6696     }
6697       
6698     if (LHSI->hasOneUse()) {
6699       // Otherwise strength reduce the shift into an and.
6700       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6701       Constant *Mask = ConstantInt::get(Val);
6702       
6703       Instruction *AndI =
6704         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6705                                   Mask, LHSI->getName()+".mask");
6706       Value *And = InsertNewInstBefore(AndI, ICI);
6707       return new ICmpInst(ICI.getPredicate(), And,
6708                           ConstantExpr::getShl(RHS, ShAmt));
6709     }
6710     break;
6711   }
6712     
6713   case Instruction::SDiv:
6714   case Instruction::UDiv:
6715     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6716     // Fold this div into the comparison, producing a range check. 
6717     // Determine, based on the divide type, what the range is being 
6718     // checked.  If there is an overflow on the low or high side, remember 
6719     // it, otherwise compute the range [low, hi) bounding the new value.
6720     // See: InsertRangeTest above for the kinds of replacements possible.
6721     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6722       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6723                                           DivRHS))
6724         return R;
6725     break;
6726
6727   case Instruction::Add:
6728     // Fold: icmp pred (add, X, C1), C2
6729
6730     if (!ICI.isEquality()) {
6731       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6732       if (!LHSC) break;
6733       const APInt &LHSV = LHSC->getValue();
6734
6735       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6736                             .subtract(LHSV);
6737
6738       if (ICI.isSignedPredicate()) {
6739         if (CR.getLower().isSignBit()) {
6740           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6741                               ConstantInt::get(CR.getUpper()));
6742         } else if (CR.getUpper().isSignBit()) {
6743           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6744                               ConstantInt::get(CR.getLower()));
6745         }
6746       } else {
6747         if (CR.getLower().isMinValue()) {
6748           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6749                               ConstantInt::get(CR.getUpper()));
6750         } else if (CR.getUpper().isMinValue()) {
6751           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6752                               ConstantInt::get(CR.getLower()));
6753         }
6754       }
6755     }
6756     break;
6757   }
6758   
6759   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6760   if (ICI.isEquality()) {
6761     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6762     
6763     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6764     // the second operand is a constant, simplify a bit.
6765     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6766       switch (BO->getOpcode()) {
6767       case Instruction::SRem:
6768         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6769         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6770           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6771           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6772             Instruction *NewRem =
6773               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6774                                          BO->getName());
6775             InsertNewInstBefore(NewRem, ICI);
6776             return new ICmpInst(ICI.getPredicate(), NewRem, 
6777                                 Constant::getNullValue(BO->getType()));
6778           }
6779         }
6780         break;
6781       case Instruction::Add:
6782         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6783         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6784           if (BO->hasOneUse())
6785             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6786                                 Subtract(RHS, BOp1C));
6787         } else if (RHSV == 0) {
6788           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6789           // efficiently invertible, or if the add has just this one use.
6790           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6791           
6792           if (Value *NegVal = dyn_castNegVal(BOp1))
6793             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6794           else if (Value *NegVal = dyn_castNegVal(BOp0))
6795             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6796           else if (BO->hasOneUse()) {
6797             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6798             InsertNewInstBefore(Neg, ICI);
6799             Neg->takeName(BO);
6800             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6801           }
6802         }
6803         break;
6804       case Instruction::Xor:
6805         // For the xor case, we can xor two constants together, eliminating
6806         // the explicit xor.
6807         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6808           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6809                               ConstantExpr::getXor(RHS, BOC));
6810         
6811         // FALLTHROUGH
6812       case Instruction::Sub:
6813         // Replace (([sub|xor] A, B) != 0) with (A != B)
6814         if (RHSV == 0)
6815           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6816                               BO->getOperand(1));
6817         break;
6818         
6819       case Instruction::Or:
6820         // If bits are being or'd in that are not present in the constant we
6821         // are comparing against, then the comparison could never succeed!
6822         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6823           Constant *NotCI = ConstantExpr::getNot(RHS);
6824           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6825             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6826                                                              isICMP_NE));
6827         }
6828         break;
6829         
6830       case Instruction::And:
6831         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6832           // If bits are being compared against that are and'd out, then the
6833           // comparison can never succeed!
6834           if ((RHSV & ~BOC->getValue()) != 0)
6835             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6836                                                              isICMP_NE));
6837           
6838           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6839           if (RHS == BOC && RHSV.isPowerOf2())
6840             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6841                                 ICmpInst::ICMP_NE, LHSI,
6842                                 Constant::getNullValue(RHS->getType()));
6843           
6844           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6845           if (BOC->getValue().isSignBit()) {
6846             Value *X = BO->getOperand(0);
6847             Constant *Zero = Constant::getNullValue(X->getType());
6848             ICmpInst::Predicate pred = isICMP_NE ? 
6849               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6850             return new ICmpInst(pred, X, Zero);
6851           }
6852           
6853           // ((X & ~7) == 0) --> X < 8
6854           if (RHSV == 0 && isHighOnes(BOC)) {
6855             Value *X = BO->getOperand(0);
6856             Constant *NegX = ConstantExpr::getNeg(BOC);
6857             ICmpInst::Predicate pred = isICMP_NE ? 
6858               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6859             return new ICmpInst(pred, X, NegX);
6860           }
6861         }
6862       default: break;
6863       }
6864     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6865       // Handle icmp {eq|ne} <intrinsic>, intcst.
6866       if (II->getIntrinsicID() == Intrinsic::bswap) {
6867         AddToWorkList(II);
6868         ICI.setOperand(0, II->getOperand(1));
6869         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6870         return &ICI;
6871       }
6872     }
6873   }
6874   return 0;
6875 }
6876
6877 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6878 /// We only handle extending casts so far.
6879 ///
6880 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6881   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6882   Value *LHSCIOp        = LHSCI->getOperand(0);
6883   const Type *SrcTy     = LHSCIOp->getType();
6884   const Type *DestTy    = LHSCI->getType();
6885   Value *RHSCIOp;
6886
6887   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6888   // integer type is the same size as the pointer type.
6889   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6890       getTargetData().getPointerSizeInBits() == 
6891          cast<IntegerType>(DestTy)->getBitWidth()) {
6892     Value *RHSOp = 0;
6893     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6894       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6895     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6896       RHSOp = RHSC->getOperand(0);
6897       // If the pointer types don't match, insert a bitcast.
6898       if (LHSCIOp->getType() != RHSOp->getType())
6899         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6900     }
6901
6902     if (RHSOp)
6903       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6904   }
6905   
6906   // The code below only handles extension cast instructions, so far.
6907   // Enforce this.
6908   if (LHSCI->getOpcode() != Instruction::ZExt &&
6909       LHSCI->getOpcode() != Instruction::SExt)
6910     return 0;
6911
6912   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6913   bool isSignedCmp = ICI.isSignedPredicate();
6914
6915   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6916     // Not an extension from the same type?
6917     RHSCIOp = CI->getOperand(0);
6918     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6919       return 0;
6920     
6921     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6922     // and the other is a zext), then we can't handle this.
6923     if (CI->getOpcode() != LHSCI->getOpcode())
6924       return 0;
6925
6926     // Deal with equality cases early.
6927     if (ICI.isEquality())
6928       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6929
6930     // A signed comparison of sign extended values simplifies into a
6931     // signed comparison.
6932     if (isSignedCmp && isSignedExt)
6933       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6934
6935     // The other three cases all fold into an unsigned comparison.
6936     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6937   }
6938
6939   // If we aren't dealing with a constant on the RHS, exit early
6940   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6941   if (!CI)
6942     return 0;
6943
6944   // Compute the constant that would happen if we truncated to SrcTy then
6945   // reextended to DestTy.
6946   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6947   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6948
6949   // If the re-extended constant didn't change...
6950   if (Res2 == CI) {
6951     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6952     // For example, we might have:
6953     //    %A = sext short %X to uint
6954     //    %B = icmp ugt uint %A, 1330
6955     // It is incorrect to transform this into 
6956     //    %B = icmp ugt short %X, 1330 
6957     // because %A may have negative value. 
6958     //
6959     // However, we allow this when the compare is EQ/NE, because they are
6960     // signless.
6961     if (isSignedExt == isSignedCmp || ICI.isEquality())
6962       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6963     return 0;
6964   }
6965
6966   // The re-extended constant changed so the constant cannot be represented 
6967   // in the shorter type. Consequently, we cannot emit a simple comparison.
6968
6969   // First, handle some easy cases. We know the result cannot be equal at this
6970   // point so handle the ICI.isEquality() cases
6971   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6972     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6973   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6974     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6975
6976   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6977   // should have been folded away previously and not enter in here.
6978   Value *Result;
6979   if (isSignedCmp) {
6980     // We're performing a signed comparison.
6981     if (cast<ConstantInt>(CI)->getValue().isNegative())
6982       Result = ConstantInt::getFalse();          // X < (small) --> false
6983     else
6984       Result = ConstantInt::getTrue();           // X < (large) --> true
6985   } else {
6986     // We're performing an unsigned comparison.
6987     if (isSignedExt) {
6988       // We're performing an unsigned comp with a sign extended value.
6989       // This is true if the input is >= 0. [aka >s -1]
6990       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6991       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6992                                    NegOne, ICI.getName()), ICI);
6993     } else {
6994       // Unsigned extend & unsigned compare -> always true.
6995       Result = ConstantInt::getTrue();
6996     }
6997   }
6998
6999   // Finally, return the value computed.
7000   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7001       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7002     return ReplaceInstUsesWith(ICI, Result);
7003
7004   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7005           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7006          "ICmp should be folded!");
7007   if (Constant *CI = dyn_cast<Constant>(Result))
7008     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7009   return BinaryOperator::CreateNot(Result);
7010 }
7011
7012 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7013   return commonShiftTransforms(I);
7014 }
7015
7016 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7017   return commonShiftTransforms(I);
7018 }
7019
7020 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7021   if (Instruction *R = commonShiftTransforms(I))
7022     return R;
7023   
7024   Value *Op0 = I.getOperand(0);
7025   
7026   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7027   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7028     if (CSI->isAllOnesValue())
7029       return ReplaceInstUsesWith(I, CSI);
7030   
7031   // See if we can turn a signed shr into an unsigned shr.
7032   if (!isa<VectorType>(I.getType())) {
7033     if (MaskedValueIsZero(Op0,
7034                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
7035       return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7036
7037     // Arithmetic shifting an all-sign-bit value is a no-op.
7038     unsigned NumSignBits = ComputeNumSignBits(Op0);
7039     if (NumSignBits == Op0->getType()->getPrimitiveSizeInBits())
7040       return ReplaceInstUsesWith(I, Op0);
7041   }
7042
7043   return 0;
7044 }
7045
7046 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7047   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7048   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7049
7050   // shl X, 0 == X and shr X, 0 == X
7051   // shl 0, X == 0 and shr 0, X == 0
7052   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7053       Op0 == Constant::getNullValue(Op0->getType()))
7054     return ReplaceInstUsesWith(I, Op0);
7055   
7056   if (isa<UndefValue>(Op0)) {            
7057     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7058       return ReplaceInstUsesWith(I, Op0);
7059     else                                    // undef << X -> 0, undef >>u X -> 0
7060       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7061   }
7062   if (isa<UndefValue>(Op1)) {
7063     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7064       return ReplaceInstUsesWith(I, Op0);          
7065     else                                     // X << undef, X >>u undef -> 0
7066       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7067   }
7068
7069   // Try to fold constant and into select arguments.
7070   if (isa<Constant>(Op0))
7071     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7072       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7073         return R;
7074
7075   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7076     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7077       return Res;
7078   return 0;
7079 }
7080
7081 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7082                                                BinaryOperator &I) {
7083   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7084
7085   // See if we can simplify any instructions used by the instruction whose sole 
7086   // purpose is to compute bits we don't care about.
7087   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
7088   if (SimplifyDemandedInstructionBits(I))
7089     return &I;
7090   
7091   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7092   // of a signed value.
7093   //
7094   if (Op1->uge(TypeBits)) {
7095     if (I.getOpcode() != Instruction::AShr)
7096       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7097     else {
7098       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7099       return &I;
7100     }
7101   }
7102   
7103   // ((X*C1) << C2) == (X * (C1 << C2))
7104   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7105     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7106       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7107         return BinaryOperator::CreateMul(BO->getOperand(0),
7108                                          ConstantExpr::getShl(BOOp, Op1));
7109   
7110   // Try to fold constant and into select arguments.
7111   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7112     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7113       return R;
7114   if (isa<PHINode>(Op0))
7115     if (Instruction *NV = FoldOpIntoPhi(I))
7116       return NV;
7117   
7118   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7119   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7120     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7121     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7122     // place.  Don't try to do this transformation in this case.  Also, we
7123     // require that the input operand is a shift-by-constant so that we have
7124     // confidence that the shifts will get folded together.  We could do this
7125     // xform in more cases, but it is unlikely to be profitable.
7126     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7127         isa<ConstantInt>(TrOp->getOperand(1))) {
7128       // Okay, we'll do this xform.  Make the shift of shift.
7129       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7130       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7131                                                 I.getName());
7132       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7133
7134       // For logical shifts, the truncation has the effect of making the high
7135       // part of the register be zeros.  Emulate this by inserting an AND to
7136       // clear the top bits as needed.  This 'and' will usually be zapped by
7137       // other xforms later if dead.
7138       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7139       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7140       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7141       
7142       // The mask we constructed says what the trunc would do if occurring
7143       // between the shifts.  We want to know the effect *after* the second
7144       // shift.  We know that it is a logical shift by a constant, so adjust the
7145       // mask as appropriate.
7146       if (I.getOpcode() == Instruction::Shl)
7147         MaskV <<= Op1->getZExtValue();
7148       else {
7149         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7150         MaskV = MaskV.lshr(Op1->getZExtValue());
7151       }
7152
7153       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7154                                                    TI->getName());
7155       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7156
7157       // Return the value truncated to the interesting size.
7158       return new TruncInst(And, I.getType());
7159     }
7160   }
7161   
7162   if (Op0->hasOneUse()) {
7163     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7164       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7165       Value *V1, *V2;
7166       ConstantInt *CC;
7167       switch (Op0BO->getOpcode()) {
7168         default: break;
7169         case Instruction::Add:
7170         case Instruction::And:
7171         case Instruction::Or:
7172         case Instruction::Xor: {
7173           // These operators commute.
7174           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7175           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7176               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7177             Instruction *YS = BinaryOperator::CreateShl(
7178                                             Op0BO->getOperand(0), Op1,
7179                                             Op0BO->getName());
7180             InsertNewInstBefore(YS, I); // (Y << C)
7181             Instruction *X = 
7182               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7183                                      Op0BO->getOperand(1)->getName());
7184             InsertNewInstBefore(X, I);  // (X + (Y << C))
7185             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7186             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7187                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7188           }
7189           
7190           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7191           Value *Op0BOOp1 = Op0BO->getOperand(1);
7192           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7193               match(Op0BOOp1, 
7194                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7195                           m_ConstantInt(CC))) &&
7196               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7197             Instruction *YS = BinaryOperator::CreateShl(
7198                                                      Op0BO->getOperand(0), Op1,
7199                                                      Op0BO->getName());
7200             InsertNewInstBefore(YS, I); // (Y << C)
7201             Instruction *XM =
7202               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7203                                         V1->getName()+".mask");
7204             InsertNewInstBefore(XM, I); // X & (CC << C)
7205             
7206             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7207           }
7208         }
7209           
7210         // FALL THROUGH.
7211         case Instruction::Sub: {
7212           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7213           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7214               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7215             Instruction *YS = BinaryOperator::CreateShl(
7216                                                      Op0BO->getOperand(1), Op1,
7217                                                      Op0BO->getName());
7218             InsertNewInstBefore(YS, I); // (Y << C)
7219             Instruction *X =
7220               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7221                                      Op0BO->getOperand(0)->getName());
7222             InsertNewInstBefore(X, I);  // (X + (Y << C))
7223             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7224             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7225                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7226           }
7227           
7228           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7229           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7230               match(Op0BO->getOperand(0),
7231                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7232                           m_ConstantInt(CC))) && V2 == Op1 &&
7233               cast<BinaryOperator>(Op0BO->getOperand(0))
7234                   ->getOperand(0)->hasOneUse()) {
7235             Instruction *YS = BinaryOperator::CreateShl(
7236                                                      Op0BO->getOperand(1), Op1,
7237                                                      Op0BO->getName());
7238             InsertNewInstBefore(YS, I); // (Y << C)
7239             Instruction *XM =
7240               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7241                                         V1->getName()+".mask");
7242             InsertNewInstBefore(XM, I); // X & (CC << C)
7243             
7244             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7245           }
7246           
7247           break;
7248         }
7249       }
7250       
7251       
7252       // If the operand is an bitwise operator with a constant RHS, and the
7253       // shift is the only use, we can pull it out of the shift.
7254       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7255         bool isValid = true;     // Valid only for And, Or, Xor
7256         bool highBitSet = false; // Transform if high bit of constant set?
7257         
7258         switch (Op0BO->getOpcode()) {
7259           default: isValid = false; break;   // Do not perform transform!
7260           case Instruction::Add:
7261             isValid = isLeftShift;
7262             break;
7263           case Instruction::Or:
7264           case Instruction::Xor:
7265             highBitSet = false;
7266             break;
7267           case Instruction::And:
7268             highBitSet = true;
7269             break;
7270         }
7271         
7272         // If this is a signed shift right, and the high bit is modified
7273         // by the logical operation, do not perform the transformation.
7274         // The highBitSet boolean indicates the value of the high bit of
7275         // the constant which would cause it to be modified for this
7276         // operation.
7277         //
7278         if (isValid && I.getOpcode() == Instruction::AShr)
7279           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7280         
7281         if (isValid) {
7282           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7283           
7284           Instruction *NewShift =
7285             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7286           InsertNewInstBefore(NewShift, I);
7287           NewShift->takeName(Op0BO);
7288           
7289           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7290                                         NewRHS);
7291         }
7292       }
7293     }
7294   }
7295   
7296   // Find out if this is a shift of a shift by a constant.
7297   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7298   if (ShiftOp && !ShiftOp->isShift())
7299     ShiftOp = 0;
7300   
7301   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7302     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7303     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7304     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7305     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7306     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7307     Value *X = ShiftOp->getOperand(0);
7308     
7309     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7310     
7311     const IntegerType *Ty = cast<IntegerType>(I.getType());
7312     
7313     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7314     if (I.getOpcode() == ShiftOp->getOpcode()) {
7315       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7316       // saturates.
7317       if (AmtSum >= TypeBits) {
7318         if (I.getOpcode() != Instruction::AShr)
7319           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7320         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7321       }
7322       
7323       return BinaryOperator::Create(I.getOpcode(), X,
7324                                     ConstantInt::get(Ty, AmtSum));
7325     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7326                I.getOpcode() == Instruction::AShr) {
7327       if (AmtSum >= TypeBits)
7328         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7329       
7330       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7331       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7332     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7333                I.getOpcode() == Instruction::LShr) {
7334       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7335       if (AmtSum >= TypeBits)
7336         AmtSum = TypeBits-1;
7337       
7338       Instruction *Shift =
7339         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7340       InsertNewInstBefore(Shift, I);
7341
7342       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7343       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7344     }
7345     
7346     // Okay, if we get here, one shift must be left, and the other shift must be
7347     // right.  See if the amounts are equal.
7348     if (ShiftAmt1 == ShiftAmt2) {
7349       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7350       if (I.getOpcode() == Instruction::Shl) {
7351         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7352         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7353       }
7354       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7355       if (I.getOpcode() == Instruction::LShr) {
7356         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7357         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7358       }
7359       // We can simplify ((X << C) >>s C) into a trunc + sext.
7360       // NOTE: we could do this for any C, but that would make 'unusual' integer
7361       // types.  For now, just stick to ones well-supported by the code
7362       // generators.
7363       const Type *SExtType = 0;
7364       switch (Ty->getBitWidth() - ShiftAmt1) {
7365       case 1  :
7366       case 8  :
7367       case 16 :
7368       case 32 :
7369       case 64 :
7370       case 128:
7371         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7372         break;
7373       default: break;
7374       }
7375       if (SExtType) {
7376         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7377         InsertNewInstBefore(NewTrunc, I);
7378         return new SExtInst(NewTrunc, Ty);
7379       }
7380       // Otherwise, we can't handle it yet.
7381     } else if (ShiftAmt1 < ShiftAmt2) {
7382       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7383       
7384       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7385       if (I.getOpcode() == Instruction::Shl) {
7386         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7387                ShiftOp->getOpcode() == Instruction::AShr);
7388         Instruction *Shift =
7389           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7390         InsertNewInstBefore(Shift, I);
7391         
7392         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7393         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7394       }
7395       
7396       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7397       if (I.getOpcode() == Instruction::LShr) {
7398         assert(ShiftOp->getOpcode() == Instruction::Shl);
7399         Instruction *Shift =
7400           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7401         InsertNewInstBefore(Shift, I);
7402         
7403         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7404         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7405       }
7406       
7407       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7408     } else {
7409       assert(ShiftAmt2 < ShiftAmt1);
7410       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7411
7412       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7413       if (I.getOpcode() == Instruction::Shl) {
7414         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7415                ShiftOp->getOpcode() == Instruction::AShr);
7416         Instruction *Shift =
7417           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7418                                  ConstantInt::get(Ty, ShiftDiff));
7419         InsertNewInstBefore(Shift, I);
7420         
7421         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7422         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7423       }
7424       
7425       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7426       if (I.getOpcode() == Instruction::LShr) {
7427         assert(ShiftOp->getOpcode() == Instruction::Shl);
7428         Instruction *Shift =
7429           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7430         InsertNewInstBefore(Shift, I);
7431         
7432         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7433         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7434       }
7435       
7436       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7437     }
7438   }
7439   return 0;
7440 }
7441
7442
7443 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7444 /// expression.  If so, decompose it, returning some value X, such that Val is
7445 /// X*Scale+Offset.
7446 ///
7447 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7448                                         int &Offset) {
7449   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7450   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7451     Offset = CI->getZExtValue();
7452     Scale  = 0;
7453     return ConstantInt::get(Type::Int32Ty, 0);
7454   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7455     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7456       if (I->getOpcode() == Instruction::Shl) {
7457         // This is a value scaled by '1 << the shift amt'.
7458         Scale = 1U << RHS->getZExtValue();
7459         Offset = 0;
7460         return I->getOperand(0);
7461       } else if (I->getOpcode() == Instruction::Mul) {
7462         // This value is scaled by 'RHS'.
7463         Scale = RHS->getZExtValue();
7464         Offset = 0;
7465         return I->getOperand(0);
7466       } else if (I->getOpcode() == Instruction::Add) {
7467         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7468         // where C1 is divisible by C2.
7469         unsigned SubScale;
7470         Value *SubVal = 
7471           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7472         Offset += RHS->getZExtValue();
7473         Scale = SubScale;
7474         return SubVal;
7475       }
7476     }
7477   }
7478
7479   // Otherwise, we can't look past this.
7480   Scale = 1;
7481   Offset = 0;
7482   return Val;
7483 }
7484
7485
7486 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7487 /// try to eliminate the cast by moving the type information into the alloc.
7488 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7489                                                    AllocationInst &AI) {
7490   const PointerType *PTy = cast<PointerType>(CI.getType());
7491   
7492   // Remove any uses of AI that are dead.
7493   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7494   
7495   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7496     Instruction *User = cast<Instruction>(*UI++);
7497     if (isInstructionTriviallyDead(User)) {
7498       while (UI != E && *UI == User)
7499         ++UI; // If this instruction uses AI more than once, don't break UI.
7500       
7501       ++NumDeadInst;
7502       DOUT << "IC: DCE: " << *User;
7503       EraseInstFromFunction(*User);
7504     }
7505   }
7506   
7507   // Get the type really allocated and the type casted to.
7508   const Type *AllocElTy = AI.getAllocatedType();
7509   const Type *CastElTy = PTy->getElementType();
7510   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7511
7512   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7513   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7514   if (CastElTyAlign < AllocElTyAlign) return 0;
7515
7516   // If the allocation has multiple uses, only promote it if we are strictly
7517   // increasing the alignment of the resultant allocation.  If we keep it the
7518   // same, we open the door to infinite loops of various kinds.  (A reference
7519   // from a dbg.declare doesn't count as a use for this purpose.)
7520   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7521       CastElTyAlign == AllocElTyAlign) return 0;
7522
7523   uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7524   uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
7525   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7526
7527   // See if we can satisfy the modulus by pulling a scale out of the array
7528   // size argument.
7529   unsigned ArraySizeScale;
7530   int ArrayOffset;
7531   Value *NumElements = // See if the array size is a decomposable linear expr.
7532     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7533  
7534   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7535   // do the xform.
7536   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7537       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7538
7539   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7540   Value *Amt = 0;
7541   if (Scale == 1) {
7542     Amt = NumElements;
7543   } else {
7544     // If the allocation size is constant, form a constant mul expression
7545     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7546     if (isa<ConstantInt>(NumElements))
7547       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7548     // otherwise multiply the amount and the number of elements
7549     else {
7550       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7551       Amt = InsertNewInstBefore(Tmp, AI);
7552     }
7553   }
7554   
7555   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7556     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7557     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7558     Amt = InsertNewInstBefore(Tmp, AI);
7559   }
7560   
7561   AllocationInst *New;
7562   if (isa<MallocInst>(AI))
7563     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7564   else
7565     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7566   InsertNewInstBefore(New, AI);
7567   New->takeName(&AI);
7568   
7569   // If the allocation has one real use plus a dbg.declare, just remove the
7570   // declare.
7571   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7572     EraseInstFromFunction(*DI);
7573   }
7574   // If the allocation has multiple real uses, insert a cast and change all
7575   // things that used it to use the new cast.  This will also hack on CI, but it
7576   // will die soon.
7577   else if (!AI.hasOneUse()) {
7578     AddUsesToWorkList(AI);
7579     // New is the allocation instruction, pointer typed. AI is the original
7580     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7581     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7582     InsertNewInstBefore(NewCast, AI);
7583     AI.replaceAllUsesWith(NewCast);
7584   }
7585   return ReplaceInstUsesWith(CI, New);
7586 }
7587
7588 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7589 /// and return it as type Ty without inserting any new casts and without
7590 /// changing the computed value.  This is used by code that tries to decide
7591 /// whether promoting or shrinking integer operations to wider or smaller types
7592 /// will allow us to eliminate a truncate or extend.
7593 ///
7594 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7595 /// extension operation if Ty is larger.
7596 ///
7597 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7598 /// should return true if trunc(V) can be computed by computing V in the smaller
7599 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7600 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7601 /// efficiently truncated.
7602 ///
7603 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7604 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7605 /// the final result.
7606 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7607                                               unsigned CastOpc,
7608                                               int &NumCastsRemoved){
7609   // We can always evaluate constants in another type.
7610   if (isa<ConstantInt>(V))
7611     return true;
7612   
7613   Instruction *I = dyn_cast<Instruction>(V);
7614   if (!I) return false;
7615   
7616   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7617   
7618   // If this is an extension or truncate, we can often eliminate it.
7619   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7620     // If this is a cast from the destination type, we can trivially eliminate
7621     // it, and this will remove a cast overall.
7622     if (I->getOperand(0)->getType() == Ty) {
7623       // If the first operand is itself a cast, and is eliminable, do not count
7624       // this as an eliminable cast.  We would prefer to eliminate those two
7625       // casts first.
7626       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7627         ++NumCastsRemoved;
7628       return true;
7629     }
7630   }
7631
7632   // We can't extend or shrink something that has multiple uses: doing so would
7633   // require duplicating the instruction in general, which isn't profitable.
7634   if (!I->hasOneUse()) return false;
7635
7636   unsigned Opc = I->getOpcode();
7637   switch (Opc) {
7638   case Instruction::Add:
7639   case Instruction::Sub:
7640   case Instruction::Mul:
7641   case Instruction::And:
7642   case Instruction::Or:
7643   case Instruction::Xor:
7644     // These operators can all arbitrarily be extended or truncated.
7645     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7646                                       NumCastsRemoved) &&
7647            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7648                                       NumCastsRemoved);
7649
7650   case Instruction::Shl:
7651     // If we are truncating the result of this SHL, and if it's a shift of a
7652     // constant amount, we can always perform a SHL in a smaller type.
7653     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7654       uint32_t BitWidth = Ty->getBitWidth();
7655       if (BitWidth < OrigTy->getBitWidth() && 
7656           CI->getLimitedValue(BitWidth) < BitWidth)
7657         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7658                                           NumCastsRemoved);
7659     }
7660     break;
7661   case Instruction::LShr:
7662     // If this is a truncate of a logical shr, we can truncate it to a smaller
7663     // lshr iff we know that the bits we would otherwise be shifting in are
7664     // already zeros.
7665     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7666       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7667       uint32_t BitWidth = Ty->getBitWidth();
7668       if (BitWidth < OrigBitWidth &&
7669           MaskedValueIsZero(I->getOperand(0),
7670             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7671           CI->getLimitedValue(BitWidth) < BitWidth) {
7672         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7673                                           NumCastsRemoved);
7674       }
7675     }
7676     break;
7677   case Instruction::ZExt:
7678   case Instruction::SExt:
7679   case Instruction::Trunc:
7680     // If this is the same kind of case as our original (e.g. zext+zext), we
7681     // can safely replace it.  Note that replacing it does not reduce the number
7682     // of casts in the input.
7683     if (Opc == CastOpc)
7684       return true;
7685
7686     // sext (zext ty1), ty2 -> zext ty2
7687     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7688       return true;
7689     break;
7690   case Instruction::Select: {
7691     SelectInst *SI = cast<SelectInst>(I);
7692     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7693                                       NumCastsRemoved) &&
7694            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7695                                       NumCastsRemoved);
7696   }
7697   case Instruction::PHI: {
7698     // We can change a phi if we can change all operands.
7699     PHINode *PN = cast<PHINode>(I);
7700     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7701       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7702                                       NumCastsRemoved))
7703         return false;
7704     return true;
7705   }
7706   default:
7707     // TODO: Can handle more cases here.
7708     break;
7709   }
7710   
7711   return false;
7712 }
7713
7714 /// EvaluateInDifferentType - Given an expression that 
7715 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7716 /// evaluate the expression.
7717 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7718                                              bool isSigned) {
7719   if (Constant *C = dyn_cast<Constant>(V))
7720     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7721
7722   // Otherwise, it must be an instruction.
7723   Instruction *I = cast<Instruction>(V);
7724   Instruction *Res = 0;
7725   unsigned Opc = I->getOpcode();
7726   switch (Opc) {
7727   case Instruction::Add:
7728   case Instruction::Sub:
7729   case Instruction::Mul:
7730   case Instruction::And:
7731   case Instruction::Or:
7732   case Instruction::Xor:
7733   case Instruction::AShr:
7734   case Instruction::LShr:
7735   case Instruction::Shl: {
7736     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7737     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7738     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7739     break;
7740   }    
7741   case Instruction::Trunc:
7742   case Instruction::ZExt:
7743   case Instruction::SExt:
7744     // If the source type of the cast is the type we're trying for then we can
7745     // just return the source.  There's no need to insert it because it is not
7746     // new.
7747     if (I->getOperand(0)->getType() == Ty)
7748       return I->getOperand(0);
7749     
7750     // Otherwise, must be the same type of cast, so just reinsert a new one.
7751     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7752                            Ty);
7753     break;
7754   case Instruction::Select: {
7755     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7756     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7757     Res = SelectInst::Create(I->getOperand(0), True, False);
7758     break;
7759   }
7760   case Instruction::PHI: {
7761     PHINode *OPN = cast<PHINode>(I);
7762     PHINode *NPN = PHINode::Create(Ty);
7763     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7764       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7765       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7766     }
7767     Res = NPN;
7768     break;
7769   }
7770   default: 
7771     // TODO: Can handle more cases here.
7772     assert(0 && "Unreachable!");
7773     break;
7774   }
7775   
7776   Res->takeName(I);
7777   return InsertNewInstBefore(Res, *I);
7778 }
7779
7780 /// @brief Implement the transforms common to all CastInst visitors.
7781 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7782   Value *Src = CI.getOperand(0);
7783
7784   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7785   // eliminate it now.
7786   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7787     if (Instruction::CastOps opc = 
7788         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7789       // The first cast (CSrc) is eliminable so we need to fix up or replace
7790       // the second cast (CI). CSrc will then have a good chance of being dead.
7791       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7792     }
7793   }
7794
7795   // If we are casting a select then fold the cast into the select
7796   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7797     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7798       return NV;
7799
7800   // If we are casting a PHI then fold the cast into the PHI
7801   if (isa<PHINode>(Src))
7802     if (Instruction *NV = FoldOpIntoPhi(CI))
7803       return NV;
7804   
7805   return 0;
7806 }
7807
7808 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7809 /// or not there is a sequence of GEP indices into the type that will land us at
7810 /// the specified offset.  If so, fill them into NewIndices and return the
7811 /// resultant element type, otherwise return null.
7812 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
7813                                        SmallVectorImpl<Value*> &NewIndices,
7814                                        const TargetData *TD) {
7815   if (!Ty->isSized()) return 0;
7816   
7817   // Start with the index over the outer type.  Note that the type size
7818   // might be zero (even if the offset isn't zero) if the indexed type
7819   // is something like [0 x {int, int}]
7820   const Type *IntPtrTy = TD->getIntPtrType();
7821   int64_t FirstIdx = 0;
7822   if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
7823     FirstIdx = Offset/TySize;
7824     Offset -= FirstIdx*TySize;
7825     
7826     // Handle hosts where % returns negative instead of values [0..TySize).
7827     if (Offset < 0) {
7828       --FirstIdx;
7829       Offset += TySize;
7830       assert(Offset >= 0);
7831     }
7832     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7833   }
7834   
7835   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7836     
7837   // Index into the types.  If we fail, set OrigBase to null.
7838   while (Offset) {
7839     // Indexing into tail padding between struct/array elements.
7840     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
7841       return 0;
7842     
7843     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7844       const StructLayout *SL = TD->getStructLayout(STy);
7845       assert(Offset < (int64_t)SL->getSizeInBytes() &&
7846              "Offset must stay within the indexed type");
7847       
7848       unsigned Elt = SL->getElementContainingOffset(Offset);
7849       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7850       
7851       Offset -= SL->getElementOffset(Elt);
7852       Ty = STy->getElementType(Elt);
7853     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
7854       uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
7855       assert(EltSize && "Cannot index into a zero-sized array");
7856       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7857       Offset %= EltSize;
7858       Ty = AT->getElementType();
7859     } else {
7860       // Otherwise, we can't index into the middle of this atomic type, bail.
7861       return 0;
7862     }
7863   }
7864   
7865   return Ty;
7866 }
7867
7868 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7869 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7870   Value *Src = CI.getOperand(0);
7871   
7872   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7873     // If casting the result of a getelementptr instruction with no offset, turn
7874     // this into a cast of the original pointer!
7875     if (GEP->hasAllZeroIndices()) {
7876       // Changing the cast operand is usually not a good idea but it is safe
7877       // here because the pointer operand is being replaced with another 
7878       // pointer operand so the opcode doesn't need to change.
7879       AddToWorkList(GEP);
7880       CI.setOperand(0, GEP->getOperand(0));
7881       return &CI;
7882     }
7883     
7884     // If the GEP has a single use, and the base pointer is a bitcast, and the
7885     // GEP computes a constant offset, see if we can convert these three
7886     // instructions into fewer.  This typically happens with unions and other
7887     // non-type-safe code.
7888     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7889       if (GEP->hasAllConstantIndices()) {
7890         // We are guaranteed to get a constant from EmitGEPOffset.
7891         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7892         int64_t Offset = OffsetV->getSExtValue();
7893         
7894         // Get the base pointer input of the bitcast, and the type it points to.
7895         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7896         const Type *GEPIdxTy =
7897           cast<PointerType>(OrigBase->getType())->getElementType();
7898         SmallVector<Value*, 8> NewIndices;
7899         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7900           // If we were able to index down into an element, create the GEP
7901           // and bitcast the result.  This eliminates one bitcast, potentially
7902           // two.
7903           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7904                                                         NewIndices.begin(),
7905                                                         NewIndices.end(), "");
7906           InsertNewInstBefore(NGEP, CI);
7907           NGEP->takeName(GEP);
7908           
7909           if (isa<BitCastInst>(CI))
7910             return new BitCastInst(NGEP, CI.getType());
7911           assert(isa<PtrToIntInst>(CI));
7912           return new PtrToIntInst(NGEP, CI.getType());
7913         }
7914       }      
7915     }
7916   }
7917     
7918   return commonCastTransforms(CI);
7919 }
7920
7921
7922 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7923 /// integer types. This function implements the common transforms for all those
7924 /// cases.
7925 /// @brief Implement the transforms common to CastInst with integer operands
7926 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7927   if (Instruction *Result = commonCastTransforms(CI))
7928     return Result;
7929
7930   Value *Src = CI.getOperand(0);
7931   const Type *SrcTy = Src->getType();
7932   const Type *DestTy = CI.getType();
7933   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7934   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7935
7936   // See if we can simplify any instructions used by the LHS whose sole 
7937   // purpose is to compute bits we don't care about.
7938   if (SimplifyDemandedInstructionBits(CI))
7939     return &CI;
7940
7941   // If the source isn't an instruction or has more than one use then we
7942   // can't do anything more. 
7943   Instruction *SrcI = dyn_cast<Instruction>(Src);
7944   if (!SrcI || !Src->hasOneUse())
7945     return 0;
7946
7947   // Attempt to propagate the cast into the instruction for int->int casts.
7948   int NumCastsRemoved = 0;
7949   if (!isa<BitCastInst>(CI) &&
7950       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7951                                  CI.getOpcode(), NumCastsRemoved)) {
7952     // If this cast is a truncate, evaluting in a different type always
7953     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7954     // we need to do an AND to maintain the clear top-part of the computation,
7955     // so we require that the input have eliminated at least one cast.  If this
7956     // is a sign extension, we insert two new casts (to do the extension) so we
7957     // require that two casts have been eliminated.
7958     bool DoXForm = false;
7959     bool JustReplace = false;
7960     switch (CI.getOpcode()) {
7961     default:
7962       // All the others use floating point so we shouldn't actually 
7963       // get here because of the check above.
7964       assert(0 && "Unknown cast type");
7965     case Instruction::Trunc:
7966       DoXForm = true;
7967       break;
7968     case Instruction::ZExt: {
7969       DoXForm = NumCastsRemoved >= 1;
7970       if (!DoXForm && 0) {
7971         // If it's unnecessary to issue an AND to clear the high bits, it's
7972         // always profitable to do this xform.
7973         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
7974         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7975         if (MaskedValueIsZero(TryRes, Mask))
7976           return ReplaceInstUsesWith(CI, TryRes);
7977         
7978         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7979           if (TryI->use_empty())
7980             EraseInstFromFunction(*TryI);
7981       }
7982       break;
7983     }
7984     case Instruction::SExt: {
7985       DoXForm = NumCastsRemoved >= 2;
7986       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
7987         // If we do not have to emit the truncate + sext pair, then it's always
7988         // profitable to do this xform.
7989         //
7990         // It's not safe to eliminate the trunc + sext pair if one of the
7991         // eliminated cast is a truncate. e.g.
7992         // t2 = trunc i32 t1 to i16
7993         // t3 = sext i16 t2 to i32
7994         // !=
7995         // i32 t1
7996         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
7997         unsigned NumSignBits = ComputeNumSignBits(TryRes);
7998         if (NumSignBits > (DestBitSize - SrcBitSize))
7999           return ReplaceInstUsesWith(CI, TryRes);
8000         
8001         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8002           if (TryI->use_empty())
8003             EraseInstFromFunction(*TryI);
8004       }
8005       break;
8006     }
8007     }
8008     
8009     if (DoXForm) {
8010       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8011            << " cast: " << CI;
8012       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8013                                            CI.getOpcode() == Instruction::SExt);
8014       if (JustReplace)
8015         // Just replace this cast with the result.
8016         return ReplaceInstUsesWith(CI, Res);
8017
8018       assert(Res->getType() == DestTy);
8019       switch (CI.getOpcode()) {
8020       default: assert(0 && "Unknown cast type!");
8021       case Instruction::Trunc:
8022       case Instruction::BitCast:
8023         // Just replace this cast with the result.
8024         return ReplaceInstUsesWith(CI, Res);
8025       case Instruction::ZExt: {
8026         assert(SrcBitSize < DestBitSize && "Not a zext?");
8027
8028         // If the high bits are already zero, just replace this cast with the
8029         // result.
8030         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8031         if (MaskedValueIsZero(Res, Mask))
8032           return ReplaceInstUsesWith(CI, Res);
8033
8034         // We need to emit an AND to clear the high bits.
8035         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8036                                                             SrcBitSize));
8037         return BinaryOperator::CreateAnd(Res, C);
8038       }
8039       case Instruction::SExt: {
8040         // If the high bits are already filled with sign bit, just replace this
8041         // cast with the result.
8042         unsigned NumSignBits = ComputeNumSignBits(Res);
8043         if (NumSignBits > (DestBitSize - SrcBitSize))
8044           return ReplaceInstUsesWith(CI, Res);
8045
8046         // We need to emit a cast to truncate, then a cast to sext.
8047         return CastInst::Create(Instruction::SExt,
8048             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8049                              CI), DestTy);
8050       }
8051       }
8052     }
8053   }
8054   
8055   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8056   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8057
8058   switch (SrcI->getOpcode()) {
8059   case Instruction::Add:
8060   case Instruction::Mul:
8061   case Instruction::And:
8062   case Instruction::Or:
8063   case Instruction::Xor:
8064     // If we are discarding information, rewrite.
8065     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8066       // Don't insert two casts if they cannot be eliminated.  We allow 
8067       // two casts to be inserted if the sizes are the same.  This could 
8068       // only be converting signedness, which is a noop.
8069       if (DestBitSize == SrcBitSize || 
8070           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8071           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8072         Instruction::CastOps opcode = CI.getOpcode();
8073         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8074         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8075         return BinaryOperator::Create(
8076             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8077       }
8078     }
8079
8080     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8081     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8082         SrcI->getOpcode() == Instruction::Xor &&
8083         Op1 == ConstantInt::getTrue() &&
8084         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8085       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8086       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
8087     }
8088     break;
8089   case Instruction::SDiv:
8090   case Instruction::UDiv:
8091   case Instruction::SRem:
8092   case Instruction::URem:
8093     // If we are just changing the sign, rewrite.
8094     if (DestBitSize == SrcBitSize) {
8095       // Don't insert two casts if they cannot be eliminated.  We allow 
8096       // two casts to be inserted if the sizes are the same.  This could 
8097       // only be converting signedness, which is a noop.
8098       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
8099           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8100         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
8101                                        Op0, DestTy, *SrcI);
8102         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
8103                                        Op1, DestTy, *SrcI);
8104         return BinaryOperator::Create(
8105           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8106       }
8107     }
8108     break;
8109
8110   case Instruction::Shl:
8111     // Allow changing the sign of the source operand.  Do not allow 
8112     // changing the size of the shift, UNLESS the shift amount is a 
8113     // constant.  We must not change variable sized shifts to a smaller 
8114     // size, because it is undefined to shift more bits out than exist 
8115     // in the value.
8116     if (DestBitSize == SrcBitSize ||
8117         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8118       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8119           Instruction::BitCast : Instruction::Trunc);
8120       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8121       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8122       return BinaryOperator::CreateShl(Op0c, Op1c);
8123     }
8124     break;
8125   case Instruction::AShr:
8126     // If this is a signed shr, and if all bits shifted in are about to be
8127     // truncated off, turn it into an unsigned shr to allow greater
8128     // simplifications.
8129     if (DestBitSize < SrcBitSize &&
8130         isa<ConstantInt>(Op1)) {
8131       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8132       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8133         // Insert the new logical shift right.
8134         return BinaryOperator::CreateLShr(Op0, Op1);
8135       }
8136     }
8137     break;
8138   }
8139   return 0;
8140 }
8141
8142 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8143   if (Instruction *Result = commonIntCastTransforms(CI))
8144     return Result;
8145   
8146   Value *Src = CI.getOperand(0);
8147   const Type *Ty = CI.getType();
8148   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8149   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
8150
8151   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8152   if (DestBitWidth == 1) {
8153     Constant *One = ConstantInt::get(Src->getType(), 1);
8154     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8155     Value *Zero = Constant::getNullValue(Src->getType());
8156     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8157   }
8158   
8159   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8160   ConstantInt *ShAmtV = 0;
8161   Value *ShiftOp = 0;
8162   if (Src->hasOneUse() &&
8163       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8164     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8165     
8166     // Get a mask for the bits shifting in.
8167     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8168     if (MaskedValueIsZero(ShiftOp, Mask)) {
8169       if (ShAmt >= DestBitWidth)        // All zeros.
8170         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8171       
8172       // Okay, we can shrink this.  Truncate the input, then return a new
8173       // shift.
8174       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8175       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8176       return BinaryOperator::CreateLShr(V1, V2);
8177     }
8178   }
8179   
8180   return 0;
8181 }
8182
8183 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8184 /// in order to eliminate the icmp.
8185 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8186                                              bool DoXform) {
8187   // If we are just checking for a icmp eq of a single bit and zext'ing it
8188   // to an integer, then shift the bit to the appropriate place and then
8189   // cast to integer to avoid the comparison.
8190   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8191     const APInt &Op1CV = Op1C->getValue();
8192       
8193     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8194     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8195     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8196         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8197       if (!DoXform) return ICI;
8198
8199       Value *In = ICI->getOperand(0);
8200       Value *Sh = ConstantInt::get(In->getType(),
8201                                    In->getType()->getPrimitiveSizeInBits()-1);
8202       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8203                                                         In->getName()+".lobit"),
8204                                CI);
8205       if (In->getType() != CI.getType())
8206         In = CastInst::CreateIntegerCast(In, CI.getType(),
8207                                          false/*ZExt*/, "tmp", &CI);
8208
8209       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8210         Constant *One = ConstantInt::get(In->getType(), 1);
8211         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8212                                                          In->getName()+".not"),
8213                                  CI);
8214       }
8215
8216       return ReplaceInstUsesWith(CI, In);
8217     }
8218       
8219       
8220       
8221     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8222     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8223     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8224     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8225     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8226     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8227     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8228     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8229     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8230         // This only works for EQ and NE
8231         ICI->isEquality()) {
8232       // If Op1C some other power of two, convert:
8233       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8234       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8235       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8236       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8237         
8238       APInt KnownZeroMask(~KnownZero);
8239       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8240         if (!DoXform) return ICI;
8241
8242         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8243         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8244           // (X&4) == 2 --> false
8245           // (X&4) != 2 --> true
8246           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8247           Res = ConstantExpr::getZExt(Res, CI.getType());
8248           return ReplaceInstUsesWith(CI, Res);
8249         }
8250           
8251         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8252         Value *In = ICI->getOperand(0);
8253         if (ShiftAmt) {
8254           // Perform a logical shr by shiftamt.
8255           // Insert the shift to put the result in the low bit.
8256           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8257                                   ConstantInt::get(In->getType(), ShiftAmt),
8258                                                    In->getName()+".lobit"), CI);
8259         }
8260           
8261         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8262           Constant *One = ConstantInt::get(In->getType(), 1);
8263           In = BinaryOperator::CreateXor(In, One, "tmp");
8264           InsertNewInstBefore(cast<Instruction>(In), CI);
8265         }
8266           
8267         if (CI.getType() == In->getType())
8268           return ReplaceInstUsesWith(CI, In);
8269         else
8270           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8271       }
8272     }
8273   }
8274
8275   return 0;
8276 }
8277
8278 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8279   // If one of the common conversion will work ..
8280   if (Instruction *Result = commonIntCastTransforms(CI))
8281     return Result;
8282
8283   Value *Src = CI.getOperand(0);
8284
8285   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8286   // types and if the sizes are just right we can convert this into a logical
8287   // 'and' which will be much cheaper than the pair of casts.
8288   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8289     // Get the sizes of the types involved.  We know that the intermediate type
8290     // will be smaller than A or C, but don't know the relation between A and C.
8291     Value *A = CSrc->getOperand(0);
8292     unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
8293     unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8294     unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8295     // If we're actually extending zero bits, then if
8296     // SrcSize <  DstSize: zext(a & mask)
8297     // SrcSize == DstSize: a & mask
8298     // SrcSize  > DstSize: trunc(a) & mask
8299     if (SrcSize < DstSize) {
8300       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8301       Constant *AndConst = ConstantInt::get(AndValue);
8302       Instruction *And =
8303         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8304       InsertNewInstBefore(And, CI);
8305       return new ZExtInst(And, CI.getType());
8306     } else if (SrcSize == DstSize) {
8307       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8308       return BinaryOperator::CreateAnd(A, ConstantInt::get(AndValue));
8309     } else if (SrcSize > DstSize) {
8310       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8311       InsertNewInstBefore(Trunc, CI);
8312       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8313       return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(AndValue));
8314     }
8315   }
8316
8317   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8318     return transformZExtICmp(ICI, CI);
8319
8320   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8321   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8322     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8323     // of the (zext icmp) will be transformed.
8324     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8325     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8326     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8327         (transformZExtICmp(LHS, CI, false) ||
8328          transformZExtICmp(RHS, CI, false))) {
8329       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8330       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8331       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8332     }
8333   }
8334
8335   return 0;
8336 }
8337
8338 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8339   if (Instruction *I = commonIntCastTransforms(CI))
8340     return I;
8341   
8342   Value *Src = CI.getOperand(0);
8343   
8344   // Canonicalize sign-extend from i1 to a select.
8345   if (Src->getType() == Type::Int1Ty)
8346     return SelectInst::Create(Src,
8347                               ConstantInt::getAllOnesValue(CI.getType()),
8348                               Constant::getNullValue(CI.getType()));
8349
8350   // See if the value being truncated is already sign extended.  If so, just
8351   // eliminate the trunc/sext pair.
8352   if (getOpcode(Src) == Instruction::Trunc) {
8353     Value *Op = cast<User>(Src)->getOperand(0);
8354     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8355     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8356     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8357     unsigned NumSignBits = ComputeNumSignBits(Op);
8358
8359     if (OpBits == DestBits) {
8360       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8361       // bits, it is already ready.
8362       if (NumSignBits > DestBits-MidBits)
8363         return ReplaceInstUsesWith(CI, Op);
8364     } else if (OpBits < DestBits) {
8365       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8366       // bits, just sext from i32.
8367       if (NumSignBits > OpBits-MidBits)
8368         return new SExtInst(Op, CI.getType(), "tmp");
8369     } else {
8370       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8371       // bits, just truncate to i32.
8372       if (NumSignBits > OpBits-MidBits)
8373         return new TruncInst(Op, CI.getType(), "tmp");
8374     }
8375   }
8376
8377   // If the input is a shl/ashr pair of a same constant, then this is a sign
8378   // extension from a smaller value.  If we could trust arbitrary bitwidth
8379   // integers, we could turn this into a truncate to the smaller bit and then
8380   // use a sext for the whole extension.  Since we don't, look deeper and check
8381   // for a truncate.  If the source and dest are the same type, eliminate the
8382   // trunc and extend and just do shifts.  For example, turn:
8383   //   %a = trunc i32 %i to i8
8384   //   %b = shl i8 %a, 6
8385   //   %c = ashr i8 %b, 6
8386   //   %d = sext i8 %c to i32
8387   // into:
8388   //   %a = shl i32 %i, 30
8389   //   %d = ashr i32 %a, 30
8390   Value *A = 0;
8391   ConstantInt *BA = 0, *CA = 0;
8392   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8393                         m_ConstantInt(CA))) &&
8394       BA == CA && isa<TruncInst>(A)) {
8395     Value *I = cast<TruncInst>(A)->getOperand(0);
8396     if (I->getType() == CI.getType()) {
8397       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8398       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8399       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8400       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8401       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8402                                                         CI.getName()), CI);
8403       return BinaryOperator::CreateAShr(I, ShAmtV);
8404     }
8405   }
8406   
8407   return 0;
8408 }
8409
8410 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8411 /// in the specified FP type without changing its value.
8412 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8413   bool losesInfo;
8414   APFloat F = CFP->getValueAPF();
8415   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8416   if (!losesInfo)
8417     return ConstantFP::get(F);
8418   return 0;
8419 }
8420
8421 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8422 /// through it until we get the source value.
8423 static Value *LookThroughFPExtensions(Value *V) {
8424   if (Instruction *I = dyn_cast<Instruction>(V))
8425     if (I->getOpcode() == Instruction::FPExt)
8426       return LookThroughFPExtensions(I->getOperand(0));
8427   
8428   // If this value is a constant, return the constant in the smallest FP type
8429   // that can accurately represent it.  This allows us to turn
8430   // (float)((double)X+2.0) into x+2.0f.
8431   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8432     if (CFP->getType() == Type::PPC_FP128Ty)
8433       return V;  // No constant folding of this.
8434     // See if the value can be truncated to float and then reextended.
8435     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8436       return V;
8437     if (CFP->getType() == Type::DoubleTy)
8438       return V;  // Won't shrink.
8439     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8440       return V;
8441     // Don't try to shrink to various long double types.
8442   }
8443   
8444   return V;
8445 }
8446
8447 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8448   if (Instruction *I = commonCastTransforms(CI))
8449     return I;
8450   
8451   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8452   // smaller than the destination type, we can eliminate the truncate by doing
8453   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8454   // many builtins (sqrt, etc).
8455   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8456   if (OpI && OpI->hasOneUse()) {
8457     switch (OpI->getOpcode()) {
8458     default: break;
8459     case Instruction::Add:
8460     case Instruction::Sub:
8461     case Instruction::Mul:
8462     case Instruction::FDiv:
8463     case Instruction::FRem:
8464       const Type *SrcTy = OpI->getType();
8465       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8466       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8467       if (LHSTrunc->getType() != SrcTy && 
8468           RHSTrunc->getType() != SrcTy) {
8469         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8470         // If the source types were both smaller than the destination type of
8471         // the cast, do this xform.
8472         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8473             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8474           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8475                                       CI.getType(), CI);
8476           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8477                                       CI.getType(), CI);
8478           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8479         }
8480       }
8481       break;  
8482     }
8483   }
8484   return 0;
8485 }
8486
8487 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8488   return commonCastTransforms(CI);
8489 }
8490
8491 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8492   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8493   if (OpI == 0)
8494     return commonCastTransforms(FI);
8495
8496   // fptoui(uitofp(X)) --> X
8497   // fptoui(sitofp(X)) --> X
8498   // This is safe if the intermediate type has enough bits in its mantissa to
8499   // accurately represent all values of X.  For example, do not do this with
8500   // i64->float->i64.  This is also safe for sitofp case, because any negative
8501   // 'X' value would cause an undefined result for the fptoui. 
8502   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8503       OpI->getOperand(0)->getType() == FI.getType() &&
8504       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8505                     OpI->getType()->getFPMantissaWidth())
8506     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8507
8508   return commonCastTransforms(FI);
8509 }
8510
8511 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8512   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8513   if (OpI == 0)
8514     return commonCastTransforms(FI);
8515   
8516   // fptosi(sitofp(X)) --> X
8517   // fptosi(uitofp(X)) --> X
8518   // This is safe if the intermediate type has enough bits in its mantissa to
8519   // accurately represent all values of X.  For example, do not do this with
8520   // i64->float->i64.  This is also safe for sitofp case, because any negative
8521   // 'X' value would cause an undefined result for the fptoui. 
8522   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8523       OpI->getOperand(0)->getType() == FI.getType() &&
8524       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8525                     OpI->getType()->getFPMantissaWidth())
8526     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8527   
8528   return commonCastTransforms(FI);
8529 }
8530
8531 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8532   return commonCastTransforms(CI);
8533 }
8534
8535 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8536   return commonCastTransforms(CI);
8537 }
8538
8539 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8540   return commonPointerCastTransforms(CI);
8541 }
8542
8543 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8544   if (Instruction *I = commonCastTransforms(CI))
8545     return I;
8546   
8547   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8548   if (!DestPointee->isSized()) return 0;
8549
8550   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8551   ConstantInt *Cst;
8552   Value *X;
8553   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8554                                     m_ConstantInt(Cst)))) {
8555     // If the source and destination operands have the same type, see if this
8556     // is a single-index GEP.
8557     if (X->getType() == CI.getType()) {
8558       // Get the size of the pointee type.
8559       uint64_t Size = TD->getTypePaddedSize(DestPointee);
8560
8561       // Convert the constant to intptr type.
8562       APInt Offset = Cst->getValue();
8563       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8564
8565       // If Offset is evenly divisible by Size, we can do this xform.
8566       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8567         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8568         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8569       }
8570     }
8571     // TODO: Could handle other cases, e.g. where add is indexing into field of
8572     // struct etc.
8573   } else if (CI.getOperand(0)->hasOneUse() &&
8574              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8575     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8576     // "inttoptr+GEP" instead of "add+intptr".
8577     
8578     // Get the size of the pointee type.
8579     uint64_t Size = TD->getTypePaddedSize(DestPointee);
8580     
8581     // Convert the constant to intptr type.
8582     APInt Offset = Cst->getValue();
8583     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8584     
8585     // If Offset is evenly divisible by Size, we can do this xform.
8586     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8587       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8588       
8589       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8590                                                             "tmp"), CI);
8591       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8592     }
8593   }
8594   return 0;
8595 }
8596
8597 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8598   // If the operands are integer typed then apply the integer transforms,
8599   // otherwise just apply the common ones.
8600   Value *Src = CI.getOperand(0);
8601   const Type *SrcTy = Src->getType();
8602   const Type *DestTy = CI.getType();
8603
8604   if (SrcTy->isInteger() && DestTy->isInteger()) {
8605     if (Instruction *Result = commonIntCastTransforms(CI))
8606       return Result;
8607   } else if (isa<PointerType>(SrcTy)) {
8608     if (Instruction *I = commonPointerCastTransforms(CI))
8609       return I;
8610   } else {
8611     if (Instruction *Result = commonCastTransforms(CI))
8612       return Result;
8613   }
8614
8615
8616   // Get rid of casts from one type to the same type. These are useless and can
8617   // be replaced by the operand.
8618   if (DestTy == Src->getType())
8619     return ReplaceInstUsesWith(CI, Src);
8620
8621   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8622     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8623     const Type *DstElTy = DstPTy->getElementType();
8624     const Type *SrcElTy = SrcPTy->getElementType();
8625     
8626     // If the address spaces don't match, don't eliminate the bitcast, which is
8627     // required for changing types.
8628     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8629       return 0;
8630     
8631     // If we are casting a malloc or alloca to a pointer to a type of the same
8632     // size, rewrite the allocation instruction to allocate the "right" type.
8633     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8634       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8635         return V;
8636     
8637     // If the source and destination are pointers, and this cast is equivalent
8638     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8639     // This can enhance SROA and other transforms that want type-safe pointers.
8640     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8641     unsigned NumZeros = 0;
8642     while (SrcElTy != DstElTy && 
8643            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8644            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8645       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8646       ++NumZeros;
8647     }
8648
8649     // If we found a path from the src to dest, create the getelementptr now.
8650     if (SrcElTy == DstElTy) {
8651       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8652       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8653                                        ((Instruction*) NULL));
8654     }
8655   }
8656
8657   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8658     if (SVI->hasOneUse()) {
8659       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8660       // a bitconvert to a vector with the same # elts.
8661       if (isa<VectorType>(DestTy) && 
8662           cast<VectorType>(DestTy)->getNumElements() ==
8663                 SVI->getType()->getNumElements() &&
8664           SVI->getType()->getNumElements() ==
8665             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8666         CastInst *Tmp;
8667         // If either of the operands is a cast from CI.getType(), then
8668         // evaluating the shuffle in the casted destination's type will allow
8669         // us to eliminate at least one cast.
8670         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8671              Tmp->getOperand(0)->getType() == DestTy) ||
8672             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8673              Tmp->getOperand(0)->getType() == DestTy)) {
8674           Value *LHS = InsertCastBefore(Instruction::BitCast,
8675                                         SVI->getOperand(0), DestTy, CI);
8676           Value *RHS = InsertCastBefore(Instruction::BitCast,
8677                                         SVI->getOperand(1), DestTy, CI);
8678           // Return a new shuffle vector.  Use the same element ID's, as we
8679           // know the vector types match #elts.
8680           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8681         }
8682       }
8683     }
8684   }
8685   return 0;
8686 }
8687
8688 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8689 ///   %C = or %A, %B
8690 ///   %D = select %cond, %C, %A
8691 /// into:
8692 ///   %C = select %cond, %B, 0
8693 ///   %D = or %A, %C
8694 ///
8695 /// Assuming that the specified instruction is an operand to the select, return
8696 /// a bitmask indicating which operands of this instruction are foldable if they
8697 /// equal the other incoming value of the select.
8698 ///
8699 static unsigned GetSelectFoldableOperands(Instruction *I) {
8700   switch (I->getOpcode()) {
8701   case Instruction::Add:
8702   case Instruction::Mul:
8703   case Instruction::And:
8704   case Instruction::Or:
8705   case Instruction::Xor:
8706     return 3;              // Can fold through either operand.
8707   case Instruction::Sub:   // Can only fold on the amount subtracted.
8708   case Instruction::Shl:   // Can only fold on the shift amount.
8709   case Instruction::LShr:
8710   case Instruction::AShr:
8711     return 1;
8712   default:
8713     return 0;              // Cannot fold
8714   }
8715 }
8716
8717 /// GetSelectFoldableConstant - For the same transformation as the previous
8718 /// function, return the identity constant that goes into the select.
8719 static Constant *GetSelectFoldableConstant(Instruction *I) {
8720   switch (I->getOpcode()) {
8721   default: assert(0 && "This cannot happen!"); abort();
8722   case Instruction::Add:
8723   case Instruction::Sub:
8724   case Instruction::Or:
8725   case Instruction::Xor:
8726   case Instruction::Shl:
8727   case Instruction::LShr:
8728   case Instruction::AShr:
8729     return Constant::getNullValue(I->getType());
8730   case Instruction::And:
8731     return Constant::getAllOnesValue(I->getType());
8732   case Instruction::Mul:
8733     return ConstantInt::get(I->getType(), 1);
8734   }
8735 }
8736
8737 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8738 /// have the same opcode and only one use each.  Try to simplify this.
8739 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8740                                           Instruction *FI) {
8741   if (TI->getNumOperands() == 1) {
8742     // If this is a non-volatile load or a cast from the same type,
8743     // merge.
8744     if (TI->isCast()) {
8745       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8746         return 0;
8747     } else {
8748       return 0;  // unknown unary op.
8749     }
8750
8751     // Fold this by inserting a select from the input values.
8752     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8753                                            FI->getOperand(0), SI.getName()+".v");
8754     InsertNewInstBefore(NewSI, SI);
8755     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8756                             TI->getType());
8757   }
8758
8759   // Only handle binary operators here.
8760   if (!isa<BinaryOperator>(TI))
8761     return 0;
8762
8763   // Figure out if the operations have any operands in common.
8764   Value *MatchOp, *OtherOpT, *OtherOpF;
8765   bool MatchIsOpZero;
8766   if (TI->getOperand(0) == FI->getOperand(0)) {
8767     MatchOp  = TI->getOperand(0);
8768     OtherOpT = TI->getOperand(1);
8769     OtherOpF = FI->getOperand(1);
8770     MatchIsOpZero = true;
8771   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8772     MatchOp  = TI->getOperand(1);
8773     OtherOpT = TI->getOperand(0);
8774     OtherOpF = FI->getOperand(0);
8775     MatchIsOpZero = false;
8776   } else if (!TI->isCommutative()) {
8777     return 0;
8778   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8779     MatchOp  = TI->getOperand(0);
8780     OtherOpT = TI->getOperand(1);
8781     OtherOpF = FI->getOperand(0);
8782     MatchIsOpZero = true;
8783   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8784     MatchOp  = TI->getOperand(1);
8785     OtherOpT = TI->getOperand(0);
8786     OtherOpF = FI->getOperand(1);
8787     MatchIsOpZero = true;
8788   } else {
8789     return 0;
8790   }
8791
8792   // If we reach here, they do have operations in common.
8793   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8794                                          OtherOpF, SI.getName()+".v");
8795   InsertNewInstBefore(NewSI, SI);
8796
8797   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8798     if (MatchIsOpZero)
8799       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8800     else
8801       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8802   }
8803   assert(0 && "Shouldn't get here");
8804   return 0;
8805 }
8806
8807 /// visitSelectInstWithICmp - Visit a SelectInst that has an
8808 /// ICmpInst as its first operand.
8809 ///
8810 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8811                                                    ICmpInst *ICI) {
8812   bool Changed = false;
8813   ICmpInst::Predicate Pred = ICI->getPredicate();
8814   Value *CmpLHS = ICI->getOperand(0);
8815   Value *CmpRHS = ICI->getOperand(1);
8816   Value *TrueVal = SI.getTrueValue();
8817   Value *FalseVal = SI.getFalseValue();
8818
8819   // Check cases where the comparison is with a constant that
8820   // can be adjusted to fit the min/max idiom. We may edit ICI in
8821   // place here, so make sure the select is the only user.
8822   if (ICI->hasOneUse())
8823     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
8824       switch (Pred) {
8825       default: break;
8826       case ICmpInst::ICMP_ULT:
8827       case ICmpInst::ICMP_SLT: {
8828         // X < MIN ? T : F  -->  F
8829         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8830           return ReplaceInstUsesWith(SI, FalseVal);
8831         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
8832         Constant *AdjustedRHS = SubOne(CI);
8833         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8834             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8835           Pred = ICmpInst::getSwappedPredicate(Pred);
8836           CmpRHS = AdjustedRHS;
8837           std::swap(FalseVal, TrueVal);
8838           ICI->setPredicate(Pred);
8839           ICI->setOperand(1, CmpRHS);
8840           SI.setOperand(1, TrueVal);
8841           SI.setOperand(2, FalseVal);
8842           Changed = true;
8843         }
8844         break;
8845       }
8846       case ICmpInst::ICMP_UGT:
8847       case ICmpInst::ICMP_SGT: {
8848         // X > MAX ? T : F  -->  F
8849         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8850           return ReplaceInstUsesWith(SI, FalseVal);
8851         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
8852         Constant *AdjustedRHS = AddOne(CI);
8853         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8854             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8855           Pred = ICmpInst::getSwappedPredicate(Pred);
8856           CmpRHS = AdjustedRHS;
8857           std::swap(FalseVal, TrueVal);
8858           ICI->setPredicate(Pred);
8859           ICI->setOperand(1, CmpRHS);
8860           SI.setOperand(1, TrueVal);
8861           SI.setOperand(2, FalseVal);
8862           Changed = true;
8863         }
8864         break;
8865       }
8866       }
8867
8868       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
8869       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
8870       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
8871       if (match(TrueVal, m_ConstantInt<-1>()) &&
8872           match(FalseVal, m_ConstantInt<0>()))
8873         Pred = ICI->getPredicate();
8874       else if (match(TrueVal, m_ConstantInt<0>()) &&
8875                match(FalseVal, m_ConstantInt<-1>()))
8876         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8877       
8878       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8879         // If we are just checking for a icmp eq of a single bit and zext'ing it
8880         // to an integer, then shift the bit to the appropriate place and then
8881         // cast to integer to avoid the comparison.
8882         const APInt &Op1CV = CI->getValue();
8883     
8884         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
8885         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
8886         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8887             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
8888           Value *In = ICI->getOperand(0);
8889           Value *Sh = ConstantInt::get(In->getType(),
8890                                        In->getType()->getPrimitiveSizeInBits()-1);
8891           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8892                                                           In->getName()+".lobit"),
8893                                    *ICI);
8894           if (In->getType() != SI.getType())
8895             In = CastInst::CreateIntegerCast(In, SI.getType(),
8896                                              true/*SExt*/, "tmp", ICI);
8897     
8898           if (Pred == ICmpInst::ICMP_SGT)
8899             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8900                                        In->getName()+".not"), *ICI);
8901     
8902           return ReplaceInstUsesWith(SI, In);
8903         }
8904       }
8905     }
8906
8907   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8908     // Transform (X == Y) ? X : Y  -> Y
8909     if (Pred == ICmpInst::ICMP_EQ)
8910       return ReplaceInstUsesWith(SI, FalseVal);
8911     // Transform (X != Y) ? X : Y  -> X
8912     if (Pred == ICmpInst::ICMP_NE)
8913       return ReplaceInstUsesWith(SI, TrueVal);
8914     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8915
8916   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8917     // Transform (X == Y) ? Y : X  -> X
8918     if (Pred == ICmpInst::ICMP_EQ)
8919       return ReplaceInstUsesWith(SI, FalseVal);
8920     // Transform (X != Y) ? Y : X  -> Y
8921     if (Pred == ICmpInst::ICMP_NE)
8922       return ReplaceInstUsesWith(SI, TrueVal);
8923     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8924   }
8925
8926   /// NOTE: if we wanted to, this is where to detect integer ABS
8927
8928   return Changed ? &SI : 0;
8929 }
8930
8931 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8932   Value *CondVal = SI.getCondition();
8933   Value *TrueVal = SI.getTrueValue();
8934   Value *FalseVal = SI.getFalseValue();
8935
8936   // select true, X, Y  -> X
8937   // select false, X, Y -> Y
8938   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8939     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8940
8941   // select C, X, X -> X
8942   if (TrueVal == FalseVal)
8943     return ReplaceInstUsesWith(SI, TrueVal);
8944
8945   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8946     return ReplaceInstUsesWith(SI, FalseVal);
8947   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8948     return ReplaceInstUsesWith(SI, TrueVal);
8949   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8950     if (isa<Constant>(TrueVal))
8951       return ReplaceInstUsesWith(SI, TrueVal);
8952     else
8953       return ReplaceInstUsesWith(SI, FalseVal);
8954   }
8955
8956   if (SI.getType() == Type::Int1Ty) {
8957     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8958       if (C->getZExtValue()) {
8959         // Change: A = select B, true, C --> A = or B, C
8960         return BinaryOperator::CreateOr(CondVal, FalseVal);
8961       } else {
8962         // Change: A = select B, false, C --> A = and !B, C
8963         Value *NotCond =
8964           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8965                                              "not."+CondVal->getName()), SI);
8966         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8967       }
8968     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8969       if (C->getZExtValue() == false) {
8970         // Change: A = select B, C, false --> A = and B, C
8971         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8972       } else {
8973         // Change: A = select B, C, true --> A = or !B, C
8974         Value *NotCond =
8975           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8976                                              "not."+CondVal->getName()), SI);
8977         return BinaryOperator::CreateOr(NotCond, TrueVal);
8978       }
8979     }
8980     
8981     // select a, b, a  -> a&b
8982     // select a, a, b  -> a|b
8983     if (CondVal == TrueVal)
8984       return BinaryOperator::CreateOr(CondVal, FalseVal);
8985     else if (CondVal == FalseVal)
8986       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8987   }
8988
8989   // Selecting between two integer constants?
8990   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8991     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8992       // select C, 1, 0 -> zext C to int
8993       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8994         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8995       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8996         // select C, 0, 1 -> zext !C to int
8997         Value *NotCond =
8998           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8999                                                "not."+CondVal->getName()), SI);
9000         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9001       }
9002
9003       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9004
9005         // (x <s 0) ? -1 : 0 -> ashr x, 31
9006         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9007           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9008             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9009               // The comparison constant and the result are not neccessarily the
9010               // same width. Make an all-ones value by inserting a AShr.
9011               Value *X = IC->getOperand(0);
9012               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
9013               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
9014               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
9015                                                         ShAmt, "ones");
9016               InsertNewInstBefore(SRA, SI);
9017
9018               // Then cast to the appropriate width.
9019               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
9020             }
9021           }
9022
9023
9024         // If one of the constants is zero (we know they can't both be) and we
9025         // have an icmp instruction with zero, and we have an 'and' with the
9026         // non-constant value, eliminate this whole mess.  This corresponds to
9027         // cases like this: ((X & 27) ? 27 : 0)
9028         if (TrueValC->isZero() || FalseValC->isZero())
9029           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9030               cast<Constant>(IC->getOperand(1))->isNullValue())
9031             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9032               if (ICA->getOpcode() == Instruction::And &&
9033                   isa<ConstantInt>(ICA->getOperand(1)) &&
9034                   (ICA->getOperand(1) == TrueValC ||
9035                    ICA->getOperand(1) == FalseValC) &&
9036                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9037                 // Okay, now we know that everything is set up, we just don't
9038                 // know whether we have a icmp_ne or icmp_eq and whether the 
9039                 // true or false val is the zero.
9040                 bool ShouldNotVal = !TrueValC->isZero();
9041                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9042                 Value *V = ICA;
9043                 if (ShouldNotVal)
9044                   V = InsertNewInstBefore(BinaryOperator::Create(
9045                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9046                 return ReplaceInstUsesWith(SI, V);
9047               }
9048       }
9049     }
9050
9051   // See if we are selecting two values based on a comparison of the two values.
9052   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9053     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9054       // Transform (X == Y) ? X : Y  -> Y
9055       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9056         // This is not safe in general for floating point:  
9057         // consider X== -0, Y== +0.
9058         // It becomes safe if either operand is a nonzero constant.
9059         ConstantFP *CFPt, *CFPf;
9060         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9061               !CFPt->getValueAPF().isZero()) ||
9062             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9063              !CFPf->getValueAPF().isZero()))
9064         return ReplaceInstUsesWith(SI, FalseVal);
9065       }
9066       // Transform (X != Y) ? X : Y  -> X
9067       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9068         return ReplaceInstUsesWith(SI, TrueVal);
9069       // NOTE: if we wanted to, this is where to detect MIN/MAX
9070
9071     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9072       // Transform (X == Y) ? Y : X  -> X
9073       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9074         // This is not safe in general for floating point:  
9075         // consider X== -0, Y== +0.
9076         // It becomes safe if either operand is a nonzero constant.
9077         ConstantFP *CFPt, *CFPf;
9078         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9079               !CFPt->getValueAPF().isZero()) ||
9080             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9081              !CFPf->getValueAPF().isZero()))
9082           return ReplaceInstUsesWith(SI, FalseVal);
9083       }
9084       // Transform (X != Y) ? Y : X  -> Y
9085       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9086         return ReplaceInstUsesWith(SI, TrueVal);
9087       // NOTE: if we wanted to, this is where to detect MIN/MAX
9088     }
9089     // NOTE: if we wanted to, this is where to detect ABS
9090   }
9091
9092   // See if we are selecting two values based on a comparison of the two values.
9093   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9094     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9095       return Result;
9096
9097   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9098     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9099       if (TI->hasOneUse() && FI->hasOneUse()) {
9100         Instruction *AddOp = 0, *SubOp = 0;
9101
9102         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9103         if (TI->getOpcode() == FI->getOpcode())
9104           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9105             return IV;
9106
9107         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9108         // even legal for FP.
9109         if (TI->getOpcode() == Instruction::Sub &&
9110             FI->getOpcode() == Instruction::Add) {
9111           AddOp = FI; SubOp = TI;
9112         } else if (FI->getOpcode() == Instruction::Sub &&
9113                    TI->getOpcode() == Instruction::Add) {
9114           AddOp = TI; SubOp = FI;
9115         }
9116
9117         if (AddOp) {
9118           Value *OtherAddOp = 0;
9119           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9120             OtherAddOp = AddOp->getOperand(1);
9121           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9122             OtherAddOp = AddOp->getOperand(0);
9123           }
9124
9125           if (OtherAddOp) {
9126             // So at this point we know we have (Y -> OtherAddOp):
9127             //        select C, (add X, Y), (sub X, Z)
9128             Value *NegVal;  // Compute -Z
9129             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9130               NegVal = ConstantExpr::getNeg(C);
9131             } else {
9132               NegVal = InsertNewInstBefore(
9133                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9134             }
9135
9136             Value *NewTrueOp = OtherAddOp;
9137             Value *NewFalseOp = NegVal;
9138             if (AddOp != TI)
9139               std::swap(NewTrueOp, NewFalseOp);
9140             Instruction *NewSel =
9141               SelectInst::Create(CondVal, NewTrueOp,
9142                                  NewFalseOp, SI.getName() + ".p");
9143
9144             NewSel = InsertNewInstBefore(NewSel, SI);
9145             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9146           }
9147         }
9148       }
9149
9150   // See if we can fold the select into one of our operands.
9151   if (SI.getType()->isInteger()) {
9152     // See the comment above GetSelectFoldableOperands for a description of the
9153     // transformation we are doing here.
9154     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9155       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9156           !isa<Constant>(FalseVal))
9157         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9158           unsigned OpToFold = 0;
9159           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9160             OpToFold = 1;
9161           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9162             OpToFold = 2;
9163           }
9164
9165           if (OpToFold) {
9166             Constant *C = GetSelectFoldableConstant(TVI);
9167             Instruction *NewSel =
9168               SelectInst::Create(SI.getCondition(),
9169                                  TVI->getOperand(2-OpToFold), C);
9170             InsertNewInstBefore(NewSel, SI);
9171             NewSel->takeName(TVI);
9172             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9173               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9174             else {
9175               assert(0 && "Unknown instruction!!");
9176             }
9177           }
9178         }
9179
9180     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9181       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9182           !isa<Constant>(TrueVal))
9183         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9184           unsigned OpToFold = 0;
9185           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9186             OpToFold = 1;
9187           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9188             OpToFold = 2;
9189           }
9190
9191           if (OpToFold) {
9192             Constant *C = GetSelectFoldableConstant(FVI);
9193             Instruction *NewSel =
9194               SelectInst::Create(SI.getCondition(), C,
9195                                  FVI->getOperand(2-OpToFold));
9196             InsertNewInstBefore(NewSel, SI);
9197             NewSel->takeName(FVI);
9198             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9199               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9200             else
9201               assert(0 && "Unknown instruction!!");
9202           }
9203         }
9204   }
9205
9206   if (BinaryOperator::isNot(CondVal)) {
9207     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9208     SI.setOperand(1, FalseVal);
9209     SI.setOperand(2, TrueVal);
9210     return &SI;
9211   }
9212
9213   return 0;
9214 }
9215
9216 /// EnforceKnownAlignment - If the specified pointer points to an object that
9217 /// we control, modify the object's alignment to PrefAlign. This isn't
9218 /// often possible though. If alignment is important, a more reliable approach
9219 /// is to simply align all global variables and allocation instructions to
9220 /// their preferred alignment from the beginning.
9221 ///
9222 static unsigned EnforceKnownAlignment(Value *V,
9223                                       unsigned Align, unsigned PrefAlign) {
9224
9225   User *U = dyn_cast<User>(V);
9226   if (!U) return Align;
9227
9228   switch (getOpcode(U)) {
9229   default: break;
9230   case Instruction::BitCast:
9231     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9232   case Instruction::GetElementPtr: {
9233     // If all indexes are zero, it is just the alignment of the base pointer.
9234     bool AllZeroOperands = true;
9235     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9236       if (!isa<Constant>(*i) ||
9237           !cast<Constant>(*i)->isNullValue()) {
9238         AllZeroOperands = false;
9239         break;
9240       }
9241
9242     if (AllZeroOperands) {
9243       // Treat this like a bitcast.
9244       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9245     }
9246     break;
9247   }
9248   }
9249
9250   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9251     // If there is a large requested alignment and we can, bump up the alignment
9252     // of the global.
9253     if (!GV->isDeclaration()) {
9254       if (GV->getAlignment() >= PrefAlign)
9255         Align = GV->getAlignment();
9256       else {
9257         GV->setAlignment(PrefAlign);
9258         Align = PrefAlign;
9259       }
9260     }
9261   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9262     // If there is a requested alignment and if this is an alloca, round up.  We
9263     // don't do this for malloc, because some systems can't respect the request.
9264     if (isa<AllocaInst>(AI)) {
9265       if (AI->getAlignment() >= PrefAlign)
9266         Align = AI->getAlignment();
9267       else {
9268         AI->setAlignment(PrefAlign);
9269         Align = PrefAlign;
9270       }
9271     }
9272   }
9273
9274   return Align;
9275 }
9276
9277 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9278 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9279 /// and it is more than the alignment of the ultimate object, see if we can
9280 /// increase the alignment of the ultimate object, making this check succeed.
9281 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9282                                                   unsigned PrefAlign) {
9283   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9284                       sizeof(PrefAlign) * CHAR_BIT;
9285   APInt Mask = APInt::getAllOnesValue(BitWidth);
9286   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9287   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9288   unsigned TrailZ = KnownZero.countTrailingOnes();
9289   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9290
9291   if (PrefAlign > Align)
9292     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9293   
9294     // We don't need to make any adjustment.
9295   return Align;
9296 }
9297
9298 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9299   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9300   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9301   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9302   unsigned CopyAlign = MI->getAlignment();
9303
9304   if (CopyAlign < MinAlign) {
9305     MI->setAlignment(MinAlign);
9306     return MI;
9307   }
9308   
9309   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9310   // load/store.
9311   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9312   if (MemOpLength == 0) return 0;
9313   
9314   // Source and destination pointer types are always "i8*" for intrinsic.  See
9315   // if the size is something we can handle with a single primitive load/store.
9316   // A single load+store correctly handles overlapping memory in the memmove
9317   // case.
9318   unsigned Size = MemOpLength->getZExtValue();
9319   if (Size == 0) return MI;  // Delete this mem transfer.
9320   
9321   if (Size > 8 || (Size&(Size-1)))
9322     return 0;  // If not 1/2/4/8 bytes, exit.
9323   
9324   // Use an integer load+store unless we can find something better.
9325   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9326   
9327   // Memcpy forces the use of i8* for the source and destination.  That means
9328   // that if you're using memcpy to move one double around, you'll get a cast
9329   // from double* to i8*.  We'd much rather use a double load+store rather than
9330   // an i64 load+store, here because this improves the odds that the source or
9331   // dest address will be promotable.  See if we can find a better type than the
9332   // integer datatype.
9333   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9334     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9335     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9336       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9337       // down through these levels if so.
9338       while (!SrcETy->isSingleValueType()) {
9339         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9340           if (STy->getNumElements() == 1)
9341             SrcETy = STy->getElementType(0);
9342           else
9343             break;
9344         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9345           if (ATy->getNumElements() == 1)
9346             SrcETy = ATy->getElementType();
9347           else
9348             break;
9349         } else
9350           break;
9351       }
9352       
9353       if (SrcETy->isSingleValueType())
9354         NewPtrTy = PointerType::getUnqual(SrcETy);
9355     }
9356   }
9357   
9358   
9359   // If the memcpy/memmove provides better alignment info than we can
9360   // infer, use it.
9361   SrcAlign = std::max(SrcAlign, CopyAlign);
9362   DstAlign = std::max(DstAlign, CopyAlign);
9363   
9364   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9365   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9366   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9367   InsertNewInstBefore(L, *MI);
9368   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9369
9370   // Set the size of the copy to 0, it will be deleted on the next iteration.
9371   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9372   return MI;
9373 }
9374
9375 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9376   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9377   if (MI->getAlignment() < Alignment) {
9378     MI->setAlignment(Alignment);
9379     return MI;
9380   }
9381   
9382   // Extract the length and alignment and fill if they are constant.
9383   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9384   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9385   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9386     return 0;
9387   uint64_t Len = LenC->getZExtValue();
9388   Alignment = MI->getAlignment();
9389   
9390   // If the length is zero, this is a no-op
9391   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9392   
9393   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9394   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9395     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9396     
9397     Value *Dest = MI->getDest();
9398     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9399
9400     // Alignment 0 is identity for alignment 1 for memset, but not store.
9401     if (Alignment == 0) Alignment = 1;
9402     
9403     // Extract the fill value and store.
9404     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9405     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9406                                       Alignment), *MI);
9407     
9408     // Set the size of the copy to 0, it will be deleted on the next iteration.
9409     MI->setLength(Constant::getNullValue(LenC->getType()));
9410     return MI;
9411   }
9412
9413   return 0;
9414 }
9415
9416
9417 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9418 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9419 /// the heavy lifting.
9420 ///
9421 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9422   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9423   if (!II) return visitCallSite(&CI);
9424   
9425   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9426   // visitCallSite.
9427   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9428     bool Changed = false;
9429
9430     // memmove/cpy/set of zero bytes is a noop.
9431     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9432       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9433
9434       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9435         if (CI->getZExtValue() == 1) {
9436           // Replace the instruction with just byte operations.  We would
9437           // transform other cases to loads/stores, but we don't know if
9438           // alignment is sufficient.
9439         }
9440     }
9441
9442     // If we have a memmove and the source operation is a constant global,
9443     // then the source and dest pointers can't alias, so we can change this
9444     // into a call to memcpy.
9445     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9446       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9447         if (GVSrc->isConstant()) {
9448           Module *M = CI.getParent()->getParent()->getParent();
9449           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9450           const Type *Tys[1];
9451           Tys[0] = CI.getOperand(3)->getType();
9452           CI.setOperand(0, 
9453                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9454           Changed = true;
9455         }
9456
9457       // memmove(x,x,size) -> noop.
9458       if (MMI->getSource() == MMI->getDest())
9459         return EraseInstFromFunction(CI);
9460     }
9461
9462     // If we can determine a pointer alignment that is bigger than currently
9463     // set, update the alignment.
9464     if (isa<MemTransferInst>(MI)) {
9465       if (Instruction *I = SimplifyMemTransfer(MI))
9466         return I;
9467     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9468       if (Instruction *I = SimplifyMemSet(MSI))
9469         return I;
9470     }
9471           
9472     if (Changed) return II;
9473   }
9474   
9475   switch (II->getIntrinsicID()) {
9476   default: break;
9477   case Intrinsic::bswap:
9478     // bswap(bswap(x)) -> x
9479     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9480       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9481         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9482     break;
9483   case Intrinsic::ppc_altivec_lvx:
9484   case Intrinsic::ppc_altivec_lvxl:
9485   case Intrinsic::x86_sse_loadu_ps:
9486   case Intrinsic::x86_sse2_loadu_pd:
9487   case Intrinsic::x86_sse2_loadu_dq:
9488     // Turn PPC lvx     -> load if the pointer is known aligned.
9489     // Turn X86 loadups -> load if the pointer is known aligned.
9490     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9491       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9492                                        PointerType::getUnqual(II->getType()),
9493                                        CI);
9494       return new LoadInst(Ptr);
9495     }
9496     break;
9497   case Intrinsic::ppc_altivec_stvx:
9498   case Intrinsic::ppc_altivec_stvxl:
9499     // Turn stvx -> store if the pointer is known aligned.
9500     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9501       const Type *OpPtrTy = 
9502         PointerType::getUnqual(II->getOperand(1)->getType());
9503       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9504       return new StoreInst(II->getOperand(1), Ptr);
9505     }
9506     break;
9507   case Intrinsic::x86_sse_storeu_ps:
9508   case Intrinsic::x86_sse2_storeu_pd:
9509   case Intrinsic::x86_sse2_storeu_dq:
9510     // Turn X86 storeu -> store if the pointer is known aligned.
9511     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9512       const Type *OpPtrTy = 
9513         PointerType::getUnqual(II->getOperand(2)->getType());
9514       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9515       return new StoreInst(II->getOperand(2), Ptr);
9516     }
9517     break;
9518     
9519   case Intrinsic::x86_sse_cvttss2si: {
9520     // These intrinsics only demands the 0th element of its input vector.  If
9521     // we can simplify the input based on that, do so now.
9522     unsigned VWidth =
9523       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9524     APInt DemandedElts(VWidth, 1);
9525     APInt UndefElts(VWidth, 0);
9526     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9527                                               UndefElts)) {
9528       II->setOperand(1, V);
9529       return II;
9530     }
9531     break;
9532   }
9533     
9534   case Intrinsic::ppc_altivec_vperm:
9535     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9536     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9537       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9538       
9539       // Check that all of the elements are integer constants or undefs.
9540       bool AllEltsOk = true;
9541       for (unsigned i = 0; i != 16; ++i) {
9542         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9543             !isa<UndefValue>(Mask->getOperand(i))) {
9544           AllEltsOk = false;
9545           break;
9546         }
9547       }
9548       
9549       if (AllEltsOk) {
9550         // Cast the input vectors to byte vectors.
9551         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9552         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9553         Value *Result = UndefValue::get(Op0->getType());
9554         
9555         // Only extract each element once.
9556         Value *ExtractedElts[32];
9557         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9558         
9559         for (unsigned i = 0; i != 16; ++i) {
9560           if (isa<UndefValue>(Mask->getOperand(i)))
9561             continue;
9562           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9563           Idx &= 31;  // Match the hardware behavior.
9564           
9565           if (ExtractedElts[Idx] == 0) {
9566             Instruction *Elt = 
9567               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9568             InsertNewInstBefore(Elt, CI);
9569             ExtractedElts[Idx] = Elt;
9570           }
9571         
9572           // Insert this value into the result vector.
9573           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9574                                              i, "tmp");
9575           InsertNewInstBefore(cast<Instruction>(Result), CI);
9576         }
9577         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9578       }
9579     }
9580     break;
9581
9582   case Intrinsic::stackrestore: {
9583     // If the save is right next to the restore, remove the restore.  This can
9584     // happen when variable allocas are DCE'd.
9585     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9586       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9587         BasicBlock::iterator BI = SS;
9588         if (&*++BI == II)
9589           return EraseInstFromFunction(CI);
9590       }
9591     }
9592     
9593     // Scan down this block to see if there is another stack restore in the
9594     // same block without an intervening call/alloca.
9595     BasicBlock::iterator BI = II;
9596     TerminatorInst *TI = II->getParent()->getTerminator();
9597     bool CannotRemove = false;
9598     for (++BI; &*BI != TI; ++BI) {
9599       if (isa<AllocaInst>(BI)) {
9600         CannotRemove = true;
9601         break;
9602       }
9603       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9604         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9605           // If there is a stackrestore below this one, remove this one.
9606           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9607             return EraseInstFromFunction(CI);
9608           // Otherwise, ignore the intrinsic.
9609         } else {
9610           // If we found a non-intrinsic call, we can't remove the stack
9611           // restore.
9612           CannotRemove = true;
9613           break;
9614         }
9615       }
9616     }
9617     
9618     // If the stack restore is in a return/unwind block and if there are no
9619     // allocas or calls between the restore and the return, nuke the restore.
9620     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9621       return EraseInstFromFunction(CI);
9622     break;
9623   }
9624   }
9625
9626   return visitCallSite(II);
9627 }
9628
9629 // InvokeInst simplification
9630 //
9631 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9632   return visitCallSite(&II);
9633 }
9634
9635 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9636 /// passed through the varargs area, we can eliminate the use of the cast.
9637 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9638                                          const CastInst * const CI,
9639                                          const TargetData * const TD,
9640                                          const int ix) {
9641   if (!CI->isLosslessCast())
9642     return false;
9643
9644   // The size of ByVal arguments is derived from the type, so we
9645   // can't change to a type with a different size.  If the size were
9646   // passed explicitly we could avoid this check.
9647   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9648     return true;
9649
9650   const Type* SrcTy = 
9651             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9652   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9653   if (!SrcTy->isSized() || !DstTy->isSized())
9654     return false;
9655   if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
9656     return false;
9657   return true;
9658 }
9659
9660 // visitCallSite - Improvements for call and invoke instructions.
9661 //
9662 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9663   bool Changed = false;
9664
9665   // If the callee is a constexpr cast of a function, attempt to move the cast
9666   // to the arguments of the call/invoke.
9667   if (transformConstExprCastCall(CS)) return 0;
9668
9669   Value *Callee = CS.getCalledValue();
9670
9671   if (Function *CalleeF = dyn_cast<Function>(Callee))
9672     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9673       Instruction *OldCall = CS.getInstruction();
9674       // If the call and callee calling conventions don't match, this call must
9675       // be unreachable, as the call is undefined.
9676       new StoreInst(ConstantInt::getTrue(),
9677                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9678                                     OldCall);
9679       if (!OldCall->use_empty())
9680         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9681       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9682         return EraseInstFromFunction(*OldCall);
9683       return 0;
9684     }
9685
9686   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9687     // This instruction is not reachable, just remove it.  We insert a store to
9688     // undef so that we know that this code is not reachable, despite the fact
9689     // that we can't modify the CFG here.
9690     new StoreInst(ConstantInt::getTrue(),
9691                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9692                   CS.getInstruction());
9693
9694     if (!CS.getInstruction()->use_empty())
9695       CS.getInstruction()->
9696         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9697
9698     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9699       // Don't break the CFG, insert a dummy cond branch.
9700       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9701                          ConstantInt::getTrue(), II);
9702     }
9703     return EraseInstFromFunction(*CS.getInstruction());
9704   }
9705
9706   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9707     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9708       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9709         return transformCallThroughTrampoline(CS);
9710
9711   const PointerType *PTy = cast<PointerType>(Callee->getType());
9712   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9713   if (FTy->isVarArg()) {
9714     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9715     // See if we can optimize any arguments passed through the varargs area of
9716     // the call.
9717     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9718            E = CS.arg_end(); I != E; ++I, ++ix) {
9719       CastInst *CI = dyn_cast<CastInst>(*I);
9720       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9721         *I = CI->getOperand(0);
9722         Changed = true;
9723       }
9724     }
9725   }
9726
9727   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9728     // Inline asm calls cannot throw - mark them 'nounwind'.
9729     CS.setDoesNotThrow();
9730     Changed = true;
9731   }
9732
9733   return Changed ? CS.getInstruction() : 0;
9734 }
9735
9736 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9737 // attempt to move the cast to the arguments of the call/invoke.
9738 //
9739 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9740   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9741   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9742   if (CE->getOpcode() != Instruction::BitCast || 
9743       !isa<Function>(CE->getOperand(0)))
9744     return false;
9745   Function *Callee = cast<Function>(CE->getOperand(0));
9746   Instruction *Caller = CS.getInstruction();
9747   const AttrListPtr &CallerPAL = CS.getAttributes();
9748
9749   // Okay, this is a cast from a function to a different type.  Unless doing so
9750   // would cause a type conversion of one of our arguments, change this call to
9751   // be a direct call with arguments casted to the appropriate types.
9752   //
9753   const FunctionType *FT = Callee->getFunctionType();
9754   const Type *OldRetTy = Caller->getType();
9755   const Type *NewRetTy = FT->getReturnType();
9756
9757   if (isa<StructType>(NewRetTy))
9758     return false; // TODO: Handle multiple return values.
9759
9760   // Check to see if we are changing the return type...
9761   if (OldRetTy != NewRetTy) {
9762     if (Callee->isDeclaration() &&
9763         // Conversion is ok if changing from one pointer type to another or from
9764         // a pointer to an integer of the same size.
9765         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9766           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9767       return false;   // Cannot transform this return value.
9768
9769     if (!Caller->use_empty() &&
9770         // void -> non-void is handled specially
9771         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9772       return false;   // Cannot transform this return value.
9773
9774     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9775       Attributes RAttrs = CallerPAL.getRetAttributes();
9776       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9777         return false;   // Attribute not compatible with transformed value.
9778     }
9779
9780     // If the callsite is an invoke instruction, and the return value is used by
9781     // a PHI node in a successor, we cannot change the return type of the call
9782     // because there is no place to put the cast instruction (without breaking
9783     // the critical edge).  Bail out in this case.
9784     if (!Caller->use_empty())
9785       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9786         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9787              UI != E; ++UI)
9788           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9789             if (PN->getParent() == II->getNormalDest() ||
9790                 PN->getParent() == II->getUnwindDest())
9791               return false;
9792   }
9793
9794   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9795   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9796
9797   CallSite::arg_iterator AI = CS.arg_begin();
9798   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9799     const Type *ParamTy = FT->getParamType(i);
9800     const Type *ActTy = (*AI)->getType();
9801
9802     if (!CastInst::isCastable(ActTy, ParamTy))
9803       return false;   // Cannot transform this parameter value.
9804
9805     if (CallerPAL.getParamAttributes(i + 1) 
9806         & Attribute::typeIncompatible(ParamTy))
9807       return false;   // Attribute not compatible with transformed value.
9808
9809     // Converting from one pointer type to another or between a pointer and an
9810     // integer of the same size is safe even if we do not have a body.
9811     bool isConvertible = ActTy == ParamTy ||
9812       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9813        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9814     if (Callee->isDeclaration() && !isConvertible) return false;
9815   }
9816
9817   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9818       Callee->isDeclaration())
9819     return false;   // Do not delete arguments unless we have a function body.
9820
9821   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9822       !CallerPAL.isEmpty())
9823     // In this case we have more arguments than the new function type, but we
9824     // won't be dropping them.  Check that these extra arguments have attributes
9825     // that are compatible with being a vararg call argument.
9826     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9827       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9828         break;
9829       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9830       if (PAttrs & Attribute::VarArgsIncompatible)
9831         return false;
9832     }
9833
9834   // Okay, we decided that this is a safe thing to do: go ahead and start
9835   // inserting cast instructions as necessary...
9836   std::vector<Value*> Args;
9837   Args.reserve(NumActualArgs);
9838   SmallVector<AttributeWithIndex, 8> attrVec;
9839   attrVec.reserve(NumCommonArgs);
9840
9841   // Get any return attributes.
9842   Attributes RAttrs = CallerPAL.getRetAttributes();
9843
9844   // If the return value is not being used, the type may not be compatible
9845   // with the existing attributes.  Wipe out any problematic attributes.
9846   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
9847
9848   // Add the new return attributes.
9849   if (RAttrs)
9850     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
9851
9852   AI = CS.arg_begin();
9853   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9854     const Type *ParamTy = FT->getParamType(i);
9855     if ((*AI)->getType() == ParamTy) {
9856       Args.push_back(*AI);
9857     } else {
9858       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9859           false, ParamTy, false);
9860       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9861       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9862     }
9863
9864     // Add any parameter attributes.
9865     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9866       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9867   }
9868
9869   // If the function takes more arguments than the call was taking, add them
9870   // now...
9871   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9872     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9873
9874   // If we are removing arguments to the function, emit an obnoxious warning...
9875   if (FT->getNumParams() < NumActualArgs) {
9876     if (!FT->isVarArg()) {
9877       cerr << "WARNING: While resolving call to function '"
9878            << Callee->getName() << "' arguments were dropped!\n";
9879     } else {
9880       // Add all of the arguments in their promoted form to the arg list...
9881       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9882         const Type *PTy = getPromotedType((*AI)->getType());
9883         if (PTy != (*AI)->getType()) {
9884           // Must promote to pass through va_arg area!
9885           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9886                                                                 PTy, false);
9887           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9888           InsertNewInstBefore(Cast, *Caller);
9889           Args.push_back(Cast);
9890         } else {
9891           Args.push_back(*AI);
9892         }
9893
9894         // Add any parameter attributes.
9895         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9896           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9897       }
9898     }
9899   }
9900
9901   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
9902     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9903
9904   if (NewRetTy == Type::VoidTy)
9905     Caller->setName("");   // Void type should not have a name.
9906
9907   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
9908
9909   Instruction *NC;
9910   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9911     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9912                             Args.begin(), Args.end(),
9913                             Caller->getName(), Caller);
9914     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9915     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
9916   } else {
9917     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9918                           Caller->getName(), Caller);
9919     CallInst *CI = cast<CallInst>(Caller);
9920     if (CI->isTailCall())
9921       cast<CallInst>(NC)->setTailCall();
9922     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9923     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
9924   }
9925
9926   // Insert a cast of the return type as necessary.
9927   Value *NV = NC;
9928   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9929     if (NV->getType() != Type::VoidTy) {
9930       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9931                                                             OldRetTy, false);
9932       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9933
9934       // If this is an invoke instruction, we should insert it after the first
9935       // non-phi, instruction in the normal successor block.
9936       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9937         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9938         InsertNewInstBefore(NC, *I);
9939       } else {
9940         // Otherwise, it's a call, just insert cast right after the call instr
9941         InsertNewInstBefore(NC, *Caller);
9942       }
9943       AddUsersToWorkList(*Caller);
9944     } else {
9945       NV = UndefValue::get(Caller->getType());
9946     }
9947   }
9948
9949   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9950     Caller->replaceAllUsesWith(NV);
9951   Caller->eraseFromParent();
9952   RemoveFromWorkList(Caller);
9953   return true;
9954 }
9955
9956 // transformCallThroughTrampoline - Turn a call to a function created by the
9957 // init_trampoline intrinsic into a direct call to the underlying function.
9958 //
9959 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9960   Value *Callee = CS.getCalledValue();
9961   const PointerType *PTy = cast<PointerType>(Callee->getType());
9962   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9963   const AttrListPtr &Attrs = CS.getAttributes();
9964
9965   // If the call already has the 'nest' attribute somewhere then give up -
9966   // otherwise 'nest' would occur twice after splicing in the chain.
9967   if (Attrs.hasAttrSomewhere(Attribute::Nest))
9968     return 0;
9969
9970   IntrinsicInst *Tramp =
9971     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9972
9973   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9974   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9975   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9976
9977   const AttrListPtr &NestAttrs = NestF->getAttributes();
9978   if (!NestAttrs.isEmpty()) {
9979     unsigned NestIdx = 1;
9980     const Type *NestTy = 0;
9981     Attributes NestAttr = Attribute::None;
9982
9983     // Look for a parameter marked with the 'nest' attribute.
9984     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9985          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9986       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
9987         // Record the parameter type and any other attributes.
9988         NestTy = *I;
9989         NestAttr = NestAttrs.getParamAttributes(NestIdx);
9990         break;
9991       }
9992
9993     if (NestTy) {
9994       Instruction *Caller = CS.getInstruction();
9995       std::vector<Value*> NewArgs;
9996       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9997
9998       SmallVector<AttributeWithIndex, 8> NewAttrs;
9999       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10000
10001       // Insert the nest argument into the call argument list, which may
10002       // mean appending it.  Likewise for attributes.
10003
10004       // Add any result attributes.
10005       if (Attributes Attr = Attrs.getRetAttributes())
10006         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10007
10008       {
10009         unsigned Idx = 1;
10010         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10011         do {
10012           if (Idx == NestIdx) {
10013             // Add the chain argument and attributes.
10014             Value *NestVal = Tramp->getOperand(3);
10015             if (NestVal->getType() != NestTy)
10016               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10017             NewArgs.push_back(NestVal);
10018             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10019           }
10020
10021           if (I == E)
10022             break;
10023
10024           // Add the original argument and attributes.
10025           NewArgs.push_back(*I);
10026           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10027             NewAttrs.push_back
10028               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10029
10030           ++Idx, ++I;
10031         } while (1);
10032       }
10033
10034       // Add any function attributes.
10035       if (Attributes Attr = Attrs.getFnAttributes())
10036         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10037
10038       // The trampoline may have been bitcast to a bogus type (FTy).
10039       // Handle this by synthesizing a new function type, equal to FTy
10040       // with the chain parameter inserted.
10041
10042       std::vector<const Type*> NewTypes;
10043       NewTypes.reserve(FTy->getNumParams()+1);
10044
10045       // Insert the chain's type into the list of parameter types, which may
10046       // mean appending it.
10047       {
10048         unsigned Idx = 1;
10049         FunctionType::param_iterator I = FTy->param_begin(),
10050           E = FTy->param_end();
10051
10052         do {
10053           if (Idx == NestIdx)
10054             // Add the chain's type.
10055             NewTypes.push_back(NestTy);
10056
10057           if (I == E)
10058             break;
10059
10060           // Add the original type.
10061           NewTypes.push_back(*I);
10062
10063           ++Idx, ++I;
10064         } while (1);
10065       }
10066
10067       // Replace the trampoline call with a direct call.  Let the generic
10068       // code sort out any function type mismatches.
10069       FunctionType *NewFTy =
10070         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
10071       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10072         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
10073       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10074
10075       Instruction *NewCaller;
10076       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10077         NewCaller = InvokeInst::Create(NewCallee,
10078                                        II->getNormalDest(), II->getUnwindDest(),
10079                                        NewArgs.begin(), NewArgs.end(),
10080                                        Caller->getName(), Caller);
10081         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10082         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10083       } else {
10084         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10085                                      Caller->getName(), Caller);
10086         if (cast<CallInst>(Caller)->isTailCall())
10087           cast<CallInst>(NewCaller)->setTailCall();
10088         cast<CallInst>(NewCaller)->
10089           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10090         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10091       }
10092       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10093         Caller->replaceAllUsesWith(NewCaller);
10094       Caller->eraseFromParent();
10095       RemoveFromWorkList(Caller);
10096       return 0;
10097     }
10098   }
10099
10100   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10101   // parameter, there is no need to adjust the argument list.  Let the generic
10102   // code sort out any function type mismatches.
10103   Constant *NewCallee =
10104     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10105   CS.setCalledFunction(NewCallee);
10106   return CS.getInstruction();
10107 }
10108
10109 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10110 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10111 /// and a single binop.
10112 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10113   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10114   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10115   unsigned Opc = FirstInst->getOpcode();
10116   Value *LHSVal = FirstInst->getOperand(0);
10117   Value *RHSVal = FirstInst->getOperand(1);
10118     
10119   const Type *LHSType = LHSVal->getType();
10120   const Type *RHSType = RHSVal->getType();
10121   
10122   // Scan to see if all operands are the same opcode, all have one use, and all
10123   // kill their operands (i.e. the operands have one use).
10124   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10125     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10126     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10127         // Verify type of the LHS matches so we don't fold cmp's of different
10128         // types or GEP's with different index types.
10129         I->getOperand(0)->getType() != LHSType ||
10130         I->getOperand(1)->getType() != RHSType)
10131       return 0;
10132
10133     // If they are CmpInst instructions, check their predicates
10134     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10135       if (cast<CmpInst>(I)->getPredicate() !=
10136           cast<CmpInst>(FirstInst)->getPredicate())
10137         return 0;
10138     
10139     // Keep track of which operand needs a phi node.
10140     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10141     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10142   }
10143   
10144   // Otherwise, this is safe to transform!
10145   
10146   Value *InLHS = FirstInst->getOperand(0);
10147   Value *InRHS = FirstInst->getOperand(1);
10148   PHINode *NewLHS = 0, *NewRHS = 0;
10149   if (LHSVal == 0) {
10150     NewLHS = PHINode::Create(LHSType,
10151                              FirstInst->getOperand(0)->getName() + ".pn");
10152     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10153     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10154     InsertNewInstBefore(NewLHS, PN);
10155     LHSVal = NewLHS;
10156   }
10157   
10158   if (RHSVal == 0) {
10159     NewRHS = PHINode::Create(RHSType,
10160                              FirstInst->getOperand(1)->getName() + ".pn");
10161     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10162     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10163     InsertNewInstBefore(NewRHS, PN);
10164     RHSVal = NewRHS;
10165   }
10166   
10167   // Add all operands to the new PHIs.
10168   if (NewLHS || NewRHS) {
10169     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10170       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10171       if (NewLHS) {
10172         Value *NewInLHS = InInst->getOperand(0);
10173         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10174       }
10175       if (NewRHS) {
10176         Value *NewInRHS = InInst->getOperand(1);
10177         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10178       }
10179     }
10180   }
10181     
10182   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10183     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10184   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10185   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10186                          RHSVal);
10187 }
10188
10189 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10190   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10191   
10192   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10193                                         FirstInst->op_end());
10194   // This is true if all GEP bases are allocas and if all indices into them are
10195   // constants.
10196   bool AllBasePointersAreAllocas = true;
10197   
10198   // Scan to see if all operands are the same opcode, all have one use, and all
10199   // kill their operands (i.e. the operands have one use).
10200   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10201     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10202     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10203       GEP->getNumOperands() != FirstInst->getNumOperands())
10204       return 0;
10205
10206     // Keep track of whether or not all GEPs are of alloca pointers.
10207     if (AllBasePointersAreAllocas &&
10208         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10209          !GEP->hasAllConstantIndices()))
10210       AllBasePointersAreAllocas = false;
10211     
10212     // Compare the operand lists.
10213     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10214       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10215         continue;
10216       
10217       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10218       // if one of the PHIs has a constant for the index.  The index may be
10219       // substantially cheaper to compute for the constants, so making it a
10220       // variable index could pessimize the path.  This also handles the case
10221       // for struct indices, which must always be constant.
10222       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10223           isa<ConstantInt>(GEP->getOperand(op)))
10224         return 0;
10225       
10226       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10227         return 0;
10228       FixedOperands[op] = 0;  // Needs a PHI.
10229     }
10230   }
10231   
10232   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10233   // bother doing this transformation.  At best, this will just save a bit of
10234   // offset calculation, but all the predecessors will have to materialize the
10235   // stack address into a register anyway.  We'd actually rather *clone* the
10236   // load up into the predecessors so that we have a load of a gep of an alloca,
10237   // which can usually all be folded into the load.
10238   if (AllBasePointersAreAllocas)
10239     return 0;
10240   
10241   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10242   // that is variable.
10243   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10244   
10245   bool HasAnyPHIs = false;
10246   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10247     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10248     Value *FirstOp = FirstInst->getOperand(i);
10249     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10250                                      FirstOp->getName()+".pn");
10251     InsertNewInstBefore(NewPN, PN);
10252     
10253     NewPN->reserveOperandSpace(e);
10254     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10255     OperandPhis[i] = NewPN;
10256     FixedOperands[i] = NewPN;
10257     HasAnyPHIs = true;
10258   }
10259
10260   
10261   // Add all operands to the new PHIs.
10262   if (HasAnyPHIs) {
10263     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10264       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10265       BasicBlock *InBB = PN.getIncomingBlock(i);
10266       
10267       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10268         if (PHINode *OpPhi = OperandPhis[op])
10269           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10270     }
10271   }
10272   
10273   Value *Base = FixedOperands[0];
10274   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10275                                    FixedOperands.end());
10276 }
10277
10278
10279 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10280 /// sink the load out of the block that defines it.  This means that it must be
10281 /// obvious the value of the load is not changed from the point of the load to
10282 /// the end of the block it is in.
10283 ///
10284 /// Finally, it is safe, but not profitable, to sink a load targetting a
10285 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10286 /// to a register.
10287 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10288   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10289   
10290   for (++BBI; BBI != E; ++BBI)
10291     if (BBI->mayWriteToMemory())
10292       return false;
10293   
10294   // Check for non-address taken alloca.  If not address-taken already, it isn't
10295   // profitable to do this xform.
10296   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10297     bool isAddressTaken = false;
10298     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10299          UI != E; ++UI) {
10300       if (isa<LoadInst>(UI)) continue;
10301       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10302         // If storing TO the alloca, then the address isn't taken.
10303         if (SI->getOperand(1) == AI) continue;
10304       }
10305       isAddressTaken = true;
10306       break;
10307     }
10308     
10309     if (!isAddressTaken && AI->isStaticAlloca())
10310       return false;
10311   }
10312   
10313   // If this load is a load from a GEP with a constant offset from an alloca,
10314   // then we don't want to sink it.  In its present form, it will be
10315   // load [constant stack offset].  Sinking it will cause us to have to
10316   // materialize the stack addresses in each predecessor in a register only to
10317   // do a shared load from register in the successor.
10318   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10319     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10320       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10321         return false;
10322   
10323   return true;
10324 }
10325
10326
10327 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10328 // operator and they all are only used by the PHI, PHI together their
10329 // inputs, and do the operation once, to the result of the PHI.
10330 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10331   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10332
10333   // Scan the instruction, looking for input operations that can be folded away.
10334   // If all input operands to the phi are the same instruction (e.g. a cast from
10335   // the same type or "+42") we can pull the operation through the PHI, reducing
10336   // code size and simplifying code.
10337   Constant *ConstantOp = 0;
10338   const Type *CastSrcTy = 0;
10339   bool isVolatile = false;
10340   if (isa<CastInst>(FirstInst)) {
10341     CastSrcTy = FirstInst->getOperand(0)->getType();
10342   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10343     // Can fold binop, compare or shift here if the RHS is a constant, 
10344     // otherwise call FoldPHIArgBinOpIntoPHI.
10345     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10346     if (ConstantOp == 0)
10347       return FoldPHIArgBinOpIntoPHI(PN);
10348   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10349     isVolatile = LI->isVolatile();
10350     // We can't sink the load if the loaded value could be modified between the
10351     // load and the PHI.
10352     if (LI->getParent() != PN.getIncomingBlock(0) ||
10353         !isSafeAndProfitableToSinkLoad(LI))
10354       return 0;
10355     
10356     // If the PHI is of volatile loads and the load block has multiple
10357     // successors, sinking it would remove a load of the volatile value from
10358     // the path through the other successor.
10359     if (isVolatile &&
10360         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10361       return 0;
10362     
10363   } else if (isa<GetElementPtrInst>(FirstInst)) {
10364     return FoldPHIArgGEPIntoPHI(PN);
10365   } else {
10366     return 0;  // Cannot fold this operation.
10367   }
10368
10369   // Check to see if all arguments are the same operation.
10370   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10371     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10372     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10373     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10374       return 0;
10375     if (CastSrcTy) {
10376       if (I->getOperand(0)->getType() != CastSrcTy)
10377         return 0;  // Cast operation must match.
10378     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10379       // We can't sink the load if the loaded value could be modified between 
10380       // the load and the PHI.
10381       if (LI->isVolatile() != isVolatile ||
10382           LI->getParent() != PN.getIncomingBlock(i) ||
10383           !isSafeAndProfitableToSinkLoad(LI))
10384         return 0;
10385       
10386       // If the PHI is of volatile loads and the load block has multiple
10387       // successors, sinking it would remove a load of the volatile value from
10388       // the path through the other successor.
10389       if (isVolatile &&
10390           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10391         return 0;
10392       
10393     } else if (I->getOperand(1) != ConstantOp) {
10394       return 0;
10395     }
10396   }
10397
10398   // Okay, they are all the same operation.  Create a new PHI node of the
10399   // correct type, and PHI together all of the LHS's of the instructions.
10400   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10401                                    PN.getName()+".in");
10402   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10403
10404   Value *InVal = FirstInst->getOperand(0);
10405   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10406
10407   // Add all operands to the new PHI.
10408   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10409     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10410     if (NewInVal != InVal)
10411       InVal = 0;
10412     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10413   }
10414
10415   Value *PhiVal;
10416   if (InVal) {
10417     // The new PHI unions all of the same values together.  This is really
10418     // common, so we handle it intelligently here for compile-time speed.
10419     PhiVal = InVal;
10420     delete NewPN;
10421   } else {
10422     InsertNewInstBefore(NewPN, PN);
10423     PhiVal = NewPN;
10424   }
10425
10426   // Insert and return the new operation.
10427   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10428     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10429   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10430     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10431   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10432     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10433                            PhiVal, ConstantOp);
10434   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10435   
10436   // If this was a volatile load that we are merging, make sure to loop through
10437   // and mark all the input loads as non-volatile.  If we don't do this, we will
10438   // insert a new volatile load and the old ones will not be deletable.
10439   if (isVolatile)
10440     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10441       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10442   
10443   return new LoadInst(PhiVal, "", isVolatile);
10444 }
10445
10446 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10447 /// that is dead.
10448 static bool DeadPHICycle(PHINode *PN,
10449                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10450   if (PN->use_empty()) return true;
10451   if (!PN->hasOneUse()) return false;
10452
10453   // Remember this node, and if we find the cycle, return.
10454   if (!PotentiallyDeadPHIs.insert(PN))
10455     return true;
10456   
10457   // Don't scan crazily complex things.
10458   if (PotentiallyDeadPHIs.size() == 16)
10459     return false;
10460
10461   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10462     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10463
10464   return false;
10465 }
10466
10467 /// PHIsEqualValue - Return true if this phi node is always equal to
10468 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10469 ///   z = some value; x = phi (y, z); y = phi (x, z)
10470 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10471                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10472   // See if we already saw this PHI node.
10473   if (!ValueEqualPHIs.insert(PN))
10474     return true;
10475   
10476   // Don't scan crazily complex things.
10477   if (ValueEqualPHIs.size() == 16)
10478     return false;
10479  
10480   // Scan the operands to see if they are either phi nodes or are equal to
10481   // the value.
10482   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10483     Value *Op = PN->getIncomingValue(i);
10484     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10485       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10486         return false;
10487     } else if (Op != NonPhiInVal)
10488       return false;
10489   }
10490   
10491   return true;
10492 }
10493
10494
10495 // PHINode simplification
10496 //
10497 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10498   // If LCSSA is around, don't mess with Phi nodes
10499   if (MustPreserveLCSSA) return 0;
10500   
10501   if (Value *V = PN.hasConstantValue())
10502     return ReplaceInstUsesWith(PN, V);
10503
10504   // If all PHI operands are the same operation, pull them through the PHI,
10505   // reducing code size.
10506   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10507       isa<Instruction>(PN.getIncomingValue(1)) &&
10508       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10509       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10510       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10511       // than themselves more than once.
10512       PN.getIncomingValue(0)->hasOneUse())
10513     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10514       return Result;
10515
10516   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10517   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10518   // PHI)... break the cycle.
10519   if (PN.hasOneUse()) {
10520     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10521     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10522       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10523       PotentiallyDeadPHIs.insert(&PN);
10524       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10525         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10526     }
10527    
10528     // If this phi has a single use, and if that use just computes a value for
10529     // the next iteration of a loop, delete the phi.  This occurs with unused
10530     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10531     // common case here is good because the only other things that catch this
10532     // are induction variable analysis (sometimes) and ADCE, which is only run
10533     // late.
10534     if (PHIUser->hasOneUse() &&
10535         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10536         PHIUser->use_back() == &PN) {
10537       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10538     }
10539   }
10540
10541   // We sometimes end up with phi cycles that non-obviously end up being the
10542   // same value, for example:
10543   //   z = some value; x = phi (y, z); y = phi (x, z)
10544   // where the phi nodes don't necessarily need to be in the same block.  Do a
10545   // quick check to see if the PHI node only contains a single non-phi value, if
10546   // so, scan to see if the phi cycle is actually equal to that value.
10547   {
10548     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10549     // Scan for the first non-phi operand.
10550     while (InValNo != NumOperandVals && 
10551            isa<PHINode>(PN.getIncomingValue(InValNo)))
10552       ++InValNo;
10553
10554     if (InValNo != NumOperandVals) {
10555       Value *NonPhiInVal = PN.getOperand(InValNo);
10556       
10557       // Scan the rest of the operands to see if there are any conflicts, if so
10558       // there is no need to recursively scan other phis.
10559       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10560         Value *OpVal = PN.getIncomingValue(InValNo);
10561         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10562           break;
10563       }
10564       
10565       // If we scanned over all operands, then we have one unique value plus
10566       // phi values.  Scan PHI nodes to see if they all merge in each other or
10567       // the value.
10568       if (InValNo == NumOperandVals) {
10569         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10570         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10571           return ReplaceInstUsesWith(PN, NonPhiInVal);
10572       }
10573     }
10574   }
10575   return 0;
10576 }
10577
10578 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10579                                    Instruction *InsertPoint,
10580                                    InstCombiner *IC) {
10581   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10582   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10583   // We must cast correctly to the pointer type. Ensure that we
10584   // sign extend the integer value if it is smaller as this is
10585   // used for address computation.
10586   Instruction::CastOps opcode = 
10587      (VTySize < PtrSize ? Instruction::SExt :
10588       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10589   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10590 }
10591
10592
10593 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10594   Value *PtrOp = GEP.getOperand(0);
10595   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10596   // If so, eliminate the noop.
10597   if (GEP.getNumOperands() == 1)
10598     return ReplaceInstUsesWith(GEP, PtrOp);
10599
10600   if (isa<UndefValue>(GEP.getOperand(0)))
10601     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10602
10603   bool HasZeroPointerIndex = false;
10604   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10605     HasZeroPointerIndex = C->isNullValue();
10606
10607   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10608     return ReplaceInstUsesWith(GEP, PtrOp);
10609
10610   // Eliminate unneeded casts for indices.
10611   bool MadeChange = false;
10612   
10613   gep_type_iterator GTI = gep_type_begin(GEP);
10614   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10615        i != e; ++i, ++GTI) {
10616     if (isa<SequentialType>(*GTI)) {
10617       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10618         if (CI->getOpcode() == Instruction::ZExt ||
10619             CI->getOpcode() == Instruction::SExt) {
10620           const Type *SrcTy = CI->getOperand(0)->getType();
10621           // We can eliminate a cast from i32 to i64 iff the target 
10622           // is a 32-bit pointer target.
10623           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10624             MadeChange = true;
10625             *i = CI->getOperand(0);
10626           }
10627         }
10628       }
10629       // If we are using a wider index than needed for this platform, shrink it
10630       // to what we need.  If narrower, sign-extend it to what we need.
10631       // If the incoming value needs a cast instruction,
10632       // insert it.  This explicit cast can make subsequent optimizations more
10633       // obvious.
10634       Value *Op = *i;
10635       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10636         if (Constant *C = dyn_cast<Constant>(Op)) {
10637           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10638           MadeChange = true;
10639         } else {
10640           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10641                                 GEP);
10642           *i = Op;
10643           MadeChange = true;
10644         }
10645       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10646         if (Constant *C = dyn_cast<Constant>(Op)) {
10647           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10648           MadeChange = true;
10649         } else {
10650           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10651                                 GEP);
10652           *i = Op;
10653           MadeChange = true;
10654         }
10655       }
10656     }
10657   }
10658   if (MadeChange) return &GEP;
10659
10660   // Combine Indices - If the source pointer to this getelementptr instruction
10661   // is a getelementptr instruction, combine the indices of the two
10662   // getelementptr instructions into a single instruction.
10663   //
10664   SmallVector<Value*, 8> SrcGEPOperands;
10665   if (User *Src = dyn_castGetElementPtr(PtrOp))
10666     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10667
10668   if (!SrcGEPOperands.empty()) {
10669     // Note that if our source is a gep chain itself that we wait for that
10670     // chain to be resolved before we perform this transformation.  This
10671     // avoids us creating a TON of code in some cases.
10672     //
10673     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10674         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10675       return 0;   // Wait until our source is folded to completion.
10676
10677     SmallVector<Value*, 8> Indices;
10678
10679     // Find out whether the last index in the source GEP is a sequential idx.
10680     bool EndsWithSequential = false;
10681     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10682            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10683       EndsWithSequential = !isa<StructType>(*I);
10684
10685     // Can we combine the two pointer arithmetics offsets?
10686     if (EndsWithSequential) {
10687       // Replace: gep (gep %P, long B), long A, ...
10688       // With:    T = long A+B; gep %P, T, ...
10689       //
10690       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10691       if (SO1 == Constant::getNullValue(SO1->getType())) {
10692         Sum = GO1;
10693       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10694         Sum = SO1;
10695       } else {
10696         // If they aren't the same type, convert both to an integer of the
10697         // target's pointer size.
10698         if (SO1->getType() != GO1->getType()) {
10699           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10700             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10701           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10702             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10703           } else {
10704             unsigned PS = TD->getPointerSizeInBits();
10705             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10706               // Convert GO1 to SO1's type.
10707               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10708
10709             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10710               // Convert SO1 to GO1's type.
10711               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10712             } else {
10713               const Type *PT = TD->getIntPtrType();
10714               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10715               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10716             }
10717           }
10718         }
10719         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10720           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10721         else {
10722           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10723           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10724         }
10725       }
10726
10727       // Recycle the GEP we already have if possible.
10728       if (SrcGEPOperands.size() == 2) {
10729         GEP.setOperand(0, SrcGEPOperands[0]);
10730         GEP.setOperand(1, Sum);
10731         return &GEP;
10732       } else {
10733         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10734                        SrcGEPOperands.end()-1);
10735         Indices.push_back(Sum);
10736         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10737       }
10738     } else if (isa<Constant>(*GEP.idx_begin()) &&
10739                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10740                SrcGEPOperands.size() != 1) {
10741       // Otherwise we can do the fold if the first index of the GEP is a zero
10742       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10743                      SrcGEPOperands.end());
10744       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10745     }
10746
10747     if (!Indices.empty())
10748       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10749                                        Indices.end(), GEP.getName());
10750
10751   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10752     // GEP of global variable.  If all of the indices for this GEP are
10753     // constants, we can promote this to a constexpr instead of an instruction.
10754
10755     // Scan for nonconstants...
10756     SmallVector<Constant*, 8> Indices;
10757     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10758     for (; I != E && isa<Constant>(*I); ++I)
10759       Indices.push_back(cast<Constant>(*I));
10760
10761     if (I == E) {  // If they are all constants...
10762       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10763                                                     &Indices[0],Indices.size());
10764
10765       // Replace all uses of the GEP with the new constexpr...
10766       return ReplaceInstUsesWith(GEP, CE);
10767     }
10768   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10769     if (!isa<PointerType>(X->getType())) {
10770       // Not interesting.  Source pointer must be a cast from pointer.
10771     } else if (HasZeroPointerIndex) {
10772       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10773       // into     : GEP [10 x i8]* X, i32 0, ...
10774       //
10775       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10776       //           into     : GEP i8* X, ...
10777       // 
10778       // This occurs when the program declares an array extern like "int X[];"
10779       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10780       const PointerType *XTy = cast<PointerType>(X->getType());
10781       if (const ArrayType *CATy =
10782           dyn_cast<ArrayType>(CPTy->getElementType())) {
10783         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10784         if (CATy->getElementType() == XTy->getElementType()) {
10785           // -> GEP i8* X, ...
10786           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10787           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10788                                            GEP.getName());
10789         } else if (const ArrayType *XATy =
10790                  dyn_cast<ArrayType>(XTy->getElementType())) {
10791           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
10792           if (CATy->getElementType() == XATy->getElementType()) {
10793             // -> GEP [10 x i8]* X, i32 0, ...
10794             // At this point, we know that the cast source type is a pointer
10795             // to an array of the same type as the destination pointer
10796             // array.  Because the array type is never stepped over (there
10797             // is a leading zero) we can fold the cast into this GEP.
10798             GEP.setOperand(0, X);
10799             return &GEP;
10800           }
10801         }
10802       }
10803     } else if (GEP.getNumOperands() == 2) {
10804       // Transform things like:
10805       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10806       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10807       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10808       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10809       if (isa<ArrayType>(SrcElTy) &&
10810           TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10811           TD->getTypePaddedSize(ResElTy)) {
10812         Value *Idx[2];
10813         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10814         Idx[1] = GEP.getOperand(1);
10815         Value *V = InsertNewInstBefore(
10816                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10817         // V and GEP are both pointer types --> BitCast
10818         return new BitCastInst(V, GEP.getType());
10819       }
10820       
10821       // Transform things like:
10822       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10823       //   (where tmp = 8*tmp2) into:
10824       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10825       
10826       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10827         uint64_t ArrayEltSize =
10828             TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
10829         
10830         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10831         // allow either a mul, shift, or constant here.
10832         Value *NewIdx = 0;
10833         ConstantInt *Scale = 0;
10834         if (ArrayEltSize == 1) {
10835           NewIdx = GEP.getOperand(1);
10836           Scale = ConstantInt::get(NewIdx->getType(), 1);
10837         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10838           NewIdx = ConstantInt::get(CI->getType(), 1);
10839           Scale = CI;
10840         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10841           if (Inst->getOpcode() == Instruction::Shl &&
10842               isa<ConstantInt>(Inst->getOperand(1))) {
10843             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10844             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10845             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10846             NewIdx = Inst->getOperand(0);
10847           } else if (Inst->getOpcode() == Instruction::Mul &&
10848                      isa<ConstantInt>(Inst->getOperand(1))) {
10849             Scale = cast<ConstantInt>(Inst->getOperand(1));
10850             NewIdx = Inst->getOperand(0);
10851           }
10852         }
10853         
10854         // If the index will be to exactly the right offset with the scale taken
10855         // out, perform the transformation. Note, we don't know whether Scale is
10856         // signed or not. We'll use unsigned version of division/modulo
10857         // operation after making sure Scale doesn't have the sign bit set.
10858         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
10859             Scale->getZExtValue() % ArrayEltSize == 0) {
10860           Scale = ConstantInt::get(Scale->getType(),
10861                                    Scale->getZExtValue() / ArrayEltSize);
10862           if (Scale->getZExtValue() != 1) {
10863             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10864                                                        false /*ZExt*/);
10865             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10866             NewIdx = InsertNewInstBefore(Sc, GEP);
10867           }
10868
10869           // Insert the new GEP instruction.
10870           Value *Idx[2];
10871           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10872           Idx[1] = NewIdx;
10873           Instruction *NewGEP =
10874             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10875           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10876           // The NewGEP must be pointer typed, so must the old one -> BitCast
10877           return new BitCastInst(NewGEP, GEP.getType());
10878         }
10879       }
10880     }
10881   }
10882   
10883   /// See if we can simplify:
10884   ///   X = bitcast A to B*
10885   ///   Y = gep X, <...constant indices...>
10886   /// into a gep of the original struct.  This is important for SROA and alias
10887   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
10888   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
10889     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10890       // Determine how much the GEP moves the pointer.  We are guaranteed to get
10891       // a constant back from EmitGEPOffset.
10892       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10893       int64_t Offset = OffsetV->getSExtValue();
10894       
10895       // If this GEP instruction doesn't move the pointer, just replace the GEP
10896       // with a bitcast of the real input to the dest type.
10897       if (Offset == 0) {
10898         // If the bitcast is of an allocation, and the allocation will be
10899         // converted to match the type of the cast, don't touch this.
10900         if (isa<AllocationInst>(BCI->getOperand(0))) {
10901           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10902           if (Instruction *I = visitBitCast(*BCI)) {
10903             if (I != BCI) {
10904               I->takeName(BCI);
10905               BCI->getParent()->getInstList().insert(BCI, I);
10906               ReplaceInstUsesWith(*BCI, I);
10907             }
10908             return &GEP;
10909           }
10910         }
10911         return new BitCastInst(BCI->getOperand(0), GEP.getType());
10912       }
10913       
10914       // Otherwise, if the offset is non-zero, we need to find out if there is a
10915       // field at Offset in 'A's type.  If so, we can pull the cast through the
10916       // GEP.
10917       SmallVector<Value*, 8> NewIndices;
10918       const Type *InTy =
10919         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10920       if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10921         Instruction *NGEP =
10922            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10923                                      NewIndices.end());
10924         if (NGEP->getType() == GEP.getType()) return NGEP;
10925         InsertNewInstBefore(NGEP, GEP);
10926         NGEP->takeName(&GEP);
10927         return new BitCastInst(NGEP, GEP.getType());
10928       }
10929     }
10930   }    
10931     
10932   return 0;
10933 }
10934
10935 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10936   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10937   if (AI.isArrayAllocation()) {  // Check C != 1
10938     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10939       const Type *NewTy = 
10940         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10941       AllocationInst *New = 0;
10942
10943       // Create and insert the replacement instruction...
10944       if (isa<MallocInst>(AI))
10945         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10946       else {
10947         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10948         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10949       }
10950
10951       InsertNewInstBefore(New, AI);
10952
10953       // Scan to the end of the allocation instructions, to skip over a block of
10954       // allocas if possible...also skip interleaved debug info
10955       //
10956       BasicBlock::iterator It = New;
10957       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
10958
10959       // Now that I is pointing to the first non-allocation-inst in the block,
10960       // insert our getelementptr instruction...
10961       //
10962       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10963       Value *Idx[2];
10964       Idx[0] = NullIdx;
10965       Idx[1] = NullIdx;
10966       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10967                                            New->getName()+".sub", It);
10968
10969       // Now make everything use the getelementptr instead of the original
10970       // allocation.
10971       return ReplaceInstUsesWith(AI, V);
10972     } else if (isa<UndefValue>(AI.getArraySize())) {
10973       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10974     }
10975   }
10976
10977   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
10978     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10979     // Note that we only do this for alloca's, because malloc should allocate
10980     // and return a unique pointer, even for a zero byte allocation.
10981     if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
10982       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10983
10984     // If the alignment is 0 (unspecified), assign it the preferred alignment.
10985     if (AI.getAlignment() == 0)
10986       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
10987   }
10988
10989   return 0;
10990 }
10991
10992 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10993   Value *Op = FI.getOperand(0);
10994
10995   // free undef -> unreachable.
10996   if (isa<UndefValue>(Op)) {
10997     // Insert a new store to null because we cannot modify the CFG here.
10998     new StoreInst(ConstantInt::getTrue(),
10999                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
11000     return EraseInstFromFunction(FI);
11001   }
11002   
11003   // If we have 'free null' delete the instruction.  This can happen in stl code
11004   // when lots of inlining happens.
11005   if (isa<ConstantPointerNull>(Op))
11006     return EraseInstFromFunction(FI);
11007   
11008   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11009   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11010     FI.setOperand(0, CI->getOperand(0));
11011     return &FI;
11012   }
11013   
11014   // Change free (gep X, 0,0,0,0) into free(X)
11015   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11016     if (GEPI->hasAllZeroIndices()) {
11017       AddToWorkList(GEPI);
11018       FI.setOperand(0, GEPI->getOperand(0));
11019       return &FI;
11020     }
11021   }
11022   
11023   // Change free(malloc) into nothing, if the malloc has a single use.
11024   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11025     if (MI->hasOneUse()) {
11026       EraseInstFromFunction(FI);
11027       return EraseInstFromFunction(*MI);
11028     }
11029
11030   return 0;
11031 }
11032
11033
11034 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11035 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11036                                         const TargetData *TD) {
11037   User *CI = cast<User>(LI.getOperand(0));
11038   Value *CastOp = CI->getOperand(0);
11039
11040   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11041     // Instead of loading constant c string, use corresponding integer value
11042     // directly if string length is small enough.
11043     std::string Str;
11044     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11045       unsigned len = Str.length();
11046       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11047       unsigned numBits = Ty->getPrimitiveSizeInBits();
11048       // Replace LI with immediate integer store.
11049       if ((numBits >> 3) == len + 1) {
11050         APInt StrVal(numBits, 0);
11051         APInt SingleChar(numBits, 0);
11052         if (TD->isLittleEndian()) {
11053           for (signed i = len-1; i >= 0; i--) {
11054             SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11055             StrVal = (StrVal << 8) | SingleChar;
11056           }
11057         } else {
11058           for (unsigned i = 0; i < len; i++) {
11059             SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11060             StrVal = (StrVal << 8) | SingleChar;
11061           }
11062           // Append NULL at the end.
11063           SingleChar = 0;
11064           StrVal = (StrVal << 8) | SingleChar;
11065         }
11066         Value *NL = ConstantInt::get(StrVal);
11067         return IC.ReplaceInstUsesWith(LI, NL);
11068       }
11069     }
11070   }
11071
11072   const PointerType *DestTy = cast<PointerType>(CI->getType());
11073   const Type *DestPTy = DestTy->getElementType();
11074   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11075
11076     // If the address spaces don't match, don't eliminate the cast.
11077     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11078       return 0;
11079
11080     const Type *SrcPTy = SrcTy->getElementType();
11081
11082     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11083          isa<VectorType>(DestPTy)) {
11084       // If the source is an array, the code below will not succeed.  Check to
11085       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11086       // constants.
11087       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11088         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11089           if (ASrcTy->getNumElements() != 0) {
11090             Value *Idxs[2];
11091             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11092             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11093             SrcTy = cast<PointerType>(CastOp->getType());
11094             SrcPTy = SrcTy->getElementType();
11095           }
11096
11097       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11098             isa<VectorType>(SrcPTy)) &&
11099           // Do not allow turning this into a load of an integer, which is then
11100           // casted to a pointer, this pessimizes pointer analysis a lot.
11101           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11102           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11103                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11104
11105         // Okay, we are casting from one integer or pointer type to another of
11106         // the same size.  Instead of casting the pointer before the load, cast
11107         // the result of the loaded value.
11108         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11109                                                              CI->getName(),
11110                                                          LI.isVolatile()),LI);
11111         // Now cast the result of the load.
11112         return new BitCastInst(NewLoad, LI.getType());
11113       }
11114     }
11115   }
11116   return 0;
11117 }
11118
11119 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
11120 /// from this value cannot trap.  If it is not obviously safe to load from the
11121 /// specified pointer, we do a quick local scan of the basic block containing
11122 /// ScanFrom, to determine if the address is already accessed.
11123 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
11124   // If it is an alloca it is always safe to load from.
11125   if (isa<AllocaInst>(V)) return true;
11126
11127   // If it is a global variable it is mostly safe to load from.
11128   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
11129     // Don't try to evaluate aliases.  External weak GV can be null.
11130     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
11131
11132   // Otherwise, be a little bit agressive by scanning the local block where we
11133   // want to check to see if the pointer is already being loaded or stored
11134   // from/to.  If so, the previous load or store would have already trapped,
11135   // so there is no harm doing an extra load (also, CSE will later eliminate
11136   // the load entirely).
11137   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11138
11139   while (BBI != E) {
11140     --BBI;
11141
11142     // If we see a free or a call (which might do a free) the pointer could be
11143     // marked invalid.
11144     if (isa<FreeInst>(BBI) || 
11145         (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)))
11146       return false;
11147     
11148     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11149       if (LI->getOperand(0) == V) return true;
11150     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
11151       if (SI->getOperand(1) == V) return true;
11152     }
11153
11154   }
11155   return false;
11156 }
11157
11158 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11159   Value *Op = LI.getOperand(0);
11160
11161   // Attempt to improve the alignment.
11162   unsigned KnownAlign =
11163     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11164   if (KnownAlign >
11165       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11166                                 LI.getAlignment()))
11167     LI.setAlignment(KnownAlign);
11168
11169   // load (cast X) --> cast (load X) iff safe
11170   if (isa<CastInst>(Op))
11171     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11172       return Res;
11173
11174   // None of the following transforms are legal for volatile loads.
11175   if (LI.isVolatile()) return 0;
11176   
11177   // Do really simple store-to-load forwarding and load CSE, to catch cases
11178   // where there are several consequtive memory accesses to the same location,
11179   // separated by a few arithmetic operations.
11180   BasicBlock::iterator BBI = &LI;
11181   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11182     return ReplaceInstUsesWith(LI, AvailableVal);
11183
11184   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11185     const Value *GEPI0 = GEPI->getOperand(0);
11186     // TODO: Consider a target hook for valid address spaces for this xform.
11187     if (isa<ConstantPointerNull>(GEPI0) &&
11188         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11189       // Insert a new store to null instruction before the load to indicate
11190       // that this code is not reachable.  We do this instead of inserting
11191       // an unreachable instruction directly because we cannot modify the
11192       // CFG.
11193       new StoreInst(UndefValue::get(LI.getType()),
11194                     Constant::getNullValue(Op->getType()), &LI);
11195       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11196     }
11197   } 
11198
11199   if (Constant *C = dyn_cast<Constant>(Op)) {
11200     // load null/undef -> undef
11201     // TODO: Consider a target hook for valid address spaces for this xform.
11202     if (isa<UndefValue>(C) || (C->isNullValue() && 
11203         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11204       // Insert a new store to null instruction before the load to indicate that
11205       // this code is not reachable.  We do this instead of inserting an
11206       // unreachable instruction directly because we cannot modify the CFG.
11207       new StoreInst(UndefValue::get(LI.getType()),
11208                     Constant::getNullValue(Op->getType()), &LI);
11209       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11210     }
11211
11212     // Instcombine load (constant global) into the value loaded.
11213     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11214       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11215         return ReplaceInstUsesWith(LI, GV->getInitializer());
11216
11217     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11218     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11219       if (CE->getOpcode() == Instruction::GetElementPtr) {
11220         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11221           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11222             if (Constant *V = 
11223                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11224               return ReplaceInstUsesWith(LI, V);
11225         if (CE->getOperand(0)->isNullValue()) {
11226           // Insert a new store to null instruction before the load to indicate
11227           // that this code is not reachable.  We do this instead of inserting
11228           // an unreachable instruction directly because we cannot modify the
11229           // CFG.
11230           new StoreInst(UndefValue::get(LI.getType()),
11231                         Constant::getNullValue(Op->getType()), &LI);
11232           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11233         }
11234
11235       } else if (CE->isCast()) {
11236         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11237           return Res;
11238       }
11239     }
11240   }
11241     
11242   // If this load comes from anywhere in a constant global, and if the global
11243   // is all undef or zero, we know what it loads.
11244   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11245     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11246       if (GV->getInitializer()->isNullValue())
11247         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11248       else if (isa<UndefValue>(GV->getInitializer()))
11249         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11250     }
11251   }
11252
11253   if (Op->hasOneUse()) {
11254     // Change select and PHI nodes to select values instead of addresses: this
11255     // helps alias analysis out a lot, allows many others simplifications, and
11256     // exposes redundancy in the code.
11257     //
11258     // Note that we cannot do the transformation unless we know that the
11259     // introduced loads cannot trap!  Something like this is valid as long as
11260     // the condition is always false: load (select bool %C, int* null, int* %G),
11261     // but it would not be valid if we transformed it to load from null
11262     // unconditionally.
11263     //
11264     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11265       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11266       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11267           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11268         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11269                                      SI->getOperand(1)->getName()+".val"), LI);
11270         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11271                                      SI->getOperand(2)->getName()+".val"), LI);
11272         return SelectInst::Create(SI->getCondition(), V1, V2);
11273       }
11274
11275       // load (select (cond, null, P)) -> load P
11276       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11277         if (C->isNullValue()) {
11278           LI.setOperand(0, SI->getOperand(2));
11279           return &LI;
11280         }
11281
11282       // load (select (cond, P, null)) -> load P
11283       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11284         if (C->isNullValue()) {
11285           LI.setOperand(0, SI->getOperand(1));
11286           return &LI;
11287         }
11288     }
11289   }
11290   return 0;
11291 }
11292
11293 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11294 /// when possible.  This makes it generally easy to do alias analysis and/or
11295 /// SROA/mem2reg of the memory object.
11296 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11297   User *CI = cast<User>(SI.getOperand(1));
11298   Value *CastOp = CI->getOperand(0);
11299
11300   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11301   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11302   if (SrcTy == 0) return 0;
11303   
11304   const Type *SrcPTy = SrcTy->getElementType();
11305
11306   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11307     return 0;
11308   
11309   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11310   /// to its first element.  This allows us to handle things like:
11311   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11312   /// on 32-bit hosts.
11313   SmallVector<Value*, 4> NewGEPIndices;
11314   
11315   // If the source is an array, the code below will not succeed.  Check to
11316   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11317   // constants.
11318   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11319     // Index through pointer.
11320     Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11321     NewGEPIndices.push_back(Zero);
11322     
11323     while (1) {
11324       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11325         if (!STy->getNumElements()) /* Struct can be empty {} */
11326           break;
11327         NewGEPIndices.push_back(Zero);
11328         SrcPTy = STy->getElementType(0);
11329       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11330         NewGEPIndices.push_back(Zero);
11331         SrcPTy = ATy->getElementType();
11332       } else {
11333         break;
11334       }
11335     }
11336     
11337     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11338   }
11339
11340   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11341     return 0;
11342   
11343   // If the pointers point into different address spaces or if they point to
11344   // values with different sizes, we can't do the transformation.
11345   if (SrcTy->getAddressSpace() != 
11346         cast<PointerType>(CI->getType())->getAddressSpace() ||
11347       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11348       IC.getTargetData().getTypeSizeInBits(DestPTy))
11349     return 0;
11350
11351   // Okay, we are casting from one integer or pointer type to another of
11352   // the same size.  Instead of casting the pointer before 
11353   // the store, cast the value to be stored.
11354   Value *NewCast;
11355   Value *SIOp0 = SI.getOperand(0);
11356   Instruction::CastOps opcode = Instruction::BitCast;
11357   const Type* CastSrcTy = SIOp0->getType();
11358   const Type* CastDstTy = SrcPTy;
11359   if (isa<PointerType>(CastDstTy)) {
11360     if (CastSrcTy->isInteger())
11361       opcode = Instruction::IntToPtr;
11362   } else if (isa<IntegerType>(CastDstTy)) {
11363     if (isa<PointerType>(SIOp0->getType()))
11364       opcode = Instruction::PtrToInt;
11365   }
11366   
11367   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11368   // emit a GEP to index into its first field.
11369   if (!NewGEPIndices.empty()) {
11370     if (Constant *C = dyn_cast<Constant>(CastOp))
11371       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11372                                               NewGEPIndices.size());
11373     else
11374       CastOp = IC.InsertNewInstBefore(
11375               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11376                                         NewGEPIndices.end()), SI);
11377   }
11378   
11379   if (Constant *C = dyn_cast<Constant>(SIOp0))
11380     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11381   else
11382     NewCast = IC.InsertNewInstBefore(
11383       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11384       SI);
11385   return new StoreInst(NewCast, CastOp);
11386 }
11387
11388 /// equivalentAddressValues - Test if A and B will obviously have the same
11389 /// value. This includes recognizing that %t0 and %t1 will have the same
11390 /// value in code like this:
11391 ///   %t0 = getelementptr \@a, 0, 3
11392 ///   store i32 0, i32* %t0
11393 ///   %t1 = getelementptr \@a, 0, 3
11394 ///   %t2 = load i32* %t1
11395 ///
11396 static bool equivalentAddressValues(Value *A, Value *B) {
11397   // Test if the values are trivially equivalent.
11398   if (A == B) return true;
11399   
11400   // Test if the values come form identical arithmetic instructions.
11401   if (isa<BinaryOperator>(A) ||
11402       isa<CastInst>(A) ||
11403       isa<PHINode>(A) ||
11404       isa<GetElementPtrInst>(A))
11405     if (Instruction *BI = dyn_cast<Instruction>(B))
11406       if (cast<Instruction>(A)->isIdenticalTo(BI))
11407         return true;
11408   
11409   // Otherwise they may not be equivalent.
11410   return false;
11411 }
11412
11413 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11414 // return the llvm.dbg.declare.
11415 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11416   if (!V->hasNUses(2))
11417     return 0;
11418   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11419        UI != E; ++UI) {
11420     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11421       return DI;
11422     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11423       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11424         return DI;
11425       }
11426   }
11427   return 0;
11428 }
11429
11430 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11431   Value *Val = SI.getOperand(0);
11432   Value *Ptr = SI.getOperand(1);
11433
11434   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11435     EraseInstFromFunction(SI);
11436     ++NumCombined;
11437     return 0;
11438   }
11439   
11440   // If the RHS is an alloca with a single use, zapify the store, making the
11441   // alloca dead.
11442   // If the RHS is an alloca with a two uses, the other one being a 
11443   // llvm.dbg.declare, zapify the store and the declare, making the
11444   // alloca dead.  We must do this to prevent declare's from affecting
11445   // codegen.
11446   if (!SI.isVolatile()) {
11447     if (Ptr->hasOneUse()) {
11448       if (isa<AllocaInst>(Ptr)) {
11449         EraseInstFromFunction(SI);
11450         ++NumCombined;
11451         return 0;
11452       }
11453       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11454         if (isa<AllocaInst>(GEP->getOperand(0))) {
11455           if (GEP->getOperand(0)->hasOneUse()) {
11456             EraseInstFromFunction(SI);
11457             ++NumCombined;
11458             return 0;
11459           }
11460           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11461             EraseInstFromFunction(*DI);
11462             EraseInstFromFunction(SI);
11463             ++NumCombined;
11464             return 0;
11465           }
11466         }
11467       }
11468     }
11469     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11470       EraseInstFromFunction(*DI);
11471       EraseInstFromFunction(SI);
11472       ++NumCombined;
11473       return 0;
11474     }
11475   }
11476
11477   // Attempt to improve the alignment.
11478   unsigned KnownAlign =
11479     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11480   if (KnownAlign >
11481       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11482                                 SI.getAlignment()))
11483     SI.setAlignment(KnownAlign);
11484
11485   // Do really simple DSE, to catch cases where there are several consecutive
11486   // stores to the same location, separated by a few arithmetic operations. This
11487   // situation often occurs with bitfield accesses.
11488   BasicBlock::iterator BBI = &SI;
11489   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11490        --ScanInsts) {
11491     --BBI;
11492     // Don't count debug info directives, lest they affect codegen,
11493     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11494     // It is necessary for correctness to skip those that feed into a
11495     // llvm.dbg.declare, as these are not present when debugging is off.
11496     if (isa<DbgInfoIntrinsic>(BBI) ||
11497         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11498       ScanInsts++;
11499       continue;
11500     }    
11501     
11502     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11503       // Prev store isn't volatile, and stores to the same location?
11504       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11505                                                           SI.getOperand(1))) {
11506         ++NumDeadStore;
11507         ++BBI;
11508         EraseInstFromFunction(*PrevSI);
11509         continue;
11510       }
11511       break;
11512     }
11513     
11514     // If this is a load, we have to stop.  However, if the loaded value is from
11515     // the pointer we're loading and is producing the pointer we're storing,
11516     // then *this* store is dead (X = load P; store X -> P).
11517     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11518       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11519           !SI.isVolatile()) {
11520         EraseInstFromFunction(SI);
11521         ++NumCombined;
11522         return 0;
11523       }
11524       // Otherwise, this is a load from some other location.  Stores before it
11525       // may not be dead.
11526       break;
11527     }
11528     
11529     // Don't skip over loads or things that can modify memory.
11530     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11531       break;
11532   }
11533   
11534   
11535   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11536
11537   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11538   if (isa<ConstantPointerNull>(Ptr)) {
11539     if (!isa<UndefValue>(Val)) {
11540       SI.setOperand(0, UndefValue::get(Val->getType()));
11541       if (Instruction *U = dyn_cast<Instruction>(Val))
11542         AddToWorkList(U);  // Dropped a use.
11543       ++NumCombined;
11544     }
11545     return 0;  // Do not modify these!
11546   }
11547
11548   // store undef, Ptr -> noop
11549   if (isa<UndefValue>(Val)) {
11550     EraseInstFromFunction(SI);
11551     ++NumCombined;
11552     return 0;
11553   }
11554
11555   // If the pointer destination is a cast, see if we can fold the cast into the
11556   // source instead.
11557   if (isa<CastInst>(Ptr))
11558     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11559       return Res;
11560   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11561     if (CE->isCast())
11562       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11563         return Res;
11564
11565   
11566   // If this store is the last instruction in the basic block (possibly
11567   // excepting debug info instructions and the pointer bitcasts that feed
11568   // into them), and if the block ends with an unconditional branch, try
11569   // to move it to the successor block.
11570   BBI = &SI; 
11571   do {
11572     ++BBI;
11573   } while (isa<DbgInfoIntrinsic>(BBI) ||
11574            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11575   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11576     if (BI->isUnconditional())
11577       if (SimplifyStoreAtEndOfBlock(SI))
11578         return 0;  // xform done!
11579   
11580   return 0;
11581 }
11582
11583 /// SimplifyStoreAtEndOfBlock - Turn things like:
11584 ///   if () { *P = v1; } else { *P = v2 }
11585 /// into a phi node with a store in the successor.
11586 ///
11587 /// Simplify things like:
11588 ///   *P = v1; if () { *P = v2; }
11589 /// into a phi node with a store in the successor.
11590 ///
11591 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11592   BasicBlock *StoreBB = SI.getParent();
11593   
11594   // Check to see if the successor block has exactly two incoming edges.  If
11595   // so, see if the other predecessor contains a store to the same location.
11596   // if so, insert a PHI node (if needed) and move the stores down.
11597   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11598   
11599   // Determine whether Dest has exactly two predecessors and, if so, compute
11600   // the other predecessor.
11601   pred_iterator PI = pred_begin(DestBB);
11602   BasicBlock *OtherBB = 0;
11603   if (*PI != StoreBB)
11604     OtherBB = *PI;
11605   ++PI;
11606   if (PI == pred_end(DestBB))
11607     return false;
11608   
11609   if (*PI != StoreBB) {
11610     if (OtherBB)
11611       return false;
11612     OtherBB = *PI;
11613   }
11614   if (++PI != pred_end(DestBB))
11615     return false;
11616
11617   // Bail out if all the relevant blocks aren't distinct (this can happen,
11618   // for example, if SI is in an infinite loop)
11619   if (StoreBB == DestBB || OtherBB == DestBB)
11620     return false;
11621
11622   // Verify that the other block ends in a branch and is not otherwise empty.
11623   BasicBlock::iterator BBI = OtherBB->getTerminator();
11624   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11625   if (!OtherBr || BBI == OtherBB->begin())
11626     return false;
11627   
11628   // If the other block ends in an unconditional branch, check for the 'if then
11629   // else' case.  there is an instruction before the branch.
11630   StoreInst *OtherStore = 0;
11631   if (OtherBr->isUnconditional()) {
11632     --BBI;
11633     // Skip over debugging info.
11634     while (isa<DbgInfoIntrinsic>(BBI) ||
11635            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11636       if (BBI==OtherBB->begin())
11637         return false;
11638       --BBI;
11639     }
11640     // If this isn't a store, or isn't a store to the same location, bail out.
11641     OtherStore = dyn_cast<StoreInst>(BBI);
11642     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11643       return false;
11644   } else {
11645     // Otherwise, the other block ended with a conditional branch. If one of the
11646     // destinations is StoreBB, then we have the if/then case.
11647     if (OtherBr->getSuccessor(0) != StoreBB && 
11648         OtherBr->getSuccessor(1) != StoreBB)
11649       return false;
11650     
11651     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11652     // if/then triangle.  See if there is a store to the same ptr as SI that
11653     // lives in OtherBB.
11654     for (;; --BBI) {
11655       // Check to see if we find the matching store.
11656       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11657         if (OtherStore->getOperand(1) != SI.getOperand(1))
11658           return false;
11659         break;
11660       }
11661       // If we find something that may be using or overwriting the stored
11662       // value, or if we run out of instructions, we can't do the xform.
11663       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11664           BBI == OtherBB->begin())
11665         return false;
11666     }
11667     
11668     // In order to eliminate the store in OtherBr, we have to
11669     // make sure nothing reads or overwrites the stored value in
11670     // StoreBB.
11671     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11672       // FIXME: This should really be AA driven.
11673       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11674         return false;
11675     }
11676   }
11677   
11678   // Insert a PHI node now if we need it.
11679   Value *MergedVal = OtherStore->getOperand(0);
11680   if (MergedVal != SI.getOperand(0)) {
11681     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11682     PN->reserveOperandSpace(2);
11683     PN->addIncoming(SI.getOperand(0), SI.getParent());
11684     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11685     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11686   }
11687   
11688   // Advance to a place where it is safe to insert the new store and
11689   // insert it.
11690   BBI = DestBB->getFirstNonPHI();
11691   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11692                                     OtherStore->isVolatile()), *BBI);
11693   
11694   // Nuke the old stores.
11695   EraseInstFromFunction(SI);
11696   EraseInstFromFunction(*OtherStore);
11697   ++NumCombined;
11698   return true;
11699 }
11700
11701
11702 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11703   // Change br (not X), label True, label False to: br X, label False, True
11704   Value *X = 0;
11705   BasicBlock *TrueDest;
11706   BasicBlock *FalseDest;
11707   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11708       !isa<Constant>(X)) {
11709     // Swap Destinations and condition...
11710     BI.setCondition(X);
11711     BI.setSuccessor(0, FalseDest);
11712     BI.setSuccessor(1, TrueDest);
11713     return &BI;
11714   }
11715
11716   // Cannonicalize fcmp_one -> fcmp_oeq
11717   FCmpInst::Predicate FPred; Value *Y;
11718   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11719                              TrueDest, FalseDest)))
11720     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11721          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11722       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11723       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11724       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11725       NewSCC->takeName(I);
11726       // Swap Destinations and condition...
11727       BI.setCondition(NewSCC);
11728       BI.setSuccessor(0, FalseDest);
11729       BI.setSuccessor(1, TrueDest);
11730       RemoveFromWorkList(I);
11731       I->eraseFromParent();
11732       AddToWorkList(NewSCC);
11733       return &BI;
11734     }
11735
11736   // Cannonicalize icmp_ne -> icmp_eq
11737   ICmpInst::Predicate IPred;
11738   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11739                       TrueDest, FalseDest)))
11740     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11741          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11742          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11743       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11744       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11745       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11746       NewSCC->takeName(I);
11747       // Swap Destinations and condition...
11748       BI.setCondition(NewSCC);
11749       BI.setSuccessor(0, FalseDest);
11750       BI.setSuccessor(1, TrueDest);
11751       RemoveFromWorkList(I);
11752       I->eraseFromParent();;
11753       AddToWorkList(NewSCC);
11754       return &BI;
11755     }
11756
11757   return 0;
11758 }
11759
11760 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11761   Value *Cond = SI.getCondition();
11762   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11763     if (I->getOpcode() == Instruction::Add)
11764       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11765         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11766         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11767           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11768                                                 AddRHS));
11769         SI.setOperand(0, I->getOperand(0));
11770         AddToWorkList(I);
11771         return &SI;
11772       }
11773   }
11774   return 0;
11775 }
11776
11777 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11778   Value *Agg = EV.getAggregateOperand();
11779
11780   if (!EV.hasIndices())
11781     return ReplaceInstUsesWith(EV, Agg);
11782
11783   if (Constant *C = dyn_cast<Constant>(Agg)) {
11784     if (isa<UndefValue>(C))
11785       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11786       
11787     if (isa<ConstantAggregateZero>(C))
11788       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11789
11790     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11791       // Extract the element indexed by the first index out of the constant
11792       Value *V = C->getOperand(*EV.idx_begin());
11793       if (EV.getNumIndices() > 1)
11794         // Extract the remaining indices out of the constant indexed by the
11795         // first index
11796         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11797       else
11798         return ReplaceInstUsesWith(EV, V);
11799     }
11800     return 0; // Can't handle other constants
11801   } 
11802   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11803     // We're extracting from an insertvalue instruction, compare the indices
11804     const unsigned *exti, *exte, *insi, *inse;
11805     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11806          exte = EV.idx_end(), inse = IV->idx_end();
11807          exti != exte && insi != inse;
11808          ++exti, ++insi) {
11809       if (*insi != *exti)
11810         // The insert and extract both reference distinctly different elements.
11811         // This means the extract is not influenced by the insert, and we can
11812         // replace the aggregate operand of the extract with the aggregate
11813         // operand of the insert. i.e., replace
11814         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11815         // %E = extractvalue { i32, { i32 } } %I, 0
11816         // with
11817         // %E = extractvalue { i32, { i32 } } %A, 0
11818         return ExtractValueInst::Create(IV->getAggregateOperand(),
11819                                         EV.idx_begin(), EV.idx_end());
11820     }
11821     if (exti == exte && insi == inse)
11822       // Both iterators are at the end: Index lists are identical. Replace
11823       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11824       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11825       // with "i32 42"
11826       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11827     if (exti == exte) {
11828       // The extract list is a prefix of the insert list. i.e. replace
11829       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11830       // %E = extractvalue { i32, { i32 } } %I, 1
11831       // with
11832       // %X = extractvalue { i32, { i32 } } %A, 1
11833       // %E = insertvalue { i32 } %X, i32 42, 0
11834       // by switching the order of the insert and extract (though the
11835       // insertvalue should be left in, since it may have other uses).
11836       Value *NewEV = InsertNewInstBefore(
11837         ExtractValueInst::Create(IV->getAggregateOperand(),
11838                                  EV.idx_begin(), EV.idx_end()),
11839         EV);
11840       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11841                                      insi, inse);
11842     }
11843     if (insi == inse)
11844       // The insert list is a prefix of the extract list
11845       // We can simply remove the common indices from the extract and make it
11846       // operate on the inserted value instead of the insertvalue result.
11847       // i.e., replace
11848       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11849       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11850       // with
11851       // %E extractvalue { i32 } { i32 42 }, 0
11852       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11853                                       exti, exte);
11854   }
11855   // Can't simplify extracts from other values. Note that nested extracts are
11856   // already simplified implicitely by the above (extract ( extract (insert) )
11857   // will be translated into extract ( insert ( extract ) ) first and then just
11858   // the value inserted, if appropriate).
11859   return 0;
11860 }
11861
11862 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11863 /// is to leave as a vector operation.
11864 static bool CheapToScalarize(Value *V, bool isConstant) {
11865   if (isa<ConstantAggregateZero>(V)) 
11866     return true;
11867   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11868     if (isConstant) return true;
11869     // If all elts are the same, we can extract.
11870     Constant *Op0 = C->getOperand(0);
11871     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11872       if (C->getOperand(i) != Op0)
11873         return false;
11874     return true;
11875   }
11876   Instruction *I = dyn_cast<Instruction>(V);
11877   if (!I) return false;
11878   
11879   // Insert element gets simplified to the inserted element or is deleted if
11880   // this is constant idx extract element and its a constant idx insertelt.
11881   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11882       isa<ConstantInt>(I->getOperand(2)))
11883     return true;
11884   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11885     return true;
11886   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11887     if (BO->hasOneUse() &&
11888         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11889          CheapToScalarize(BO->getOperand(1), isConstant)))
11890       return true;
11891   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11892     if (CI->hasOneUse() &&
11893         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11894          CheapToScalarize(CI->getOperand(1), isConstant)))
11895       return true;
11896   
11897   return false;
11898 }
11899
11900 /// Read and decode a shufflevector mask.
11901 ///
11902 /// It turns undef elements into values that are larger than the number of
11903 /// elements in the input.
11904 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11905   unsigned NElts = SVI->getType()->getNumElements();
11906   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11907     return std::vector<unsigned>(NElts, 0);
11908   if (isa<UndefValue>(SVI->getOperand(2)))
11909     return std::vector<unsigned>(NElts, 2*NElts);
11910
11911   std::vector<unsigned> Result;
11912   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11913   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11914     if (isa<UndefValue>(*i))
11915       Result.push_back(NElts*2);  // undef -> 8
11916     else
11917       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
11918   return Result;
11919 }
11920
11921 /// FindScalarElement - Given a vector and an element number, see if the scalar
11922 /// value is already around as a register, for example if it were inserted then
11923 /// extracted from the vector.
11924 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11925   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11926   const VectorType *PTy = cast<VectorType>(V->getType());
11927   unsigned Width = PTy->getNumElements();
11928   if (EltNo >= Width)  // Out of range access.
11929     return UndefValue::get(PTy->getElementType());
11930   
11931   if (isa<UndefValue>(V))
11932     return UndefValue::get(PTy->getElementType());
11933   else if (isa<ConstantAggregateZero>(V))
11934     return Constant::getNullValue(PTy->getElementType());
11935   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11936     return CP->getOperand(EltNo);
11937   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11938     // If this is an insert to a variable element, we don't know what it is.
11939     if (!isa<ConstantInt>(III->getOperand(2))) 
11940       return 0;
11941     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11942     
11943     // If this is an insert to the element we are looking for, return the
11944     // inserted value.
11945     if (EltNo == IIElt) 
11946       return III->getOperand(1);
11947     
11948     // Otherwise, the insertelement doesn't modify the value, recurse on its
11949     // vector input.
11950     return FindScalarElement(III->getOperand(0), EltNo);
11951   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11952     unsigned LHSWidth =
11953       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11954     unsigned InEl = getShuffleMask(SVI)[EltNo];
11955     if (InEl < LHSWidth)
11956       return FindScalarElement(SVI->getOperand(0), InEl);
11957     else if (InEl < LHSWidth*2)
11958       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
11959     else
11960       return UndefValue::get(PTy->getElementType());
11961   }
11962   
11963   // Otherwise, we don't know.
11964   return 0;
11965 }
11966
11967 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11968   // If vector val is undef, replace extract with scalar undef.
11969   if (isa<UndefValue>(EI.getOperand(0)))
11970     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11971
11972   // If vector val is constant 0, replace extract with scalar 0.
11973   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11974     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11975   
11976   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11977     // If vector val is constant with all elements the same, replace EI with
11978     // that element. When the elements are not identical, we cannot replace yet
11979     // (we do that below, but only when the index is constant).
11980     Constant *op0 = C->getOperand(0);
11981     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11982       if (C->getOperand(i) != op0) {
11983         op0 = 0; 
11984         break;
11985       }
11986     if (op0)
11987       return ReplaceInstUsesWith(EI, op0);
11988   }
11989   
11990   // If extracting a specified index from the vector, see if we can recursively
11991   // find a previously computed scalar that was inserted into the vector.
11992   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11993     unsigned IndexVal = IdxC->getZExtValue();
11994     unsigned VectorWidth = 
11995       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11996       
11997     // If this is extracting an invalid index, turn this into undef, to avoid
11998     // crashing the code below.
11999     if (IndexVal >= VectorWidth)
12000       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12001     
12002     // This instruction only demands the single element from the input vector.
12003     // If the input vector has a single use, simplify it based on this use
12004     // property.
12005     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12006       APInt UndefElts(VectorWidth, 0);
12007       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12008       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12009                                                 DemandedMask, UndefElts)) {
12010         EI.setOperand(0, V);
12011         return &EI;
12012       }
12013     }
12014     
12015     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
12016       return ReplaceInstUsesWith(EI, Elt);
12017     
12018     // If the this extractelement is directly using a bitcast from a vector of
12019     // the same number of elements, see if we can find the source element from
12020     // it.  In this case, we will end up needing to bitcast the scalars.
12021     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12022       if (const VectorType *VT = 
12023               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12024         if (VT->getNumElements() == VectorWidth)
12025           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12026             return new BitCastInst(Elt, EI.getType());
12027     }
12028   }
12029   
12030   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12031     if (I->hasOneUse()) {
12032       // Push extractelement into predecessor operation if legal and
12033       // profitable to do so
12034       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12035         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12036         if (CheapToScalarize(BO, isConstantElt)) {
12037           ExtractElementInst *newEI0 = 
12038             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12039                                    EI.getName()+".lhs");
12040           ExtractElementInst *newEI1 =
12041             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12042                                    EI.getName()+".rhs");
12043           InsertNewInstBefore(newEI0, EI);
12044           InsertNewInstBefore(newEI1, EI);
12045           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12046         }
12047       } else if (isa<LoadInst>(I)) {
12048         unsigned AS = 
12049           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12050         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12051                                          PointerType::get(EI.getType(), AS),EI);
12052         GetElementPtrInst *GEP =
12053           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12054         InsertNewInstBefore(GEP, EI);
12055         return new LoadInst(GEP);
12056       }
12057     }
12058     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12059       // Extracting the inserted element?
12060       if (IE->getOperand(2) == EI.getOperand(1))
12061         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12062       // If the inserted and extracted elements are constants, they must not
12063       // be the same value, extract from the pre-inserted value instead.
12064       if (isa<Constant>(IE->getOperand(2)) &&
12065           isa<Constant>(EI.getOperand(1))) {
12066         AddUsesToWorkList(EI);
12067         EI.setOperand(0, IE->getOperand(0));
12068         return &EI;
12069       }
12070     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12071       // If this is extracting an element from a shufflevector, figure out where
12072       // it came from and extract from the appropriate input element instead.
12073       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12074         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12075         Value *Src;
12076         unsigned LHSWidth =
12077           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12078
12079         if (SrcIdx < LHSWidth)
12080           Src = SVI->getOperand(0);
12081         else if (SrcIdx < LHSWidth*2) {
12082           SrcIdx -= LHSWidth;
12083           Src = SVI->getOperand(1);
12084         } else {
12085           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12086         }
12087         return new ExtractElementInst(Src, SrcIdx);
12088       }
12089     }
12090   }
12091   return 0;
12092 }
12093
12094 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12095 /// elements from either LHS or RHS, return the shuffle mask and true. 
12096 /// Otherwise, return false.
12097 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12098                                          std::vector<Constant*> &Mask) {
12099   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12100          "Invalid CollectSingleShuffleElements");
12101   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12102
12103   if (isa<UndefValue>(V)) {
12104     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12105     return true;
12106   } else if (V == LHS) {
12107     for (unsigned i = 0; i != NumElts; ++i)
12108       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12109     return true;
12110   } else if (V == RHS) {
12111     for (unsigned i = 0; i != NumElts; ++i)
12112       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12113     return true;
12114   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12115     // If this is an insert of an extract from some other vector, include it.
12116     Value *VecOp    = IEI->getOperand(0);
12117     Value *ScalarOp = IEI->getOperand(1);
12118     Value *IdxOp    = IEI->getOperand(2);
12119     
12120     if (!isa<ConstantInt>(IdxOp))
12121       return false;
12122     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12123     
12124     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12125       // Okay, we can handle this if the vector we are insertinting into is
12126       // transitively ok.
12127       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12128         // If so, update the mask to reflect the inserted undef.
12129         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12130         return true;
12131       }      
12132     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12133       if (isa<ConstantInt>(EI->getOperand(1)) &&
12134           EI->getOperand(0)->getType() == V->getType()) {
12135         unsigned ExtractedIdx =
12136           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12137         
12138         // This must be extracting from either LHS or RHS.
12139         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12140           // Okay, we can handle this if the vector we are insertinting into is
12141           // transitively ok.
12142           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12143             // If so, update the mask to reflect the inserted value.
12144             if (EI->getOperand(0) == LHS) {
12145               Mask[InsertedIdx % NumElts] = 
12146                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12147             } else {
12148               assert(EI->getOperand(0) == RHS);
12149               Mask[InsertedIdx % NumElts] = 
12150                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12151               
12152             }
12153             return true;
12154           }
12155         }
12156       }
12157     }
12158   }
12159   // TODO: Handle shufflevector here!
12160   
12161   return false;
12162 }
12163
12164 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12165 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12166 /// that computes V and the LHS value of the shuffle.
12167 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12168                                      Value *&RHS) {
12169   assert(isa<VectorType>(V->getType()) && 
12170          (RHS == 0 || V->getType() == RHS->getType()) &&
12171          "Invalid shuffle!");
12172   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12173
12174   if (isa<UndefValue>(V)) {
12175     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12176     return V;
12177   } else if (isa<ConstantAggregateZero>(V)) {
12178     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12179     return V;
12180   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12181     // If this is an insert of an extract from some other vector, include it.
12182     Value *VecOp    = IEI->getOperand(0);
12183     Value *ScalarOp = IEI->getOperand(1);
12184     Value *IdxOp    = IEI->getOperand(2);
12185     
12186     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12187       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12188           EI->getOperand(0)->getType() == V->getType()) {
12189         unsigned ExtractedIdx =
12190           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12191         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12192         
12193         // Either the extracted from or inserted into vector must be RHSVec,
12194         // otherwise we'd end up with a shuffle of three inputs.
12195         if (EI->getOperand(0) == RHS || RHS == 0) {
12196           RHS = EI->getOperand(0);
12197           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
12198           Mask[InsertedIdx % NumElts] = 
12199             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12200           return V;
12201         }
12202         
12203         if (VecOp == RHS) {
12204           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
12205           // Everything but the extracted element is replaced with the RHS.
12206           for (unsigned i = 0; i != NumElts; ++i) {
12207             if (i != InsertedIdx)
12208               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12209           }
12210           return V;
12211         }
12212         
12213         // If this insertelement is a chain that comes from exactly these two
12214         // vectors, return the vector and the effective shuffle.
12215         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12216           return EI->getOperand(0);
12217         
12218       }
12219     }
12220   }
12221   // TODO: Handle shufflevector here!
12222   
12223   // Otherwise, can't do anything fancy.  Return an identity vector.
12224   for (unsigned i = 0; i != NumElts; ++i)
12225     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12226   return V;
12227 }
12228
12229 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12230   Value *VecOp    = IE.getOperand(0);
12231   Value *ScalarOp = IE.getOperand(1);
12232   Value *IdxOp    = IE.getOperand(2);
12233   
12234   // Inserting an undef or into an undefined place, remove this.
12235   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12236     ReplaceInstUsesWith(IE, VecOp);
12237   
12238   // If the inserted element was extracted from some other vector, and if the 
12239   // indexes are constant, try to turn this into a shufflevector operation.
12240   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12241     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12242         EI->getOperand(0)->getType() == IE.getType()) {
12243       unsigned NumVectorElts = IE.getType()->getNumElements();
12244       unsigned ExtractedIdx =
12245         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12246       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12247       
12248       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12249         return ReplaceInstUsesWith(IE, VecOp);
12250       
12251       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12252         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12253       
12254       // If we are extracting a value from a vector, then inserting it right
12255       // back into the same place, just use the input vector.
12256       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12257         return ReplaceInstUsesWith(IE, VecOp);      
12258       
12259       // We could theoretically do this for ANY input.  However, doing so could
12260       // turn chains of insertelement instructions into a chain of shufflevector
12261       // instructions, and right now we do not merge shufflevectors.  As such,
12262       // only do this in a situation where it is clear that there is benefit.
12263       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12264         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12265         // the values of VecOp, except then one read from EIOp0.
12266         // Build a new shuffle mask.
12267         std::vector<Constant*> Mask;
12268         if (isa<UndefValue>(VecOp))
12269           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12270         else {
12271           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12272           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12273                                                        NumVectorElts));
12274         } 
12275         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12276         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12277                                      ConstantVector::get(Mask));
12278       }
12279       
12280       // If this insertelement isn't used by some other insertelement, turn it
12281       // (and any insertelements it points to), into one big shuffle.
12282       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12283         std::vector<Constant*> Mask;
12284         Value *RHS = 0;
12285         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12286         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12287         // We now have a shuffle of LHS, RHS, Mask.
12288         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12289       }
12290     }
12291   }
12292
12293   return 0;
12294 }
12295
12296
12297 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12298   Value *LHS = SVI.getOperand(0);
12299   Value *RHS = SVI.getOperand(1);
12300   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12301
12302   bool MadeChange = false;
12303
12304   // Undefined shuffle mask -> undefined value.
12305   if (isa<UndefValue>(SVI.getOperand(2)))
12306     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12307
12308   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12309
12310   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12311     return 0;
12312
12313   APInt UndefElts(VWidth, 0);
12314   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12315   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12316     LHS = SVI.getOperand(0);
12317     RHS = SVI.getOperand(1);
12318     MadeChange = true;
12319   }
12320   
12321   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12322   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12323   if (LHS == RHS || isa<UndefValue>(LHS)) {
12324     if (isa<UndefValue>(LHS) && LHS == RHS) {
12325       // shuffle(undef,undef,mask) -> undef.
12326       return ReplaceInstUsesWith(SVI, LHS);
12327     }
12328     
12329     // Remap any references to RHS to use LHS.
12330     std::vector<Constant*> Elts;
12331     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12332       if (Mask[i] >= 2*e)
12333         Elts.push_back(UndefValue::get(Type::Int32Ty));
12334       else {
12335         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12336             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12337           Mask[i] = 2*e;     // Turn into undef.
12338           Elts.push_back(UndefValue::get(Type::Int32Ty));
12339         } else {
12340           Mask[i] = Mask[i] % e;  // Force to LHS.
12341           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12342         }
12343       }
12344     }
12345     SVI.setOperand(0, SVI.getOperand(1));
12346     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12347     SVI.setOperand(2, ConstantVector::get(Elts));
12348     LHS = SVI.getOperand(0);
12349     RHS = SVI.getOperand(1);
12350     MadeChange = true;
12351   }
12352   
12353   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12354   bool isLHSID = true, isRHSID = true;
12355     
12356   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12357     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12358     // Is this an identity shuffle of the LHS value?
12359     isLHSID &= (Mask[i] == i);
12360       
12361     // Is this an identity shuffle of the RHS value?
12362     isRHSID &= (Mask[i]-e == i);
12363   }
12364
12365   // Eliminate identity shuffles.
12366   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12367   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12368   
12369   // If the LHS is a shufflevector itself, see if we can combine it with this
12370   // one without producing an unusual shuffle.  Here we are really conservative:
12371   // we are absolutely afraid of producing a shuffle mask not in the input
12372   // program, because the code gen may not be smart enough to turn a merged
12373   // shuffle into two specific shuffles: it may produce worse code.  As such,
12374   // we only merge two shuffles if the result is one of the two input shuffle
12375   // masks.  In this case, merging the shuffles just removes one instruction,
12376   // which we know is safe.  This is good for things like turning:
12377   // (splat(splat)) -> splat.
12378   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12379     if (isa<UndefValue>(RHS)) {
12380       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12381
12382       std::vector<unsigned> NewMask;
12383       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12384         if (Mask[i] >= 2*e)
12385           NewMask.push_back(2*e);
12386         else
12387           NewMask.push_back(LHSMask[Mask[i]]);
12388       
12389       // If the result mask is equal to the src shuffle or this shuffle mask, do
12390       // the replacement.
12391       if (NewMask == LHSMask || NewMask == Mask) {
12392         unsigned LHSInNElts =
12393           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12394         std::vector<Constant*> Elts;
12395         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12396           if (NewMask[i] >= LHSInNElts*2) {
12397             Elts.push_back(UndefValue::get(Type::Int32Ty));
12398           } else {
12399             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12400           }
12401         }
12402         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12403                                      LHSSVI->getOperand(1),
12404                                      ConstantVector::get(Elts));
12405       }
12406     }
12407   }
12408
12409   return MadeChange ? &SVI : 0;
12410 }
12411
12412
12413
12414
12415 /// TryToSinkInstruction - Try to move the specified instruction from its
12416 /// current block into the beginning of DestBlock, which can only happen if it's
12417 /// safe to move the instruction past all of the instructions between it and the
12418 /// end of its block.
12419 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12420   assert(I->hasOneUse() && "Invariants didn't hold!");
12421
12422   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12423   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12424     return false;
12425
12426   // Do not sink alloca instructions out of the entry block.
12427   if (isa<AllocaInst>(I) && I->getParent() ==
12428         &DestBlock->getParent()->getEntryBlock())
12429     return false;
12430
12431   // We can only sink load instructions if there is nothing between the load and
12432   // the end of block that could change the value.
12433   if (I->mayReadFromMemory()) {
12434     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12435          Scan != E; ++Scan)
12436       if (Scan->mayWriteToMemory())
12437         return false;
12438   }
12439
12440   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12441
12442   CopyPrecedingStopPoint(I, InsertPos);
12443   I->moveBefore(InsertPos);
12444   ++NumSunkInst;
12445   return true;
12446 }
12447
12448
12449 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12450 /// all reachable code to the worklist.
12451 ///
12452 /// This has a couple of tricks to make the code faster and more powerful.  In
12453 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12454 /// them to the worklist (this significantly speeds up instcombine on code where
12455 /// many instructions are dead or constant).  Additionally, if we find a branch
12456 /// whose condition is a known constant, we only visit the reachable successors.
12457 ///
12458 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12459                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12460                                        InstCombiner &IC,
12461                                        const TargetData *TD) {
12462   SmallVector<BasicBlock*, 256> Worklist;
12463   Worklist.push_back(BB);
12464
12465   while (!Worklist.empty()) {
12466     BB = Worklist.back();
12467     Worklist.pop_back();
12468     
12469     // We have now visited this block!  If we've already been here, ignore it.
12470     if (!Visited.insert(BB)) continue;
12471
12472     DbgInfoIntrinsic *DBI_Prev = NULL;
12473     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12474       Instruction *Inst = BBI++;
12475       
12476       // DCE instruction if trivially dead.
12477       if (isInstructionTriviallyDead(Inst)) {
12478         ++NumDeadInst;
12479         DOUT << "IC: DCE: " << *Inst;
12480         Inst->eraseFromParent();
12481         continue;
12482       }
12483       
12484       // ConstantProp instruction if trivially constant.
12485       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12486         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12487         Inst->replaceAllUsesWith(C);
12488         ++NumConstProp;
12489         Inst->eraseFromParent();
12490         continue;
12491       }
12492      
12493       // If there are two consecutive llvm.dbg.stoppoint calls then
12494       // it is likely that the optimizer deleted code in between these
12495       // two intrinsics. 
12496       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12497       if (DBI_Next) {
12498         if (DBI_Prev
12499             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12500             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12501           IC.RemoveFromWorkList(DBI_Prev);
12502           DBI_Prev->eraseFromParent();
12503         }
12504         DBI_Prev = DBI_Next;
12505       } else {
12506         DBI_Prev = 0;
12507       }
12508
12509       IC.AddToWorkList(Inst);
12510     }
12511
12512     // Recursively visit successors.  If this is a branch or switch on a
12513     // constant, only visit the reachable successor.
12514     TerminatorInst *TI = BB->getTerminator();
12515     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12516       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12517         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12518         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12519         Worklist.push_back(ReachableBB);
12520         continue;
12521       }
12522     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12523       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12524         // See if this is an explicit destination.
12525         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12526           if (SI->getCaseValue(i) == Cond) {
12527             BasicBlock *ReachableBB = SI->getSuccessor(i);
12528             Worklist.push_back(ReachableBB);
12529             continue;
12530           }
12531         
12532         // Otherwise it is the default destination.
12533         Worklist.push_back(SI->getSuccessor(0));
12534         continue;
12535       }
12536     }
12537     
12538     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12539       Worklist.push_back(TI->getSuccessor(i));
12540   }
12541 }
12542
12543 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12544   bool Changed = false;
12545   TD = &getAnalysis<TargetData>();
12546   
12547   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12548              << F.getNameStr() << "\n");
12549
12550   {
12551     // Do a depth-first traversal of the function, populate the worklist with
12552     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12553     // track of which blocks we visit.
12554     SmallPtrSet<BasicBlock*, 64> Visited;
12555     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12556
12557     // Do a quick scan over the function.  If we find any blocks that are
12558     // unreachable, remove any instructions inside of them.  This prevents
12559     // the instcombine code from having to deal with some bad special cases.
12560     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12561       if (!Visited.count(BB)) {
12562         Instruction *Term = BB->getTerminator();
12563         while (Term != BB->begin()) {   // Remove instrs bottom-up
12564           BasicBlock::iterator I = Term; --I;
12565
12566           DOUT << "IC: DCE: " << *I;
12567           // A debug intrinsic shouldn't force another iteration if we weren't
12568           // going to do one without it.
12569           if (!isa<DbgInfoIntrinsic>(I)) {
12570             ++NumDeadInst;
12571             Changed = true;
12572           }
12573           if (!I->use_empty())
12574             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12575           I->eraseFromParent();
12576         }
12577       }
12578   }
12579
12580   while (!Worklist.empty()) {
12581     Instruction *I = RemoveOneFromWorkList();
12582     if (I == 0) continue;  // skip null values.
12583
12584     // Check to see if we can DCE the instruction.
12585     if (isInstructionTriviallyDead(I)) {
12586       // Add operands to the worklist.
12587       if (I->getNumOperands() < 4)
12588         AddUsesToWorkList(*I);
12589       ++NumDeadInst;
12590
12591       DOUT << "IC: DCE: " << *I;
12592
12593       I->eraseFromParent();
12594       RemoveFromWorkList(I);
12595       Changed = true;
12596       continue;
12597     }
12598
12599     // Instruction isn't dead, see if we can constant propagate it.
12600     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12601       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12602
12603       // Add operands to the worklist.
12604       AddUsesToWorkList(*I);
12605       ReplaceInstUsesWith(*I, C);
12606
12607       ++NumConstProp;
12608       I->eraseFromParent();
12609       RemoveFromWorkList(I);
12610       Changed = true;
12611       continue;
12612     }
12613
12614     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12615       // See if we can constant fold its operands.
12616       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12617         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12618           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12619             if (NewC != CE) {
12620               i->set(NewC);
12621               Changed = true;
12622             }
12623     }
12624
12625     // See if we can trivially sink this instruction to a successor basic block.
12626     if (I->hasOneUse()) {
12627       BasicBlock *BB = I->getParent();
12628       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12629       if (UserParent != BB) {
12630         bool UserIsSuccessor = false;
12631         // See if the user is one of our successors.
12632         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12633           if (*SI == UserParent) {
12634             UserIsSuccessor = true;
12635             break;
12636           }
12637
12638         // If the user is one of our immediate successors, and if that successor
12639         // only has us as a predecessors (we'd have to split the critical edge
12640         // otherwise), we can keep going.
12641         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12642             next(pred_begin(UserParent)) == pred_end(UserParent))
12643           // Okay, the CFG is simple enough, try to sink this instruction.
12644           Changed |= TryToSinkInstruction(I, UserParent);
12645       }
12646     }
12647
12648     // Now that we have an instruction, try combining it to simplify it...
12649 #ifndef NDEBUG
12650     std::string OrigI;
12651 #endif
12652     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12653     if (Instruction *Result = visit(*I)) {
12654       ++NumCombined;
12655       // Should we replace the old instruction with a new one?
12656       if (Result != I) {
12657         DOUT << "IC: Old = " << *I
12658              << "    New = " << *Result;
12659
12660         // Everything uses the new instruction now.
12661         I->replaceAllUsesWith(Result);
12662
12663         // Push the new instruction and any users onto the worklist.
12664         AddToWorkList(Result);
12665         AddUsersToWorkList(*Result);
12666
12667         // Move the name to the new instruction first.
12668         Result->takeName(I);
12669
12670         // Insert the new instruction into the basic block...
12671         BasicBlock *InstParent = I->getParent();
12672         BasicBlock::iterator InsertPos = I;
12673
12674         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12675           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12676             ++InsertPos;
12677
12678         InstParent->getInstList().insert(InsertPos, Result);
12679
12680         // Make sure that we reprocess all operands now that we reduced their
12681         // use counts.
12682         AddUsesToWorkList(*I);
12683
12684         // Instructions can end up on the worklist more than once.  Make sure
12685         // we do not process an instruction that has been deleted.
12686         RemoveFromWorkList(I);
12687
12688         // Erase the old instruction.
12689         InstParent->getInstList().erase(I);
12690       } else {
12691 #ifndef NDEBUG
12692         DOUT << "IC: Mod = " << OrigI
12693              << "    New = " << *I;
12694 #endif
12695
12696         // If the instruction was modified, it's possible that it is now dead.
12697         // if so, remove it.
12698         if (isInstructionTriviallyDead(I)) {
12699           // Make sure we process all operands now that we are reducing their
12700           // use counts.
12701           AddUsesToWorkList(*I);
12702
12703           // Instructions may end up in the worklist more than once.  Erase all
12704           // occurrences of this instruction.
12705           RemoveFromWorkList(I);
12706           I->eraseFromParent();
12707         } else {
12708           AddToWorkList(I);
12709           AddUsersToWorkList(*I);
12710         }
12711       }
12712       Changed = true;
12713     }
12714   }
12715
12716   assert(WorklistMap.empty() && "Worklist empty, but map not?");
12717     
12718   // Do an explicit clear, this shrinks the map if needed.
12719   WorklistMap.clear();
12720   return Changed;
12721 }
12722
12723
12724 bool InstCombiner::runOnFunction(Function &F) {
12725   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12726   
12727   bool EverMadeChange = false;
12728
12729   // Iterate while there is work to do.
12730   unsigned Iteration = 0;
12731   while (DoOneIteration(F, Iteration++))
12732     EverMadeChange = true;
12733   return EverMadeChange;
12734 }
12735
12736 FunctionPass *llvm::createInstructionCombiningPass() {
12737   return new InstCombiner();
12738 }