Fix PR3874 by restoring a condition I removed, but making it more
[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(PtrToIntInst &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   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
478                                                 DstTy, TD->getIntPtrType());
479   
480   // We don't want to form an inttoptr or ptrtoint that converts to an integer
481   // type that differs from the pointer size.
482   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
483       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
484     Res = 0;
485   
486   return Instruction::CastOps(Res);
487 }
488
489 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
490 /// in any code being generated.  It does not require codegen if V is simple
491 /// enough or if the cast can be folded into other casts.
492 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
493                               const Type *Ty, TargetData *TD) {
494   if (V->getType() == Ty || isa<Constant>(V)) return false;
495   
496   // If this is another cast that can be eliminated, it isn't codegen either.
497   if (const CastInst *CI = dyn_cast<CastInst>(V))
498     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
499       return false;
500   return true;
501 }
502
503 // SimplifyCommutative - This performs a few simplifications for commutative
504 // operators:
505 //
506 //  1. Order operands such that they are listed from right (least complex) to
507 //     left (most complex).  This puts constants before unary operators before
508 //     binary operators.
509 //
510 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
511 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
512 //
513 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
514   bool Changed = false;
515   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
516     Changed = !I.swapOperands();
517
518   if (!I.isAssociative()) return Changed;
519   Instruction::BinaryOps Opcode = I.getOpcode();
520   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
521     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
522       if (isa<Constant>(I.getOperand(1))) {
523         Constant *Folded = ConstantExpr::get(I.getOpcode(),
524                                              cast<Constant>(I.getOperand(1)),
525                                              cast<Constant>(Op->getOperand(1)));
526         I.setOperand(0, Op->getOperand(0));
527         I.setOperand(1, Folded);
528         return true;
529       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
530         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
531             isOnlyUse(Op) && isOnlyUse(Op1)) {
532           Constant *C1 = cast<Constant>(Op->getOperand(1));
533           Constant *C2 = cast<Constant>(Op1->getOperand(1));
534
535           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
536           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
537           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
538                                                     Op1->getOperand(0),
539                                                     Op1->getName(), &I);
540           AddToWorkList(New);
541           I.setOperand(0, New);
542           I.setOperand(1, Folded);
543           return true;
544         }
545     }
546   return Changed;
547 }
548
549 /// SimplifyCompare - For a CmpInst this function just orders the operands
550 /// so that theyare listed from right (least complex) to left (most complex).
551 /// This puts constants before unary operators before binary operators.
552 bool InstCombiner::SimplifyCompare(CmpInst &I) {
553   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
554     return false;
555   I.swapOperands();
556   // Compare instructions are not associative so there's nothing else we can do.
557   return true;
558 }
559
560 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
561 // if the LHS is a constant zero (which is the 'negate' form).
562 //
563 static inline Value *dyn_castNegVal(Value *V) {
564   if (BinaryOperator::isNeg(V))
565     return BinaryOperator::getNegArgument(V);
566
567   // Constants can be considered to be negated values if they can be folded.
568   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
569     return ConstantExpr::getNeg(C);
570
571   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572     if (C->getType()->getElementType()->isInteger())
573       return ConstantExpr::getNeg(C);
574
575   return 0;
576 }
577
578 static inline Value *dyn_castNotVal(Value *V) {
579   if (BinaryOperator::isNot(V))
580     return BinaryOperator::getNotArgument(V);
581
582   // Constants can be considered to be not'ed values...
583   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
584     return ConstantInt::get(~C->getValue());
585   return 0;
586 }
587
588 // dyn_castFoldableMul - If this value is a multiply that can be folded into
589 // other computations (because it has a constant operand), return the
590 // non-constant operand of the multiply, and set CST to point to the multiplier.
591 // Otherwise, return null.
592 //
593 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
594   if (V->hasOneUse() && V->getType()->isInteger())
595     if (Instruction *I = dyn_cast<Instruction>(V)) {
596       if (I->getOpcode() == Instruction::Mul)
597         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
598           return I->getOperand(0);
599       if (I->getOpcode() == Instruction::Shl)
600         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
601           // The multiplier is really 1 << CST.
602           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
603           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
604           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
605           return I->getOperand(0);
606         }
607     }
608   return 0;
609 }
610
611 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
612 /// expression, return it.
613 static User *dyn_castGetElementPtr(Value *V) {
614   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
615   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
616     if (CE->getOpcode() == Instruction::GetElementPtr)
617       return cast<User>(V);
618   return false;
619 }
620
621 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
622 /// opcode value. Otherwise return UserOp1.
623 static unsigned getOpcode(const Value *V) {
624   if (const Instruction *I = dyn_cast<Instruction>(V))
625     return I->getOpcode();
626   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
627     return CE->getOpcode();
628   // Use UserOp1 to mean there's no opcode.
629   return Instruction::UserOp1;
630 }
631
632 /// AddOne - Add one to a ConstantInt
633 static ConstantInt *AddOne(ConstantInt *C) {
634   APInt Val(C->getValue());
635   return ConstantInt::get(++Val);
636 }
637 /// SubOne - Subtract one from a ConstantInt
638 static ConstantInt *SubOne(ConstantInt *C) {
639   APInt Val(C->getValue());
640   return ConstantInt::get(--Val);
641 }
642 /// Add - Add two ConstantInts together
643 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
644   return ConstantInt::get(C1->getValue() + C2->getValue());
645 }
646 /// And - Bitwise AND two ConstantInts together
647 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
648   return ConstantInt::get(C1->getValue() & C2->getValue());
649 }
650 /// Subtract - Subtract one ConstantInt from another
651 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
652   return ConstantInt::get(C1->getValue() - C2->getValue());
653 }
654 /// Multiply - Multiply two ConstantInts together
655 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
656   return ConstantInt::get(C1->getValue() * C2->getValue());
657 }
658 /// MultiplyOverflows - True if the multiply can not be expressed in an int
659 /// this size.
660 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
661   uint32_t W = C1->getBitWidth();
662   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
663   if (sign) {
664     LHSExt.sext(W * 2);
665     RHSExt.sext(W * 2);
666   } else {
667     LHSExt.zext(W * 2);
668     RHSExt.zext(W * 2);
669   }
670
671   APInt MulExt = LHSExt * RHSExt;
672
673   if (sign) {
674     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
675     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
676     return MulExt.slt(Min) || MulExt.sgt(Max);
677   } else 
678     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
679 }
680
681
682 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
683 /// specified instruction is a constant integer.  If so, check to see if there
684 /// are any bits set in the constant that are not demanded.  If so, shrink the
685 /// constant and return true.
686 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
687                                    APInt Demanded) {
688   assert(I && "No instruction?");
689   assert(OpNo < I->getNumOperands() && "Operand index too large");
690
691   // If the operand is not a constant integer, nothing to do.
692   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
693   if (!OpC) return false;
694
695   // If there are no bits set that aren't demanded, nothing to do.
696   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
697   if ((~Demanded & OpC->getValue()) == 0)
698     return false;
699
700   // This instruction is producing bits that are not demanded. Shrink the RHS.
701   Demanded &= OpC->getValue();
702   I->setOperand(OpNo, ConstantInt::get(Demanded));
703   return true;
704 }
705
706 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
707 // set of known zero and one bits, compute the maximum and minimum values that
708 // could have the specified known zero and known one bits, returning them in
709 // min/max.
710 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
711                                                    const APInt& KnownZero,
712                                                    const APInt& KnownOne,
713                                                    APInt& Min, APInt& Max) {
714   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
715   assert(KnownZero.getBitWidth() == BitWidth && 
716          KnownOne.getBitWidth() == BitWidth &&
717          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
718          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
719   APInt UnknownBits = ~(KnownZero|KnownOne);
720
721   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
722   // bit if it is unknown.
723   Min = KnownOne;
724   Max = KnownOne|UnknownBits;
725   
726   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
727     Min.set(BitWidth-1);
728     Max.clear(BitWidth-1);
729   }
730 }
731
732 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
733 // a set of known zero and one bits, compute the maximum and minimum values that
734 // could have the specified known zero and known one bits, returning them in
735 // min/max.
736 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
737                                                      const APInt &KnownZero,
738                                                      const APInt &KnownOne,
739                                                      APInt &Min, APInt &Max) {
740   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
741   assert(KnownZero.getBitWidth() == BitWidth && 
742          KnownOne.getBitWidth() == BitWidth &&
743          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
744          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
745   APInt UnknownBits = ~(KnownZero|KnownOne);
746   
747   // The minimum value is when the unknown bits are all zeros.
748   Min = KnownOne;
749   // The maximum value is when the unknown bits are all ones.
750   Max = KnownOne|UnknownBits;
751 }
752
753 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
754 /// SimplifyDemandedBits knows about.  See if the instruction has any
755 /// properties that allow us to simplify its operands.
756 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
757   unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
758   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
759   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
760   
761   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
762                                      KnownZero, KnownOne, 0);
763   if (V == 0) return false;
764   if (V == &Inst) return true;
765   ReplaceInstUsesWith(Inst, V);
766   return true;
767 }
768
769 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
770 /// specified instruction operand if possible, updating it in place.  It returns
771 /// true if it made any change and false otherwise.
772 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
773                                         APInt &KnownZero, APInt &KnownOne,
774                                         unsigned Depth) {
775   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
776                                           KnownZero, KnownOne, Depth);
777   if (NewVal == 0) return false;
778   U.set(NewVal);
779   return true;
780 }
781
782
783 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
784 /// value based on the demanded bits.  When this function is called, it is known
785 /// that only the bits set in DemandedMask of the result of V are ever used
786 /// downstream. Consequently, depending on the mask and V, it may be possible
787 /// to replace V with a constant or one of its operands. In such cases, this
788 /// function does the replacement and returns true. In all other cases, it
789 /// returns false after analyzing the expression and setting KnownOne and known
790 /// to be one in the expression.  KnownZero contains all the bits that are known
791 /// to be zero in the expression. These are provided to potentially allow the
792 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
793 /// the expression. KnownOne and KnownZero always follow the invariant that 
794 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
795 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
796 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
797 /// and KnownOne must all be the same.
798 ///
799 /// This returns null if it did not change anything and it permits no
800 /// simplification.  This returns V itself if it did some simplification of V's
801 /// operands based on the information about what bits are demanded. This returns
802 /// some other non-null value if it found out that V is equal to another value
803 /// in the context where the specified bits are demanded, but not for all users.
804 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
805                                              APInt &KnownZero, APInt &KnownOne,
806                                              unsigned Depth) {
807   assert(V != 0 && "Null pointer of Value???");
808   assert(Depth <= 6 && "Limit Search Depth");
809   uint32_t BitWidth = DemandedMask.getBitWidth();
810   const IntegerType *VTy = cast<IntegerType>(V->getType());
811   assert(VTy->getBitWidth() == BitWidth && 
812          KnownZero.getBitWidth() == BitWidth && 
813          KnownOne.getBitWidth() == BitWidth &&
814          "Value *V, DemandedMask, KnownZero and KnownOne \
815           must have same BitWidth");
816   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
817     // We know all of the bits for a constant!
818     KnownOne = CI->getValue() & DemandedMask;
819     KnownZero = ~KnownOne & DemandedMask;
820     return 0;
821   }
822   
823   KnownZero.clear();
824   KnownOne.clear();
825   if (DemandedMask == 0) {   // Not demanding any bits from V.
826     if (isa<UndefValue>(V))
827       return 0;
828     return UndefValue::get(VTy);
829   }
830   
831   if (Depth == 6)        // Limit search depth.
832     return 0;
833   
834   Instruction *I = dyn_cast<Instruction>(V);
835   if (!I) return 0;        // Only analyze instructions.
836   
837   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
838   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
839
840   // If there are multiple uses of this value and we aren't at the root, then
841   // we can't do any simplifications of the operands, because DemandedMask
842   // only reflects the bits demanded by *one* of the users.
843   if (Depth != 0 && !I->hasOneUse()) {
844     // Despite the fact that we can't simplify this instruction in all User's
845     // context, we can at least compute the knownzero/knownone bits, and we can
846     // do simplifications that apply to *just* the one user if we know that
847     // this instruction has a simpler value in that context.
848     if (I->getOpcode() == Instruction::And) {
849       // If either the LHS or the RHS are Zero, the result is zero.
850       ComputeMaskedBits(I->getOperand(1), DemandedMask,
851                         RHSKnownZero, RHSKnownOne, Depth+1);
852       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
853                         LHSKnownZero, LHSKnownOne, Depth+1);
854       
855       // If all of the demanded bits are known 1 on one side, return the other.
856       // These bits cannot contribute to the result of the 'and' in this
857       // context.
858       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
859           (DemandedMask & ~LHSKnownZero))
860         return I->getOperand(0);
861       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
862           (DemandedMask & ~RHSKnownZero))
863         return I->getOperand(1);
864       
865       // If all of the demanded bits in the inputs are known zeros, return zero.
866       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
867         return Constant::getNullValue(VTy);
868       
869     } else if (I->getOpcode() == Instruction::Or) {
870       // We can simplify (X|Y) -> X or Y in the user's context if we know that
871       // only bits from X or Y are demanded.
872       
873       // If either the LHS or the RHS are One, the result is One.
874       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
875                         RHSKnownZero, RHSKnownOne, Depth+1);
876       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
877                         LHSKnownZero, LHSKnownOne, Depth+1);
878       
879       // If all of the demanded bits are known zero on one side, return the
880       // other.  These bits cannot contribute to the result of the 'or' in this
881       // context.
882       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
883           (DemandedMask & ~LHSKnownOne))
884         return I->getOperand(0);
885       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
886           (DemandedMask & ~RHSKnownOne))
887         return I->getOperand(1);
888       
889       // If all of the potentially set bits on one side are known to be set on
890       // the other side, just use the 'other' side.
891       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
892           (DemandedMask & (~RHSKnownZero)))
893         return I->getOperand(0);
894       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
895           (DemandedMask & (~LHSKnownZero)))
896         return I->getOperand(1);
897     }
898     
899     // Compute the KnownZero/KnownOne bits to simplify things downstream.
900     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
901     return 0;
902   }
903   
904   // If this is the root being simplified, allow it to have multiple uses,
905   // just set the DemandedMask to all bits so that we can try to simplify the
906   // operands.  This allows visitTruncInst (for example) to simplify the
907   // operand of a trunc without duplicating all the logic below.
908   if (Depth == 0 && !V->hasOneUse())
909     DemandedMask = APInt::getAllOnesValue(BitWidth);
910   
911   switch (I->getOpcode()) {
912   default:
913     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
914     break;
915   case Instruction::And:
916     // If either the LHS or the RHS are Zero, the result is zero.
917     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
918                              RHSKnownZero, RHSKnownOne, Depth+1) ||
919         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
920                              LHSKnownZero, LHSKnownOne, Depth+1))
921       return I;
922     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
923     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
924
925     // If all of the demanded bits are known 1 on one side, return the other.
926     // These bits cannot contribute to the result of the 'and'.
927     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
928         (DemandedMask & ~LHSKnownZero))
929       return I->getOperand(0);
930     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
931         (DemandedMask & ~RHSKnownZero))
932       return I->getOperand(1);
933     
934     // If all of the demanded bits in the inputs are known zeros, return zero.
935     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
936       return Constant::getNullValue(VTy);
937       
938     // If the RHS is a constant, see if we can simplify it.
939     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
940       return I;
941       
942     // Output known-1 bits are only known if set in both the LHS & RHS.
943     RHSKnownOne &= LHSKnownOne;
944     // Output known-0 are known to be clear if zero in either the LHS | RHS.
945     RHSKnownZero |= LHSKnownZero;
946     break;
947   case Instruction::Or:
948     // If either the LHS or the RHS are One, the result is One.
949     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
950                              RHSKnownZero, RHSKnownOne, Depth+1) ||
951         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
952                              LHSKnownZero, LHSKnownOne, Depth+1))
953       return I;
954     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
955     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
956     
957     // If all of the demanded bits are known zero on one side, return the other.
958     // These bits cannot contribute to the result of the 'or'.
959     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
960         (DemandedMask & ~LHSKnownOne))
961       return I->getOperand(0);
962     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
963         (DemandedMask & ~RHSKnownOne))
964       return I->getOperand(1);
965
966     // If all of the potentially set bits on one side are known to be set on
967     // the other side, just use the 'other' side.
968     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
969         (DemandedMask & (~RHSKnownZero)))
970       return I->getOperand(0);
971     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
972         (DemandedMask & (~LHSKnownZero)))
973       return I->getOperand(1);
974         
975     // If the RHS is a constant, see if we can simplify it.
976     if (ShrinkDemandedConstant(I, 1, DemandedMask))
977       return I;
978           
979     // Output known-0 bits are only known if clear in both the LHS & RHS.
980     RHSKnownZero &= LHSKnownZero;
981     // Output known-1 are known to be set if set in either the LHS | RHS.
982     RHSKnownOne |= LHSKnownOne;
983     break;
984   case Instruction::Xor: {
985     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
986                              RHSKnownZero, RHSKnownOne, Depth+1) ||
987         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
988                              LHSKnownZero, LHSKnownOne, Depth+1))
989       return I;
990     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
991     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
992     
993     // If all of the demanded bits are known zero on one side, return the other.
994     // These bits cannot contribute to the result of the 'xor'.
995     if ((DemandedMask & RHSKnownZero) == DemandedMask)
996       return I->getOperand(0);
997     if ((DemandedMask & LHSKnownZero) == DemandedMask)
998       return I->getOperand(1);
999     
1000     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1001     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1002                          (RHSKnownOne & LHSKnownOne);
1003     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1004     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1005                         (RHSKnownOne & LHSKnownZero);
1006     
1007     // If all of the demanded bits are known to be zero on one side or the
1008     // other, turn this into an *inclusive* or.
1009     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1010     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1011       Instruction *Or =
1012         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1013                                  I->getName());
1014       return InsertNewInstBefore(Or, *I);
1015     }
1016     
1017     // If all of the demanded bits on one side are known, and all of the set
1018     // bits on that side are also known to be set on the other side, turn this
1019     // into an AND, as we know the bits will be cleared.
1020     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1021     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1022       // all known
1023       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1024         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1025         Instruction *And = 
1026           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1027         return InsertNewInstBefore(And, *I);
1028       }
1029     }
1030     
1031     // If the RHS is a constant, see if we can simplify it.
1032     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1033     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1034       return I;
1035     
1036     RHSKnownZero = KnownZeroOut;
1037     RHSKnownOne  = KnownOneOut;
1038     break;
1039   }
1040   case Instruction::Select:
1041     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1042                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1043         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1044                              LHSKnownZero, LHSKnownOne, Depth+1))
1045       return I;
1046     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1047     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1048     
1049     // If the operands are constants, see if we can simplify them.
1050     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1051         ShrinkDemandedConstant(I, 2, DemandedMask))
1052       return I;
1053     
1054     // Only known if known in both the LHS and RHS.
1055     RHSKnownOne &= LHSKnownOne;
1056     RHSKnownZero &= LHSKnownZero;
1057     break;
1058   case Instruction::Trunc: {
1059     unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1060     DemandedMask.zext(truncBf);
1061     RHSKnownZero.zext(truncBf);
1062     RHSKnownOne.zext(truncBf);
1063     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1064                              RHSKnownZero, RHSKnownOne, Depth+1))
1065       return I;
1066     DemandedMask.trunc(BitWidth);
1067     RHSKnownZero.trunc(BitWidth);
1068     RHSKnownOne.trunc(BitWidth);
1069     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1070     break;
1071   }
1072   case Instruction::BitCast:
1073     if (!I->getOperand(0)->getType()->isInteger())
1074       return false;  // vector->int or fp->int?
1075     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1076                              RHSKnownZero, RHSKnownOne, Depth+1))
1077       return I;
1078     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1079     break;
1080   case Instruction::ZExt: {
1081     // Compute the bits in the result that are not present in the input.
1082     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1083     
1084     DemandedMask.trunc(SrcBitWidth);
1085     RHSKnownZero.trunc(SrcBitWidth);
1086     RHSKnownOne.trunc(SrcBitWidth);
1087     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1088                              RHSKnownZero, RHSKnownOne, Depth+1))
1089       return I;
1090     DemandedMask.zext(BitWidth);
1091     RHSKnownZero.zext(BitWidth);
1092     RHSKnownOne.zext(BitWidth);
1093     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1094     // The top bits are known to be zero.
1095     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1096     break;
1097   }
1098   case Instruction::SExt: {
1099     // Compute the bits in the result that are not present in the input.
1100     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1101     
1102     APInt InputDemandedBits = DemandedMask & 
1103                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1104
1105     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1106     // If any of the sign extended bits are demanded, we know that the sign
1107     // bit is demanded.
1108     if ((NewBits & DemandedMask) != 0)
1109       InputDemandedBits.set(SrcBitWidth-1);
1110       
1111     InputDemandedBits.trunc(SrcBitWidth);
1112     RHSKnownZero.trunc(SrcBitWidth);
1113     RHSKnownOne.trunc(SrcBitWidth);
1114     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1115                              RHSKnownZero, RHSKnownOne, Depth+1))
1116       return I;
1117     InputDemandedBits.zext(BitWidth);
1118     RHSKnownZero.zext(BitWidth);
1119     RHSKnownOne.zext(BitWidth);
1120     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1121       
1122     // If the sign bit of the input is known set or clear, then we know the
1123     // top bits of the result.
1124
1125     // If the input sign bit is known zero, or if the NewBits are not demanded
1126     // convert this into a zero extension.
1127     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1128       // Convert to ZExt cast
1129       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1130       return InsertNewInstBefore(NewCast, *I);
1131     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1132       RHSKnownOne |= NewBits;
1133     }
1134     break;
1135   }
1136   case Instruction::Add: {
1137     // Figure out what the input bits are.  If the top bits of the and result
1138     // are not demanded, then the add doesn't demand them from its input
1139     // either.
1140     unsigned NLZ = DemandedMask.countLeadingZeros();
1141       
1142     // If there is a constant on the RHS, there are a variety of xformations
1143     // we can do.
1144     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1145       // If null, this should be simplified elsewhere.  Some of the xforms here
1146       // won't work if the RHS is zero.
1147       if (RHS->isZero())
1148         break;
1149       
1150       // If the top bit of the output is demanded, demand everything from the
1151       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1152       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1153
1154       // Find information about known zero/one bits in the input.
1155       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1156                                LHSKnownZero, LHSKnownOne, Depth+1))
1157         return I;
1158
1159       // If the RHS of the add has bits set that can't affect the input, reduce
1160       // the constant.
1161       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1162         return I;
1163       
1164       // Avoid excess work.
1165       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1166         break;
1167       
1168       // Turn it into OR if input bits are zero.
1169       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1170         Instruction *Or =
1171           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1172                                    I->getName());
1173         return InsertNewInstBefore(Or, *I);
1174       }
1175       
1176       // We can say something about the output known-zero and known-one bits,
1177       // depending on potential carries from the input constant and the
1178       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1179       // bits set and the RHS constant is 0x01001, then we know we have a known
1180       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1181       
1182       // To compute this, we first compute the potential carry bits.  These are
1183       // the bits which may be modified.  I'm not aware of a better way to do
1184       // this scan.
1185       const APInt &RHSVal = RHS->getValue();
1186       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1187       
1188       // Now that we know which bits have carries, compute the known-1/0 sets.
1189       
1190       // Bits are known one if they are known zero in one operand and one in the
1191       // other, and there is no input carry.
1192       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1193                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1194       
1195       // Bits are known zero if they are known zero in both operands and there
1196       // is no input carry.
1197       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1198     } else {
1199       // If the high-bits of this ADD are not demanded, then it does not demand
1200       // the high bits of its LHS or RHS.
1201       if (DemandedMask[BitWidth-1] == 0) {
1202         // Right fill the mask of bits for this ADD to demand the most
1203         // significant bit and all those below it.
1204         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1205         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1206                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1207             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1208                                  LHSKnownZero, LHSKnownOne, Depth+1))
1209           return I;
1210       }
1211     }
1212     break;
1213   }
1214   case Instruction::Sub:
1215     // If the high-bits of this SUB are not demanded, then it does not demand
1216     // the high bits of its LHS or RHS.
1217     if (DemandedMask[BitWidth-1] == 0) {
1218       // Right fill the mask of bits for this SUB to demand the most
1219       // significant bit and all those below it.
1220       uint32_t NLZ = DemandedMask.countLeadingZeros();
1221       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1222       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1223                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1224           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1225                                LHSKnownZero, LHSKnownOne, Depth+1))
1226         return I;
1227     }
1228     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1229     // the known zeros and ones.
1230     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1231     break;
1232   case Instruction::Shl:
1233     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1234       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1235       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1236       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1237                                RHSKnownZero, RHSKnownOne, Depth+1))
1238         return I;
1239       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1240       RHSKnownZero <<= ShiftAmt;
1241       RHSKnownOne  <<= ShiftAmt;
1242       // low bits known zero.
1243       if (ShiftAmt)
1244         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1245     }
1246     break;
1247   case Instruction::LShr:
1248     // For a logical shift right
1249     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1250       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1251       
1252       // Unsigned shift right.
1253       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1254       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1255                                RHSKnownZero, RHSKnownOne, Depth+1))
1256         return I;
1257       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1258       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1259       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1260       if (ShiftAmt) {
1261         // Compute the new bits that are at the top now.
1262         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1263         RHSKnownZero |= HighBits;  // high bits known zero.
1264       }
1265     }
1266     break;
1267   case Instruction::AShr:
1268     // If this is an arithmetic shift right and only the low-bit is set, we can
1269     // always convert this into a logical shr, even if the shift amount is
1270     // variable.  The low bit of the shift cannot be an input sign bit unless
1271     // the shift amount is >= the size of the datatype, which is undefined.
1272     if (DemandedMask == 1) {
1273       // Perform the logical shift right.
1274       Instruction *NewVal = BinaryOperator::CreateLShr(
1275                         I->getOperand(0), I->getOperand(1), I->getName());
1276       return InsertNewInstBefore(NewVal, *I);
1277     }    
1278
1279     // If the sign bit is the only bit demanded by this ashr, then there is no
1280     // need to do it, the shift doesn't change the high bit.
1281     if (DemandedMask.isSignBit())
1282       return I->getOperand(0);
1283     
1284     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1285       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1286       
1287       // Signed shift right.
1288       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1289       // If any of the "high bits" are demanded, we should set the sign bit as
1290       // demanded.
1291       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1292         DemandedMaskIn.set(BitWidth-1);
1293       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1294                                RHSKnownZero, RHSKnownOne, Depth+1))
1295         return I;
1296       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1297       // Compute the new bits that are at the top now.
1298       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1299       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1300       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1301         
1302       // Handle the sign bits.
1303       APInt SignBit(APInt::getSignBit(BitWidth));
1304       // Adjust to where it is now in the mask.
1305       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1306         
1307       // If the input sign bit is known to be zero, or if none of the top bits
1308       // are demanded, turn this into an unsigned shift right.
1309       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1310           (HighBits & ~DemandedMask) == HighBits) {
1311         // Perform the logical shift right.
1312         Instruction *NewVal = BinaryOperator::CreateLShr(
1313                           I->getOperand(0), SA, I->getName());
1314         return InsertNewInstBefore(NewVal, *I);
1315       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1316         RHSKnownOne |= HighBits;
1317       }
1318     }
1319     break;
1320   case Instruction::SRem:
1321     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1322       APInt RA = Rem->getValue().abs();
1323       if (RA.isPowerOf2()) {
1324         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1325           return I->getOperand(0);
1326
1327         APInt LowBits = RA - 1;
1328         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1329         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1330                                  LHSKnownZero, LHSKnownOne, Depth+1))
1331           return I;
1332
1333         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1334           LHSKnownZero |= ~LowBits;
1335
1336         KnownZero |= LHSKnownZero & DemandedMask;
1337
1338         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1339       }
1340     }
1341     break;
1342   case Instruction::URem: {
1343     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1344     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1345     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1346                              KnownZero2, KnownOne2, Depth+1) ||
1347         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1348                              KnownZero2, KnownOne2, Depth+1))
1349       return I;
1350
1351     unsigned Leaders = KnownZero2.countLeadingOnes();
1352     Leaders = std::max(Leaders,
1353                        KnownZero2.countLeadingOnes());
1354     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1355     break;
1356   }
1357   case Instruction::Call:
1358     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1359       switch (II->getIntrinsicID()) {
1360       default: break;
1361       case Intrinsic::bswap: {
1362         // If the only bits demanded come from one byte of the bswap result,
1363         // just shift the input byte into position to eliminate the bswap.
1364         unsigned NLZ = DemandedMask.countLeadingZeros();
1365         unsigned NTZ = DemandedMask.countTrailingZeros();
1366           
1367         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1368         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1369         // have 14 leading zeros, round to 8.
1370         NLZ &= ~7;
1371         NTZ &= ~7;
1372         // If we need exactly one byte, we can do this transformation.
1373         if (BitWidth-NLZ-NTZ == 8) {
1374           unsigned ResultBit = NTZ;
1375           unsigned InputBit = BitWidth-NTZ-8;
1376           
1377           // Replace this with either a left or right shift to get the byte into
1378           // the right place.
1379           Instruction *NewVal;
1380           if (InputBit > ResultBit)
1381             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1382                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1383           else
1384             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1385                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1386           NewVal->takeName(I);
1387           return InsertNewInstBefore(NewVal, *I);
1388         }
1389           
1390         // TODO: Could compute known zero/one bits based on the input.
1391         break;
1392       }
1393       }
1394     }
1395     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1396     break;
1397   }
1398   
1399   // If the client is only demanding bits that we know, return the known
1400   // constant.
1401   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1402     return ConstantInt::get(RHSKnownOne);
1403   return false;
1404 }
1405
1406
1407 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1408 /// any number of elements. DemandedElts contains the set of elements that are
1409 /// actually used by the caller.  This method analyzes which elements of the
1410 /// operand are undef and returns that information in UndefElts.
1411 ///
1412 /// If the information about demanded elements can be used to simplify the
1413 /// operation, the operation is simplified, then the resultant value is
1414 /// returned.  This returns null if no change was made.
1415 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1416                                                 APInt& UndefElts,
1417                                                 unsigned Depth) {
1418   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1419   APInt EltMask(APInt::getAllOnesValue(VWidth));
1420   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1421
1422   if (isa<UndefValue>(V)) {
1423     // If the entire vector is undefined, just return this info.
1424     UndefElts = EltMask;
1425     return 0;
1426   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1427     UndefElts = EltMask;
1428     return UndefValue::get(V->getType());
1429   }
1430
1431   UndefElts = 0;
1432   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1433     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1434     Constant *Undef = UndefValue::get(EltTy);
1435
1436     std::vector<Constant*> Elts;
1437     for (unsigned i = 0; i != VWidth; ++i)
1438       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1439         Elts.push_back(Undef);
1440         UndefElts.set(i);
1441       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1442         Elts.push_back(Undef);
1443         UndefElts.set(i);
1444       } else {                               // Otherwise, defined.
1445         Elts.push_back(CP->getOperand(i));
1446       }
1447
1448     // If we changed the constant, return it.
1449     Constant *NewCP = ConstantVector::get(Elts);
1450     return NewCP != CP ? NewCP : 0;
1451   } else if (isa<ConstantAggregateZero>(V)) {
1452     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1453     // set to undef.
1454     
1455     // Check if this is identity. If so, return 0 since we are not simplifying
1456     // anything.
1457     if (DemandedElts == ((1ULL << VWidth) -1))
1458       return 0;
1459     
1460     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1461     Constant *Zero = Constant::getNullValue(EltTy);
1462     Constant *Undef = UndefValue::get(EltTy);
1463     std::vector<Constant*> Elts;
1464     for (unsigned i = 0; i != VWidth; ++i) {
1465       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1466       Elts.push_back(Elt);
1467     }
1468     UndefElts = DemandedElts ^ EltMask;
1469     return ConstantVector::get(Elts);
1470   }
1471   
1472   // Limit search depth.
1473   if (Depth == 10)
1474     return false;
1475
1476   // If multiple users are using the root value, procede with
1477   // simplification conservatively assuming that all elements
1478   // are needed.
1479   if (!V->hasOneUse()) {
1480     // Quit if we find multiple users of a non-root value though.
1481     // They'll be handled when it's their turn to be visited by
1482     // the main instcombine process.
1483     if (Depth != 0)
1484       // TODO: Just compute the UndefElts information recursively.
1485       return false;
1486
1487     // Conservatively assume that all elements are needed.
1488     DemandedElts = EltMask;
1489   }
1490   
1491   Instruction *I = dyn_cast<Instruction>(V);
1492   if (!I) return false;        // Only analyze instructions.
1493   
1494   bool MadeChange = false;
1495   APInt UndefElts2(VWidth, 0);
1496   Value *TmpV;
1497   switch (I->getOpcode()) {
1498   default: break;
1499     
1500   case Instruction::InsertElement: {
1501     // If this is a variable index, we don't know which element it overwrites.
1502     // demand exactly the same input as we produce.
1503     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1504     if (Idx == 0) {
1505       // Note that we can't propagate undef elt info, because we don't know
1506       // which elt is getting updated.
1507       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1508                                         UndefElts2, Depth+1);
1509       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1510       break;
1511     }
1512     
1513     // If this is inserting an element that isn't demanded, remove this
1514     // insertelement.
1515     unsigned IdxNo = Idx->getZExtValue();
1516     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1517       return AddSoonDeadInstToWorklist(*I, 0);
1518     
1519     // Otherwise, the element inserted overwrites whatever was there, so the
1520     // input demanded set is simpler than the output set.
1521     APInt DemandedElts2 = DemandedElts;
1522     DemandedElts2.clear(IdxNo);
1523     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1524                                       UndefElts, Depth+1);
1525     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1526
1527     // The inserted element is defined.
1528     UndefElts.clear(IdxNo);
1529     break;
1530   }
1531   case Instruction::ShuffleVector: {
1532     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1533     uint64_t LHSVWidth =
1534       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1535     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1536     for (unsigned i = 0; i < VWidth; i++) {
1537       if (DemandedElts[i]) {
1538         unsigned MaskVal = Shuffle->getMaskValue(i);
1539         if (MaskVal != -1u) {
1540           assert(MaskVal < LHSVWidth * 2 &&
1541                  "shufflevector mask index out of range!");
1542           if (MaskVal < LHSVWidth)
1543             LeftDemanded.set(MaskVal);
1544           else
1545             RightDemanded.set(MaskVal - LHSVWidth);
1546         }
1547       }
1548     }
1549
1550     APInt UndefElts4(LHSVWidth, 0);
1551     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1552                                       UndefElts4, Depth+1);
1553     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1554
1555     APInt UndefElts3(LHSVWidth, 0);
1556     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1557                                       UndefElts3, Depth+1);
1558     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1559
1560     bool NewUndefElts = false;
1561     for (unsigned i = 0; i < VWidth; i++) {
1562       unsigned MaskVal = Shuffle->getMaskValue(i);
1563       if (MaskVal == -1u) {
1564         UndefElts.set(i);
1565       } else if (MaskVal < LHSVWidth) {
1566         if (UndefElts4[MaskVal]) {
1567           NewUndefElts = true;
1568           UndefElts.set(i);
1569         }
1570       } else {
1571         if (UndefElts3[MaskVal - LHSVWidth]) {
1572           NewUndefElts = true;
1573           UndefElts.set(i);
1574         }
1575       }
1576     }
1577
1578     if (NewUndefElts) {
1579       // Add additional discovered undefs.
1580       std::vector<Constant*> Elts;
1581       for (unsigned i = 0; i < VWidth; ++i) {
1582         if (UndefElts[i])
1583           Elts.push_back(UndefValue::get(Type::Int32Ty));
1584         else
1585           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1586                                           Shuffle->getMaskValue(i)));
1587       }
1588       I->setOperand(2, ConstantVector::get(Elts));
1589       MadeChange = true;
1590     }
1591     break;
1592   }
1593   case Instruction::BitCast: {
1594     // Vector->vector casts only.
1595     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1596     if (!VTy) break;
1597     unsigned InVWidth = VTy->getNumElements();
1598     APInt InputDemandedElts(InVWidth, 0);
1599     unsigned Ratio;
1600
1601     if (VWidth == InVWidth) {
1602       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1603       // elements as are demanded of us.
1604       Ratio = 1;
1605       InputDemandedElts = DemandedElts;
1606     } else if (VWidth > InVWidth) {
1607       // Untested so far.
1608       break;
1609       
1610       // If there are more elements in the result than there are in the source,
1611       // then an input element is live if any of the corresponding output
1612       // elements are live.
1613       Ratio = VWidth/InVWidth;
1614       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1615         if (DemandedElts[OutIdx])
1616           InputDemandedElts.set(OutIdx/Ratio);
1617       }
1618     } else {
1619       // Untested so far.
1620       break;
1621       
1622       // If there are more elements in the source than there are in the result,
1623       // then an input element is live if the corresponding output element is
1624       // live.
1625       Ratio = InVWidth/VWidth;
1626       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1627         if (DemandedElts[InIdx/Ratio])
1628           InputDemandedElts.set(InIdx);
1629     }
1630     
1631     // div/rem demand all inputs, because they don't want divide by zero.
1632     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1633                                       UndefElts2, Depth+1);
1634     if (TmpV) {
1635       I->setOperand(0, TmpV);
1636       MadeChange = true;
1637     }
1638     
1639     UndefElts = UndefElts2;
1640     if (VWidth > InVWidth) {
1641       assert(0 && "Unimp");
1642       // If there are more elements in the result than there are in the source,
1643       // then an output element is undef if the corresponding input element is
1644       // undef.
1645       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1646         if (UndefElts2[OutIdx/Ratio])
1647           UndefElts.set(OutIdx);
1648     } else if (VWidth < InVWidth) {
1649       assert(0 && "Unimp");
1650       // If there are more elements in the source than there are in the result,
1651       // then a result element is undef if all of the corresponding input
1652       // elements are undef.
1653       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1654       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1655         if (!UndefElts2[InIdx])            // Not undef?
1656           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1657     }
1658     break;
1659   }
1660   case Instruction::And:
1661   case Instruction::Or:
1662   case Instruction::Xor:
1663   case Instruction::Add:
1664   case Instruction::Sub:
1665   case Instruction::Mul:
1666     // div/rem demand all inputs, because they don't want divide by zero.
1667     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1668                                       UndefElts, Depth+1);
1669     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1670     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1671                                       UndefElts2, Depth+1);
1672     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1673       
1674     // Output elements are undefined if both are undefined.  Consider things
1675     // like undef&0.  The result is known zero, not undef.
1676     UndefElts &= UndefElts2;
1677     break;
1678     
1679   case Instruction::Call: {
1680     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1681     if (!II) break;
1682     switch (II->getIntrinsicID()) {
1683     default: break;
1684       
1685     // Binary vector operations that work column-wise.  A dest element is a
1686     // function of the corresponding input elements from the two inputs.
1687     case Intrinsic::x86_sse_sub_ss:
1688     case Intrinsic::x86_sse_mul_ss:
1689     case Intrinsic::x86_sse_min_ss:
1690     case Intrinsic::x86_sse_max_ss:
1691     case Intrinsic::x86_sse2_sub_sd:
1692     case Intrinsic::x86_sse2_mul_sd:
1693     case Intrinsic::x86_sse2_min_sd:
1694     case Intrinsic::x86_sse2_max_sd:
1695       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1696                                         UndefElts, Depth+1);
1697       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1698       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1699                                         UndefElts2, Depth+1);
1700       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1701
1702       // If only the low elt is demanded and this is a scalarizable intrinsic,
1703       // scalarize it now.
1704       if (DemandedElts == 1) {
1705         switch (II->getIntrinsicID()) {
1706         default: break;
1707         case Intrinsic::x86_sse_sub_ss:
1708         case Intrinsic::x86_sse_mul_ss:
1709         case Intrinsic::x86_sse2_sub_sd:
1710         case Intrinsic::x86_sse2_mul_sd:
1711           // TODO: Lower MIN/MAX/ABS/etc
1712           Value *LHS = II->getOperand(1);
1713           Value *RHS = II->getOperand(2);
1714           // Extract the element as scalars.
1715           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1716           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1717           
1718           switch (II->getIntrinsicID()) {
1719           default: assert(0 && "Case stmts out of sync!");
1720           case Intrinsic::x86_sse_sub_ss:
1721           case Intrinsic::x86_sse2_sub_sd:
1722             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1723                                                         II->getName()), *II);
1724             break;
1725           case Intrinsic::x86_sse_mul_ss:
1726           case Intrinsic::x86_sse2_mul_sd:
1727             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1728                                                          II->getName()), *II);
1729             break;
1730           }
1731           
1732           Instruction *New =
1733             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1734                                       II->getName());
1735           InsertNewInstBefore(New, *II);
1736           AddSoonDeadInstToWorklist(*II, 0);
1737           return New;
1738         }            
1739       }
1740         
1741       // Output elements are undefined if both are undefined.  Consider things
1742       // like undef&0.  The result is known zero, not undef.
1743       UndefElts &= UndefElts2;
1744       break;
1745     }
1746     break;
1747   }
1748   }
1749   return MadeChange ? I : 0;
1750 }
1751
1752
1753 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1754 /// function is designed to check a chain of associative operators for a
1755 /// potential to apply a certain optimization.  Since the optimization may be
1756 /// applicable if the expression was reassociated, this checks the chain, then
1757 /// reassociates the expression as necessary to expose the optimization
1758 /// opportunity.  This makes use of a special Functor, which must define
1759 /// 'shouldApply' and 'apply' methods.
1760 ///
1761 template<typename Functor>
1762 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1763   unsigned Opcode = Root.getOpcode();
1764   Value *LHS = Root.getOperand(0);
1765
1766   // Quick check, see if the immediate LHS matches...
1767   if (F.shouldApply(LHS))
1768     return F.apply(Root);
1769
1770   // Otherwise, if the LHS is not of the same opcode as the root, return.
1771   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1772   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1773     // Should we apply this transform to the RHS?
1774     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1775
1776     // If not to the RHS, check to see if we should apply to the LHS...
1777     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1778       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1779       ShouldApply = true;
1780     }
1781
1782     // If the functor wants to apply the optimization to the RHS of LHSI,
1783     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1784     if (ShouldApply) {
1785       // Now all of the instructions are in the current basic block, go ahead
1786       // and perform the reassociation.
1787       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1788
1789       // First move the selected RHS to the LHS of the root...
1790       Root.setOperand(0, LHSI->getOperand(1));
1791
1792       // Make what used to be the LHS of the root be the user of the root...
1793       Value *ExtraOperand = TmpLHSI->getOperand(1);
1794       if (&Root == TmpLHSI) {
1795         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1796         return 0;
1797       }
1798       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1799       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1800       BasicBlock::iterator ARI = &Root; ++ARI;
1801       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1802       ARI = Root;
1803
1804       // Now propagate the ExtraOperand down the chain of instructions until we
1805       // get to LHSI.
1806       while (TmpLHSI != LHSI) {
1807         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1808         // Move the instruction to immediately before the chain we are
1809         // constructing to avoid breaking dominance properties.
1810         NextLHSI->moveBefore(ARI);
1811         ARI = NextLHSI;
1812
1813         Value *NextOp = NextLHSI->getOperand(1);
1814         NextLHSI->setOperand(1, ExtraOperand);
1815         TmpLHSI = NextLHSI;
1816         ExtraOperand = NextOp;
1817       }
1818
1819       // Now that the instructions are reassociated, have the functor perform
1820       // the transformation...
1821       return F.apply(Root);
1822     }
1823
1824     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1825   }
1826   return 0;
1827 }
1828
1829 namespace {
1830
1831 // AddRHS - Implements: X + X --> X << 1
1832 struct AddRHS {
1833   Value *RHS;
1834   AddRHS(Value *rhs) : RHS(rhs) {}
1835   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1836   Instruction *apply(BinaryOperator &Add) const {
1837     return BinaryOperator::CreateShl(Add.getOperand(0),
1838                                      ConstantInt::get(Add.getType(), 1));
1839   }
1840 };
1841
1842 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1843 //                 iff C1&C2 == 0
1844 struct AddMaskingAnd {
1845   Constant *C2;
1846   AddMaskingAnd(Constant *c) : C2(c) {}
1847   bool shouldApply(Value *LHS) const {
1848     ConstantInt *C1;
1849     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1850            ConstantExpr::getAnd(C1, C2)->isNullValue();
1851   }
1852   Instruction *apply(BinaryOperator &Add) const {
1853     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1854   }
1855 };
1856
1857 }
1858
1859 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1860                                              InstCombiner *IC) {
1861   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1862     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1863   }
1864
1865   // Figure out if the constant is the left or the right argument.
1866   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1867   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1868
1869   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1870     if (ConstIsRHS)
1871       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1872     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1873   }
1874
1875   Value *Op0 = SO, *Op1 = ConstOperand;
1876   if (!ConstIsRHS)
1877     std::swap(Op0, Op1);
1878   Instruction *New;
1879   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1880     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1881   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1882     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1883                           SO->getName()+".cmp");
1884   else {
1885     assert(0 && "Unknown binary instruction type!");
1886     abort();
1887   }
1888   return IC->InsertNewInstBefore(New, I);
1889 }
1890
1891 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1892 // constant as the other operand, try to fold the binary operator into the
1893 // select arguments.  This also works for Cast instructions, which obviously do
1894 // not have a second operand.
1895 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1896                                      InstCombiner *IC) {
1897   // Don't modify shared select instructions
1898   if (!SI->hasOneUse()) return 0;
1899   Value *TV = SI->getOperand(1);
1900   Value *FV = SI->getOperand(2);
1901
1902   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1903     // Bool selects with constant operands can be folded to logical ops.
1904     if (SI->getType() == Type::Int1Ty) return 0;
1905
1906     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1907     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1908
1909     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1910                               SelectFalseVal);
1911   }
1912   return 0;
1913 }
1914
1915
1916 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1917 /// node as operand #0, see if we can fold the instruction into the PHI (which
1918 /// is only possible if all operands to the PHI are constants).
1919 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1920   PHINode *PN = cast<PHINode>(I.getOperand(0));
1921   unsigned NumPHIValues = PN->getNumIncomingValues();
1922   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1923
1924   // Check to see if all of the operands of the PHI are constants.  If there is
1925   // one non-constant value, remember the BB it is.  If there is more than one
1926   // or if *it* is a PHI, bail out.
1927   BasicBlock *NonConstBB = 0;
1928   for (unsigned i = 0; i != NumPHIValues; ++i)
1929     if (!isa<Constant>(PN->getIncomingValue(i))) {
1930       if (NonConstBB) return 0;  // More than one non-const value.
1931       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1932       NonConstBB = PN->getIncomingBlock(i);
1933       
1934       // If the incoming non-constant value is in I's block, we have an infinite
1935       // loop.
1936       if (NonConstBB == I.getParent())
1937         return 0;
1938     }
1939   
1940   // If there is exactly one non-constant value, we can insert a copy of the
1941   // operation in that block.  However, if this is a critical edge, we would be
1942   // inserting the computation one some other paths (e.g. inside a loop).  Only
1943   // do this if the pred block is unconditionally branching into the phi block.
1944   if (NonConstBB) {
1945     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1946     if (!BI || !BI->isUnconditional()) return 0;
1947   }
1948
1949   // Okay, we can do the transformation: create the new PHI node.
1950   PHINode *NewPN = PHINode::Create(I.getType(), "");
1951   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1952   InsertNewInstBefore(NewPN, *PN);
1953   NewPN->takeName(PN);
1954
1955   // Next, add all of the operands to the PHI.
1956   if (I.getNumOperands() == 2) {
1957     Constant *C = cast<Constant>(I.getOperand(1));
1958     for (unsigned i = 0; i != NumPHIValues; ++i) {
1959       Value *InV = 0;
1960       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1961         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1962           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1963         else
1964           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1965       } else {
1966         assert(PN->getIncomingBlock(i) == NonConstBB);
1967         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1968           InV = BinaryOperator::Create(BO->getOpcode(),
1969                                        PN->getIncomingValue(i), C, "phitmp",
1970                                        NonConstBB->getTerminator());
1971         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1972           InV = CmpInst::Create(CI->getOpcode(), 
1973                                 CI->getPredicate(),
1974                                 PN->getIncomingValue(i), C, "phitmp",
1975                                 NonConstBB->getTerminator());
1976         else
1977           assert(0 && "Unknown binop!");
1978         
1979         AddToWorkList(cast<Instruction>(InV));
1980       }
1981       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1982     }
1983   } else { 
1984     CastInst *CI = cast<CastInst>(&I);
1985     const Type *RetTy = CI->getType();
1986     for (unsigned i = 0; i != NumPHIValues; ++i) {
1987       Value *InV;
1988       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1989         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1990       } else {
1991         assert(PN->getIncomingBlock(i) == NonConstBB);
1992         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1993                                I.getType(), "phitmp", 
1994                                NonConstBB->getTerminator());
1995         AddToWorkList(cast<Instruction>(InV));
1996       }
1997       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1998     }
1999   }
2000   return ReplaceInstUsesWith(I, NewPN);
2001 }
2002
2003
2004 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2005 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2006 /// This basically requires proving that the add in the original type would not
2007 /// overflow to change the sign bit or have a carry out.
2008 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2009   // There are different heuristics we can use for this.  Here are some simple
2010   // ones.
2011   
2012   // Add has the property that adding any two 2's complement numbers can only 
2013   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2014   // have at least two sign bits, we know that the addition of the two values will
2015   // sign extend fine.
2016   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2017     return true;
2018   
2019   
2020   // If one of the operands only has one non-zero bit, and if the other operand
2021   // has a known-zero bit in a more significant place than it (not including the
2022   // sign bit) the ripple may go up to and fill the zero, but won't change the
2023   // sign.  For example, (X & ~4) + 1.
2024   
2025   // TODO: Implement.
2026   
2027   return false;
2028 }
2029
2030
2031 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2032   bool Changed = SimplifyCommutative(I);
2033   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2034
2035   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2036     // X + undef -> undef
2037     if (isa<UndefValue>(RHS))
2038       return ReplaceInstUsesWith(I, RHS);
2039
2040     // X + 0 --> X
2041     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2042       if (RHSC->isNullValue())
2043         return ReplaceInstUsesWith(I, LHS);
2044     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2045       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2046                               (I.getType())->getValueAPF()))
2047         return ReplaceInstUsesWith(I, LHS);
2048     }
2049
2050     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2051       // X + (signbit) --> X ^ signbit
2052       const APInt& Val = CI->getValue();
2053       uint32_t BitWidth = Val.getBitWidth();
2054       if (Val == APInt::getSignBit(BitWidth))
2055         return BinaryOperator::CreateXor(LHS, RHS);
2056       
2057       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2058       // (X & 254)+1 -> (X&254)|1
2059       if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
2060         return &I;
2061
2062       // zext(i1) - 1  ->  select i1, 0, -1
2063       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2064         if (CI->isAllOnesValue() &&
2065             ZI->getOperand(0)->getType() == Type::Int1Ty)
2066           return SelectInst::Create(ZI->getOperand(0),
2067                                     Constant::getNullValue(I.getType()),
2068                                     ConstantInt::getAllOnesValue(I.getType()));
2069     }
2070
2071     if (isa<PHINode>(LHS))
2072       if (Instruction *NV = FoldOpIntoPhi(I))
2073         return NV;
2074     
2075     ConstantInt *XorRHS = 0;
2076     Value *XorLHS = 0;
2077     if (isa<ConstantInt>(RHSC) &&
2078         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2079       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2080       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2081       
2082       uint32_t Size = TySizeBits / 2;
2083       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2084       APInt CFF80Val(-C0080Val);
2085       do {
2086         if (TySizeBits > Size) {
2087           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2088           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2089           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2090               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2091             // This is a sign extend if the top bits are known zero.
2092             if (!MaskedValueIsZero(XorLHS, 
2093                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2094               Size = 0;  // Not a sign ext, but can't be any others either.
2095             break;
2096           }
2097         }
2098         Size >>= 1;
2099         C0080Val = APIntOps::lshr(C0080Val, Size);
2100         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2101       } while (Size >= 1);
2102       
2103       // FIXME: This shouldn't be necessary. When the backends can handle types
2104       // with funny bit widths then this switch statement should be removed. It
2105       // is just here to get the size of the "middle" type back up to something
2106       // that the back ends can handle.
2107       const Type *MiddleType = 0;
2108       switch (Size) {
2109         default: break;
2110         case 32: MiddleType = Type::Int32Ty; break;
2111         case 16: MiddleType = Type::Int16Ty; break;
2112         case  8: MiddleType = Type::Int8Ty; break;
2113       }
2114       if (MiddleType) {
2115         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2116         InsertNewInstBefore(NewTrunc, I);
2117         return new SExtInst(NewTrunc, I.getType(), I.getName());
2118       }
2119     }
2120   }
2121
2122   if (I.getType() == Type::Int1Ty)
2123     return BinaryOperator::CreateXor(LHS, RHS);
2124
2125   // X + X --> X << 1
2126   if (I.getType()->isInteger()) {
2127     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2128
2129     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2130       if (RHSI->getOpcode() == Instruction::Sub)
2131         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2132           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2133     }
2134     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2135       if (LHSI->getOpcode() == Instruction::Sub)
2136         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2137           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2138     }
2139   }
2140
2141   // -A + B  -->  B - A
2142   // -A + -B  -->  -(A + B)
2143   if (Value *LHSV = dyn_castNegVal(LHS)) {
2144     if (LHS->getType()->isIntOrIntVector()) {
2145       if (Value *RHSV = dyn_castNegVal(RHS)) {
2146         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2147         InsertNewInstBefore(NewAdd, I);
2148         return BinaryOperator::CreateNeg(NewAdd);
2149       }
2150     }
2151     
2152     return BinaryOperator::CreateSub(RHS, LHSV);
2153   }
2154
2155   // A + -B  -->  A - B
2156   if (!isa<Constant>(RHS))
2157     if (Value *V = dyn_castNegVal(RHS))
2158       return BinaryOperator::CreateSub(LHS, V);
2159
2160
2161   ConstantInt *C2;
2162   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2163     if (X == RHS)   // X*C + X --> X * (C+1)
2164       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2165
2166     // X*C1 + X*C2 --> X * (C1+C2)
2167     ConstantInt *C1;
2168     if (X == dyn_castFoldableMul(RHS, C1))
2169       return BinaryOperator::CreateMul(X, Add(C1, C2));
2170   }
2171
2172   // X + X*C --> X * (C+1)
2173   if (dyn_castFoldableMul(RHS, C2) == LHS)
2174     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2175
2176   // X + ~X --> -1   since   ~X = -X-1
2177   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2178     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2179   
2180
2181   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2182   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2183     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2184       return R;
2185   
2186   // A+B --> A|B iff A and B have no bits set in common.
2187   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2188     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2189     APInt LHSKnownOne(IT->getBitWidth(), 0);
2190     APInt LHSKnownZero(IT->getBitWidth(), 0);
2191     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2192     if (LHSKnownZero != 0) {
2193       APInt RHSKnownOne(IT->getBitWidth(), 0);
2194       APInt RHSKnownZero(IT->getBitWidth(), 0);
2195       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2196       
2197       // No bits in common -> bitwise or.
2198       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2199         return BinaryOperator::CreateOr(LHS, RHS);
2200     }
2201   }
2202
2203   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2204   if (I.getType()->isIntOrIntVector()) {
2205     Value *W, *X, *Y, *Z;
2206     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2207         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2208       if (W != Y) {
2209         if (W == Z) {
2210           std::swap(Y, Z);
2211         } else if (Y == X) {
2212           std::swap(W, X);
2213         } else if (X == Z) {
2214           std::swap(Y, Z);
2215           std::swap(W, X);
2216         }
2217       }
2218
2219       if (W == Y) {
2220         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2221                                                             LHS->getName()), I);
2222         return BinaryOperator::CreateMul(W, NewAdd);
2223       }
2224     }
2225   }
2226
2227   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2228     Value *X = 0;
2229     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2230       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2231
2232     // (X & FF00) + xx00  -> (X+xx00) & FF00
2233     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2234       Constant *Anded = And(CRHS, C2);
2235       if (Anded == CRHS) {
2236         // See if all bits from the first bit set in the Add RHS up are included
2237         // in the mask.  First, get the rightmost bit.
2238         const APInt& AddRHSV = CRHS->getValue();
2239
2240         // Form a mask of all bits from the lowest bit added through the top.
2241         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2242
2243         // See if the and mask includes all of these bits.
2244         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2245
2246         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2247           // Okay, the xform is safe.  Insert the new add pronto.
2248           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2249                                                             LHS->getName()), I);
2250           return BinaryOperator::CreateAnd(NewAdd, C2);
2251         }
2252       }
2253     }
2254
2255     // Try to fold constant add into select arguments.
2256     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2257       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2258         return R;
2259   }
2260
2261   // add (cast *A to intptrtype) B -> 
2262   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2263   {
2264     CastInst *CI = dyn_cast<CastInst>(LHS);
2265     Value *Other = RHS;
2266     if (!CI) {
2267       CI = dyn_cast<CastInst>(RHS);
2268       Other = LHS;
2269     }
2270     if (CI && CI->getType()->isSized() && 
2271         (CI->getType()->getPrimitiveSizeInBits() == 
2272          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2273         && isa<PointerType>(CI->getOperand(0)->getType())) {
2274       unsigned AS =
2275         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2276       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2277                                       PointerType::get(Type::Int8Ty, AS), I);
2278       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2279       return new PtrToIntInst(I2, CI->getType());
2280     }
2281   }
2282   
2283   // add (select X 0 (sub n A)) A  -->  select X A n
2284   {
2285     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2286     Value *A = RHS;
2287     if (!SI) {
2288       SI = dyn_cast<SelectInst>(RHS);
2289       A = LHS;
2290     }
2291     if (SI && SI->hasOneUse()) {
2292       Value *TV = SI->getTrueValue();
2293       Value *FV = SI->getFalseValue();
2294       Value *N;
2295
2296       // Can we fold the add into the argument of the select?
2297       // We check both true and false select arguments for a matching subtract.
2298       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2299         // Fold the add into the true select value.
2300         return SelectInst::Create(SI->getCondition(), N, A);
2301       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2302         // Fold the add into the false select value.
2303         return SelectInst::Create(SI->getCondition(), A, N);
2304     }
2305   }
2306   
2307   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2308   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2309     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2310       return ReplaceInstUsesWith(I, LHS);
2311
2312   // Check for (add (sext x), y), see if we can merge this into an
2313   // integer add followed by a sext.
2314   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2315     // (add (sext x), cst) --> (sext (add x, cst'))
2316     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2317       Constant *CI = 
2318         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2319       if (LHSConv->hasOneUse() &&
2320           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2321           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2322         // Insert the new, smaller add.
2323         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2324                                                         CI, "addconv");
2325         InsertNewInstBefore(NewAdd, I);
2326         return new SExtInst(NewAdd, I.getType());
2327       }
2328     }
2329     
2330     // (add (sext x), (sext y)) --> (sext (add int x, y))
2331     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2332       // Only do this if x/y have the same type, if at last one of them has a
2333       // single use (so we don't increase the number of sexts), and if the
2334       // integer add will not overflow.
2335       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2336           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2337           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2338                                    RHSConv->getOperand(0))) {
2339         // Insert the new integer add.
2340         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2341                                                         RHSConv->getOperand(0),
2342                                                         "addconv");
2343         InsertNewInstBefore(NewAdd, I);
2344         return new SExtInst(NewAdd, I.getType());
2345       }
2346     }
2347   }
2348   
2349   // Check for (add double (sitofp x), y), see if we can merge this into an
2350   // integer add followed by a promotion.
2351   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2352     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2353     // ... if the constant fits in the integer value.  This is useful for things
2354     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2355     // requires a constant pool load, and generally allows the add to be better
2356     // instcombined.
2357     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2358       Constant *CI = 
2359       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2360       if (LHSConv->hasOneUse() &&
2361           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2362           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2363         // Insert the new integer add.
2364         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2365                                                         CI, "addconv");
2366         InsertNewInstBefore(NewAdd, I);
2367         return new SIToFPInst(NewAdd, I.getType());
2368       }
2369     }
2370     
2371     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2372     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2373       // Only do this if x/y have the same type, if at last one of them has a
2374       // single use (so we don't increase the number of int->fp conversions),
2375       // and if the integer add will not overflow.
2376       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2377           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2378           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2379                                    RHSConv->getOperand(0))) {
2380         // Insert the new integer add.
2381         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2382                                                         RHSConv->getOperand(0),
2383                                                         "addconv");
2384         InsertNewInstBefore(NewAdd, I);
2385         return new SIToFPInst(NewAdd, I.getType());
2386       }
2387     }
2388   }
2389   
2390   return Changed ? &I : 0;
2391 }
2392
2393 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2394   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2395
2396   if (Op0 == Op1 &&                        // sub X, X  -> 0
2397       !I.getType()->isFPOrFPVector())
2398     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2399
2400   // If this is a 'B = x-(-A)', change to B = x+A...
2401   if (Value *V = dyn_castNegVal(Op1))
2402     return BinaryOperator::CreateAdd(Op0, V);
2403
2404   if (isa<UndefValue>(Op0))
2405     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2406   if (isa<UndefValue>(Op1))
2407     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2408
2409   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2410     // Replace (-1 - A) with (~A)...
2411     if (C->isAllOnesValue())
2412       return BinaryOperator::CreateNot(Op1);
2413
2414     // C - ~X == X + (1+C)
2415     Value *X = 0;
2416     if (match(Op1, m_Not(m_Value(X))))
2417       return BinaryOperator::CreateAdd(X, AddOne(C));
2418
2419     // -(X >>u 31) -> (X >>s 31)
2420     // -(X >>s 31) -> (X >>u 31)
2421     if (C->isZero()) {
2422       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2423         if (SI->getOpcode() == Instruction::LShr) {
2424           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2425             // Check to see if we are shifting out everything but the sign bit.
2426             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2427                 SI->getType()->getPrimitiveSizeInBits()-1) {
2428               // Ok, the transformation is safe.  Insert AShr.
2429               return BinaryOperator::Create(Instruction::AShr, 
2430                                           SI->getOperand(0), CU, SI->getName());
2431             }
2432           }
2433         }
2434         else if (SI->getOpcode() == Instruction::AShr) {
2435           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2436             // Check to see if we are shifting out everything but the sign bit.
2437             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2438                 SI->getType()->getPrimitiveSizeInBits()-1) {
2439               // Ok, the transformation is safe.  Insert LShr. 
2440               return BinaryOperator::CreateLShr(
2441                                           SI->getOperand(0), CU, SI->getName());
2442             }
2443           }
2444         }
2445       }
2446     }
2447
2448     // Try to fold constant sub into select arguments.
2449     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2450       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2451         return R;
2452   }
2453
2454   if (I.getType() == Type::Int1Ty)
2455     return BinaryOperator::CreateXor(Op0, Op1);
2456
2457   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2458     if (Op1I->getOpcode() == Instruction::Add &&
2459         !Op0->getType()->isFPOrFPVector()) {
2460       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2461         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2462       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2463         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2464       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2465         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2466           // C1-(X+C2) --> (C1-C2)-X
2467           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2468                                            Op1I->getOperand(0));
2469       }
2470     }
2471
2472     if (Op1I->hasOneUse()) {
2473       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2474       // is not used by anyone else...
2475       //
2476       if (Op1I->getOpcode() == Instruction::Sub &&
2477           !Op1I->getType()->isFPOrFPVector()) {
2478         // Swap the two operands of the subexpr...
2479         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2480         Op1I->setOperand(0, IIOp1);
2481         Op1I->setOperand(1, IIOp0);
2482
2483         // Create the new top level add instruction...
2484         return BinaryOperator::CreateAdd(Op0, Op1);
2485       }
2486
2487       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2488       //
2489       if (Op1I->getOpcode() == Instruction::And &&
2490           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2491         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2492
2493         Value *NewNot =
2494           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2495         return BinaryOperator::CreateAnd(Op0, NewNot);
2496       }
2497
2498       // 0 - (X sdiv C)  -> (X sdiv -C)
2499       if (Op1I->getOpcode() == Instruction::SDiv)
2500         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2501           if (CSI->isZero())
2502             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2503               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2504                                                ConstantExpr::getNeg(DivRHS));
2505
2506       // X - X*C --> X * (1-C)
2507       ConstantInt *C2 = 0;
2508       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2509         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2510         return BinaryOperator::CreateMul(Op0, CP1);
2511       }
2512     }
2513   }
2514
2515   if (!Op0->getType()->isFPOrFPVector())
2516     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2517       if (Op0I->getOpcode() == Instruction::Add) {
2518         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2519           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2520         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2521           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2522       } else if (Op0I->getOpcode() == Instruction::Sub) {
2523         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2524           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2525       }
2526     }
2527
2528   ConstantInt *C1;
2529   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2530     if (X == Op1)  // X*C - X --> X * (C-1)
2531       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2532
2533     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2534     if (X == dyn_castFoldableMul(Op1, C2))
2535       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2536   }
2537   return 0;
2538 }
2539
2540 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2541 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2542 /// TrueIfSigned if the result of the comparison is true when the input value is
2543 /// signed.
2544 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2545                            bool &TrueIfSigned) {
2546   switch (pred) {
2547   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2548     TrueIfSigned = true;
2549     return RHS->isZero();
2550   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2551     TrueIfSigned = true;
2552     return RHS->isAllOnesValue();
2553   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2554     TrueIfSigned = false;
2555     return RHS->isAllOnesValue();
2556   case ICmpInst::ICMP_UGT:
2557     // True if LHS u> RHS and RHS == high-bit-mask - 1
2558     TrueIfSigned = true;
2559     return RHS->getValue() ==
2560       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2561   case ICmpInst::ICMP_UGE: 
2562     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2563     TrueIfSigned = true;
2564     return RHS->getValue().isSignBit();
2565   default:
2566     return false;
2567   }
2568 }
2569
2570 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2571   bool Changed = SimplifyCommutative(I);
2572   Value *Op0 = I.getOperand(0);
2573
2574   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2575     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2576
2577   // Simplify mul instructions with a constant RHS...
2578   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2579     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2580
2581       // ((X << C1)*C2) == (X * (C2 << C1))
2582       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2583         if (SI->getOpcode() == Instruction::Shl)
2584           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2585             return BinaryOperator::CreateMul(SI->getOperand(0),
2586                                              ConstantExpr::getShl(CI, ShOp));
2587
2588       if (CI->isZero())
2589         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2590       if (CI->equalsInt(1))                  // X * 1  == X
2591         return ReplaceInstUsesWith(I, Op0);
2592       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2593         return BinaryOperator::CreateNeg(Op0, I.getName());
2594
2595       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2596       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2597         return BinaryOperator::CreateShl(Op0,
2598                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2599       }
2600     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2601       if (Op1F->isNullValue())
2602         return ReplaceInstUsesWith(I, Op1);
2603
2604       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2605       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2606       if (Op1F->isExactlyValue(1.0))
2607         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2608     } else if (isa<VectorType>(Op1->getType())) {
2609       if (isa<ConstantAggregateZero>(Op1))
2610         return ReplaceInstUsesWith(I, Op1);
2611
2612       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2613         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2614           return BinaryOperator::CreateNeg(Op0, I.getName());
2615
2616         // As above, vector X*splat(1.0) -> X in all defined cases.
2617         if (Constant *Splat = Op1V->getSplatValue()) {
2618           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2619             if (F->isExactlyValue(1.0))
2620               return ReplaceInstUsesWith(I, Op0);
2621           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2622             if (CI->equalsInt(1))
2623               return ReplaceInstUsesWith(I, Op0);
2624         }
2625       }
2626     }
2627     
2628     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2629       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2630           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2631         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2632         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2633                                                      Op1, "tmp");
2634         InsertNewInstBefore(Add, I);
2635         Value *C1C2 = ConstantExpr::getMul(Op1, 
2636                                            cast<Constant>(Op0I->getOperand(1)));
2637         return BinaryOperator::CreateAdd(Add, C1C2);
2638         
2639       }
2640
2641     // Try to fold constant mul into select arguments.
2642     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2643       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2644         return R;
2645
2646     if (isa<PHINode>(Op0))
2647       if (Instruction *NV = FoldOpIntoPhi(I))
2648         return NV;
2649   }
2650
2651   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2652     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2653       return BinaryOperator::CreateMul(Op0v, Op1v);
2654
2655   // (X / Y) *  Y = X - (X % Y)
2656   // (X / Y) * -Y = (X % Y) - X
2657   {
2658     Value *Op1 = I.getOperand(1);
2659     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2660     if (!BO ||
2661         (BO->getOpcode() != Instruction::UDiv && 
2662          BO->getOpcode() != Instruction::SDiv)) {
2663       Op1 = Op0;
2664       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2665     }
2666     Value *Neg = dyn_castNegVal(Op1);
2667     if (BO && BO->hasOneUse() &&
2668         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2669         (BO->getOpcode() == Instruction::UDiv ||
2670          BO->getOpcode() == Instruction::SDiv)) {
2671       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2672
2673       Instruction *Rem;
2674       if (BO->getOpcode() == Instruction::UDiv)
2675         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2676       else
2677         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2678
2679       InsertNewInstBefore(Rem, I);
2680       Rem->takeName(BO);
2681
2682       if (Op1BO == Op1)
2683         return BinaryOperator::CreateSub(Op0BO, Rem);
2684       else
2685         return BinaryOperator::CreateSub(Rem, Op0BO);
2686     }
2687   }
2688
2689   if (I.getType() == Type::Int1Ty)
2690     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2691
2692   // If one of the operands of the multiply is a cast from a boolean value, then
2693   // we know the bool is either zero or one, so this is a 'masking' multiply.
2694   // See if we can simplify things based on how the boolean was originally
2695   // formed.
2696   CastInst *BoolCast = 0;
2697   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2698     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2699       BoolCast = CI;
2700   if (!BoolCast)
2701     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2702       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2703         BoolCast = CI;
2704   if (BoolCast) {
2705     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2706       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2707       const Type *SCOpTy = SCIOp0->getType();
2708       bool TIS = false;
2709       
2710       // If the icmp is true iff the sign bit of X is set, then convert this
2711       // multiply into a shift/and combination.
2712       if (isa<ConstantInt>(SCIOp1) &&
2713           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2714           TIS) {
2715         // Shift the X value right to turn it into "all signbits".
2716         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2717                                           SCOpTy->getPrimitiveSizeInBits()-1);
2718         Value *V =
2719           InsertNewInstBefore(
2720             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2721                                             BoolCast->getOperand(0)->getName()+
2722                                             ".mask"), I);
2723
2724         // If the multiply type is not the same as the source type, sign extend
2725         // or truncate to the multiply type.
2726         if (I.getType() != V->getType()) {
2727           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2728           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2729           Instruction::CastOps opcode = 
2730             (SrcBits == DstBits ? Instruction::BitCast : 
2731              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2732           V = InsertCastBefore(opcode, V, I.getType(), I);
2733         }
2734
2735         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2736         return BinaryOperator::CreateAnd(V, OtherOp);
2737       }
2738     }
2739   }
2740
2741   return Changed ? &I : 0;
2742 }
2743
2744 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2745 /// instruction.
2746 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2747   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2748   
2749   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2750   int NonNullOperand = -1;
2751   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2752     if (ST->isNullValue())
2753       NonNullOperand = 2;
2754   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2755   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2756     if (ST->isNullValue())
2757       NonNullOperand = 1;
2758   
2759   if (NonNullOperand == -1)
2760     return false;
2761   
2762   Value *SelectCond = SI->getOperand(0);
2763   
2764   // Change the div/rem to use 'Y' instead of the select.
2765   I.setOperand(1, SI->getOperand(NonNullOperand));
2766   
2767   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2768   // problem.  However, the select, or the condition of the select may have
2769   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2770   // propagate the known value for the select into other uses of it, and
2771   // propagate a known value of the condition into its other users.
2772   
2773   // If the select and condition only have a single use, don't bother with this,
2774   // early exit.
2775   if (SI->use_empty() && SelectCond->hasOneUse())
2776     return true;
2777   
2778   // Scan the current block backward, looking for other uses of SI.
2779   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2780   
2781   while (BBI != BBFront) {
2782     --BBI;
2783     // If we found a call to a function, we can't assume it will return, so
2784     // information from below it cannot be propagated above it.
2785     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2786       break;
2787     
2788     // Replace uses of the select or its condition with the known values.
2789     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2790          I != E; ++I) {
2791       if (*I == SI) {
2792         *I = SI->getOperand(NonNullOperand);
2793         AddToWorkList(BBI);
2794       } else if (*I == SelectCond) {
2795         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2796                                    ConstantInt::getFalse();
2797         AddToWorkList(BBI);
2798       }
2799     }
2800     
2801     // If we past the instruction, quit looking for it.
2802     if (&*BBI == SI)
2803       SI = 0;
2804     if (&*BBI == SelectCond)
2805       SelectCond = 0;
2806     
2807     // If we ran out of things to eliminate, break out of the loop.
2808     if (SelectCond == 0 && SI == 0)
2809       break;
2810     
2811   }
2812   return true;
2813 }
2814
2815
2816 /// This function implements the transforms on div instructions that work
2817 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2818 /// used by the visitors to those instructions.
2819 /// @brief Transforms common to all three div instructions
2820 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2821   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2822
2823   // undef / X -> 0        for integer.
2824   // undef / X -> undef    for FP (the undef could be a snan).
2825   if (isa<UndefValue>(Op0)) {
2826     if (Op0->getType()->isFPOrFPVector())
2827       return ReplaceInstUsesWith(I, Op0);
2828     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2829   }
2830
2831   // X / undef -> undef
2832   if (isa<UndefValue>(Op1))
2833     return ReplaceInstUsesWith(I, Op1);
2834
2835   return 0;
2836 }
2837
2838 /// This function implements the transforms common to both integer division
2839 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2840 /// division instructions.
2841 /// @brief Common integer divide transforms
2842 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2843   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2844
2845   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2846   if (Op0 == Op1) {
2847     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2848       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2849       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2850       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2851     }
2852
2853     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2854     return ReplaceInstUsesWith(I, CI);
2855   }
2856   
2857   if (Instruction *Common = commonDivTransforms(I))
2858     return Common;
2859   
2860   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2861   // This does not apply for fdiv.
2862   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2863     return &I;
2864
2865   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2866     // div X, 1 == X
2867     if (RHS->equalsInt(1))
2868       return ReplaceInstUsesWith(I, Op0);
2869
2870     // (X / C1) / C2  -> X / (C1*C2)
2871     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2872       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2873         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2874           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2875             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2876           else 
2877             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2878                                           Multiply(RHS, LHSRHS));
2879         }
2880
2881     if (!RHS->isZero()) { // avoid X udiv 0
2882       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2883         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2884           return R;
2885       if (isa<PHINode>(Op0))
2886         if (Instruction *NV = FoldOpIntoPhi(I))
2887           return NV;
2888     }
2889   }
2890
2891   // 0 / X == 0, we don't need to preserve faults!
2892   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2893     if (LHS->equalsInt(0))
2894       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2895
2896   // It can't be division by zero, hence it must be division by one.
2897   if (I.getType() == Type::Int1Ty)
2898     return ReplaceInstUsesWith(I, Op0);
2899
2900   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2901     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2902       // div X, 1 == X
2903       if (X->isOne())
2904         return ReplaceInstUsesWith(I, Op0);
2905   }
2906
2907   return 0;
2908 }
2909
2910 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2911   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2912
2913   // Handle the integer div common cases
2914   if (Instruction *Common = commonIDivTransforms(I))
2915     return Common;
2916
2917   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2918     // X udiv C^2 -> X >> C
2919     // Check to see if this is an unsigned division with an exact power of 2,
2920     // if so, convert to a right shift.
2921     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2922       return BinaryOperator::CreateLShr(Op0, 
2923                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2924
2925     // X udiv C, where C >= signbit
2926     if (C->getValue().isNegative()) {
2927       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2928                                       I);
2929       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2930                                 ConstantInt::get(I.getType(), 1));
2931     }
2932   }
2933
2934   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2935   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2936     if (RHSI->getOpcode() == Instruction::Shl &&
2937         isa<ConstantInt>(RHSI->getOperand(0))) {
2938       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2939       if (C1.isPowerOf2()) {
2940         Value *N = RHSI->getOperand(1);
2941         const Type *NTy = N->getType();
2942         if (uint32_t C2 = C1.logBase2()) {
2943           Constant *C2V = ConstantInt::get(NTy, C2);
2944           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2945         }
2946         return BinaryOperator::CreateLShr(Op0, N);
2947       }
2948     }
2949   }
2950   
2951   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2952   // where C1&C2 are powers of two.
2953   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2954     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2955       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2956         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2957         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2958           // Compute the shift amounts
2959           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2960           // Construct the "on true" case of the select
2961           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2962           Instruction *TSI = BinaryOperator::CreateLShr(
2963                                                  Op0, TC, SI->getName()+".t");
2964           TSI = InsertNewInstBefore(TSI, I);
2965   
2966           // Construct the "on false" case of the select
2967           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2968           Instruction *FSI = BinaryOperator::CreateLShr(
2969                                                  Op0, FC, SI->getName()+".f");
2970           FSI = InsertNewInstBefore(FSI, I);
2971
2972           // construct the select instruction and return it.
2973           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2974         }
2975       }
2976   return 0;
2977 }
2978
2979 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2980   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2981
2982   // Handle the integer div common cases
2983   if (Instruction *Common = commonIDivTransforms(I))
2984     return Common;
2985
2986   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2987     // sdiv X, -1 == -X
2988     if (RHS->isAllOnesValue())
2989       return BinaryOperator::CreateNeg(Op0);
2990   }
2991
2992   // If the sign bits of both operands are zero (i.e. we can prove they are
2993   // unsigned inputs), turn this into a udiv.
2994   if (I.getType()->isInteger()) {
2995     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2996     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2997       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2998       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2999     }
3000   }      
3001   
3002   return 0;
3003 }
3004
3005 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3006   return commonDivTransforms(I);
3007 }
3008
3009 /// This function implements the transforms on rem instructions that work
3010 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3011 /// is used by the visitors to those instructions.
3012 /// @brief Transforms common to all three rem instructions
3013 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3014   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3015
3016   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3017     if (I.getType()->isFPOrFPVector())
3018       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3019     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3020   }
3021   if (isa<UndefValue>(Op1))
3022     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3023
3024   // Handle cases involving: rem X, (select Cond, Y, Z)
3025   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3026     return &I;
3027
3028   return 0;
3029 }
3030
3031 /// This function implements the transforms common to both integer remainder
3032 /// instructions (urem and srem). It is called by the visitors to those integer
3033 /// remainder instructions.
3034 /// @brief Common integer remainder transforms
3035 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3036   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3037
3038   if (Instruction *common = commonRemTransforms(I))
3039     return common;
3040
3041   // 0 % X == 0 for integer, we don't need to preserve faults!
3042   if (Constant *LHS = dyn_cast<Constant>(Op0))
3043     if (LHS->isNullValue())
3044       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3045
3046   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3047     // X % 0 == undef, we don't need to preserve faults!
3048     if (RHS->equalsInt(0))
3049       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3050     
3051     if (RHS->equalsInt(1))  // X % 1 == 0
3052       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3053
3054     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3055       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3056         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3057           return R;
3058       } else if (isa<PHINode>(Op0I)) {
3059         if (Instruction *NV = FoldOpIntoPhi(I))
3060           return NV;
3061       }
3062
3063       // See if we can fold away this rem instruction.
3064       if (SimplifyDemandedInstructionBits(I))
3065         return &I;
3066     }
3067   }
3068
3069   return 0;
3070 }
3071
3072 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3073   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3074
3075   if (Instruction *common = commonIRemTransforms(I))
3076     return common;
3077   
3078   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3079     // X urem C^2 -> X and C
3080     // Check to see if this is an unsigned remainder with an exact power of 2,
3081     // if so, convert to a bitwise and.
3082     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3083       if (C->getValue().isPowerOf2())
3084         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3085   }
3086
3087   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3088     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3089     if (RHSI->getOpcode() == Instruction::Shl &&
3090         isa<ConstantInt>(RHSI->getOperand(0))) {
3091       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3092         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3093         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3094                                                                    "tmp"), I);
3095         return BinaryOperator::CreateAnd(Op0, Add);
3096       }
3097     }
3098   }
3099
3100   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3101   // where C1&C2 are powers of two.
3102   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3103     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3104       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3105         // STO == 0 and SFO == 0 handled above.
3106         if ((STO->getValue().isPowerOf2()) && 
3107             (SFO->getValue().isPowerOf2())) {
3108           Value *TrueAnd = InsertNewInstBefore(
3109             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3110           Value *FalseAnd = InsertNewInstBefore(
3111             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3112           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3113         }
3114       }
3115   }
3116   
3117   return 0;
3118 }
3119
3120 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3121   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3122
3123   // Handle the integer rem common cases
3124   if (Instruction *common = commonIRemTransforms(I))
3125     return common;
3126   
3127   if (Value *RHSNeg = dyn_castNegVal(Op1))
3128     if (!isa<Constant>(RHSNeg) ||
3129         (isa<ConstantInt>(RHSNeg) &&
3130          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3131       // X % -Y -> X % Y
3132       AddUsesToWorkList(I);
3133       I.setOperand(1, RHSNeg);
3134       return &I;
3135     }
3136
3137   // If the sign bits of both operands are zero (i.e. we can prove they are
3138   // unsigned inputs), turn this into a urem.
3139   if (I.getType()->isInteger()) {
3140     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3141     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3142       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3143       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3144     }
3145   }
3146
3147   // If it's a constant vector, flip any negative values positive.
3148   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3149     unsigned VWidth = RHSV->getNumOperands();
3150
3151     bool hasNegative = false;
3152     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3153       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3154         if (RHS->getValue().isNegative())
3155           hasNegative = true;
3156
3157     if (hasNegative) {
3158       std::vector<Constant *> Elts(VWidth);
3159       for (unsigned i = 0; i != VWidth; ++i) {
3160         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3161           if (RHS->getValue().isNegative())
3162             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3163           else
3164             Elts[i] = RHS;
3165         }
3166       }
3167
3168       Constant *NewRHSV = ConstantVector::get(Elts);
3169       if (NewRHSV != RHSV) {
3170         AddUsesToWorkList(I);
3171         I.setOperand(1, NewRHSV);
3172         return &I;
3173       }
3174     }
3175   }
3176
3177   return 0;
3178 }
3179
3180 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3181   return commonRemTransforms(I);
3182 }
3183
3184 // isOneBitSet - Return true if there is exactly one bit set in the specified
3185 // constant.
3186 static bool isOneBitSet(const ConstantInt *CI) {
3187   return CI->getValue().isPowerOf2();
3188 }
3189
3190 // isHighOnes - Return true if the constant is of the form 1+0+.
3191 // This is the same as lowones(~X).
3192 static bool isHighOnes(const ConstantInt *CI) {
3193   return (~CI->getValue() + 1).isPowerOf2();
3194 }
3195
3196 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3197 /// are carefully arranged to allow folding of expressions such as:
3198 ///
3199 ///      (A < B) | (A > B) --> (A != B)
3200 ///
3201 /// Note that this is only valid if the first and second predicates have the
3202 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3203 ///
3204 /// Three bits are used to represent the condition, as follows:
3205 ///   0  A > B
3206 ///   1  A == B
3207 ///   2  A < B
3208 ///
3209 /// <=>  Value  Definition
3210 /// 000     0   Always false
3211 /// 001     1   A >  B
3212 /// 010     2   A == B
3213 /// 011     3   A >= B
3214 /// 100     4   A <  B
3215 /// 101     5   A != B
3216 /// 110     6   A <= B
3217 /// 111     7   Always true
3218 ///  
3219 static unsigned getICmpCode(const ICmpInst *ICI) {
3220   switch (ICI->getPredicate()) {
3221     // False -> 0
3222   case ICmpInst::ICMP_UGT: return 1;  // 001
3223   case ICmpInst::ICMP_SGT: return 1;  // 001
3224   case ICmpInst::ICMP_EQ:  return 2;  // 010
3225   case ICmpInst::ICMP_UGE: return 3;  // 011
3226   case ICmpInst::ICMP_SGE: return 3;  // 011
3227   case ICmpInst::ICMP_ULT: return 4;  // 100
3228   case ICmpInst::ICMP_SLT: return 4;  // 100
3229   case ICmpInst::ICMP_NE:  return 5;  // 101
3230   case ICmpInst::ICMP_ULE: return 6;  // 110
3231   case ICmpInst::ICMP_SLE: return 6;  // 110
3232     // True -> 7
3233   default:
3234     assert(0 && "Invalid ICmp predicate!");
3235     return 0;
3236   }
3237 }
3238
3239 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3240 /// predicate into a three bit mask. It also returns whether it is an ordered
3241 /// predicate by reference.
3242 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3243   isOrdered = false;
3244   switch (CC) {
3245   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3246   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3247   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3248   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3249   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3250   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3251   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3252   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3253   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3254   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3255   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3256   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3257   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3258   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3259     // True -> 7
3260   default:
3261     // Not expecting FCMP_FALSE and FCMP_TRUE;
3262     assert(0 && "Unexpected FCmp predicate!");
3263     return 0;
3264   }
3265 }
3266
3267 /// getICmpValue - This is the complement of getICmpCode, which turns an
3268 /// opcode and two operands into either a constant true or false, or a brand 
3269 /// new ICmp instruction. The sign is passed in to determine which kind
3270 /// of predicate to use in the new icmp instruction.
3271 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3272   switch (code) {
3273   default: assert(0 && "Illegal ICmp code!");
3274   case  0: return ConstantInt::getFalse();
3275   case  1: 
3276     if (sign)
3277       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3278     else
3279       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3280   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3281   case  3: 
3282     if (sign)
3283       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3284     else
3285       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3286   case  4: 
3287     if (sign)
3288       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3289     else
3290       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3291   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3292   case  6: 
3293     if (sign)
3294       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3295     else
3296       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3297   case  7: return ConstantInt::getTrue();
3298   }
3299 }
3300
3301 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3302 /// opcode and two operands into either a FCmp instruction. isordered is passed
3303 /// in to determine which kind of predicate to use in the new fcmp instruction.
3304 static Value *getFCmpValue(bool isordered, unsigned code,
3305                            Value *LHS, Value *RHS) {
3306   switch (code) {
3307   default: assert(0 && "Illegal FCmp code!");
3308   case  0:
3309     if (isordered)
3310       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3311     else
3312       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3313   case  1: 
3314     if (isordered)
3315       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3316     else
3317       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3318   case  2: 
3319     if (isordered)
3320       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3321     else
3322       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3323   case  3: 
3324     if (isordered)
3325       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3326     else
3327       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3328   case  4: 
3329     if (isordered)
3330       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3331     else
3332       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3333   case  5: 
3334     if (isordered)
3335       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3336     else
3337       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3338   case  6: 
3339     if (isordered)
3340       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3341     else
3342       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3343   case  7: return ConstantInt::getTrue();
3344   }
3345 }
3346
3347 /// PredicatesFoldable - Return true if both predicates match sign or if at
3348 /// least one of them is an equality comparison (which is signless).
3349 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3350   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3351          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3352          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3353 }
3354
3355 namespace { 
3356 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3357 struct FoldICmpLogical {
3358   InstCombiner &IC;
3359   Value *LHS, *RHS;
3360   ICmpInst::Predicate pred;
3361   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3362     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3363       pred(ICI->getPredicate()) {}
3364   bool shouldApply(Value *V) const {
3365     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3366       if (PredicatesFoldable(pred, ICI->getPredicate()))
3367         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3368                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3369     return false;
3370   }
3371   Instruction *apply(Instruction &Log) const {
3372     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3373     if (ICI->getOperand(0) != LHS) {
3374       assert(ICI->getOperand(1) == LHS);
3375       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3376     }
3377
3378     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3379     unsigned LHSCode = getICmpCode(ICI);
3380     unsigned RHSCode = getICmpCode(RHSICI);
3381     unsigned Code;
3382     switch (Log.getOpcode()) {
3383     case Instruction::And: Code = LHSCode & RHSCode; break;
3384     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3385     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3386     default: assert(0 && "Illegal logical opcode!"); return 0;
3387     }
3388
3389     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3390                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3391       
3392     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3393     if (Instruction *I = dyn_cast<Instruction>(RV))
3394       return I;
3395     // Otherwise, it's a constant boolean value...
3396     return IC.ReplaceInstUsesWith(Log, RV);
3397   }
3398 };
3399 } // end anonymous namespace
3400
3401 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3402 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3403 // guaranteed to be a binary operator.
3404 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3405                                     ConstantInt *OpRHS,
3406                                     ConstantInt *AndRHS,
3407                                     BinaryOperator &TheAnd) {
3408   Value *X = Op->getOperand(0);
3409   Constant *Together = 0;
3410   if (!Op->isShift())
3411     Together = And(AndRHS, OpRHS);
3412
3413   switch (Op->getOpcode()) {
3414   case Instruction::Xor:
3415     if (Op->hasOneUse()) {
3416       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3417       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3418       InsertNewInstBefore(And, TheAnd);
3419       And->takeName(Op);
3420       return BinaryOperator::CreateXor(And, Together);
3421     }
3422     break;
3423   case Instruction::Or:
3424     if (Together == AndRHS) // (X | C) & C --> C
3425       return ReplaceInstUsesWith(TheAnd, AndRHS);
3426
3427     if (Op->hasOneUse() && Together != OpRHS) {
3428       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3429       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3430       InsertNewInstBefore(Or, TheAnd);
3431       Or->takeName(Op);
3432       return BinaryOperator::CreateAnd(Or, AndRHS);
3433     }
3434     break;
3435   case Instruction::Add:
3436     if (Op->hasOneUse()) {
3437       // Adding a one to a single bit bit-field should be turned into an XOR
3438       // of the bit.  First thing to check is to see if this AND is with a
3439       // single bit constant.
3440       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3441
3442       // If there is only one bit set...
3443       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3444         // Ok, at this point, we know that we are masking the result of the
3445         // ADD down to exactly one bit.  If the constant we are adding has
3446         // no bits set below this bit, then we can eliminate the ADD.
3447         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3448
3449         // Check to see if any bits below the one bit set in AndRHSV are set.
3450         if ((AddRHS & (AndRHSV-1)) == 0) {
3451           // If not, the only thing that can effect the output of the AND is
3452           // the bit specified by AndRHSV.  If that bit is set, the effect of
3453           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3454           // no effect.
3455           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3456             TheAnd.setOperand(0, X);
3457             return &TheAnd;
3458           } else {
3459             // Pull the XOR out of the AND.
3460             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3461             InsertNewInstBefore(NewAnd, TheAnd);
3462             NewAnd->takeName(Op);
3463             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3464           }
3465         }
3466       }
3467     }
3468     break;
3469
3470   case Instruction::Shl: {
3471     // We know that the AND will not produce any of the bits shifted in, so if
3472     // the anded constant includes them, clear them now!
3473     //
3474     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3475     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3476     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3477     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3478
3479     if (CI->getValue() == ShlMask) { 
3480     // Masking out bits that the shift already masks
3481       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3482     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3483       TheAnd.setOperand(1, CI);
3484       return &TheAnd;
3485     }
3486     break;
3487   }
3488   case Instruction::LShr:
3489   {
3490     // We know that the AND will not produce any of the bits shifted in, so if
3491     // the anded constant includes them, clear them now!  This only applies to
3492     // unsigned shifts, because a signed shr may bring in set bits!
3493     //
3494     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3495     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3496     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3497     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3498
3499     if (CI->getValue() == ShrMask) {   
3500     // Masking out bits that the shift already masks.
3501       return ReplaceInstUsesWith(TheAnd, Op);
3502     } else if (CI != AndRHS) {
3503       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3504       return &TheAnd;
3505     }
3506     break;
3507   }
3508   case Instruction::AShr:
3509     // Signed shr.
3510     // See if this is shifting in some sign extension, then masking it out
3511     // with an and.
3512     if (Op->hasOneUse()) {
3513       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3514       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3515       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3516       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3517       if (C == AndRHS) {          // Masking out bits shifted in.
3518         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3519         // Make the argument unsigned.
3520         Value *ShVal = Op->getOperand(0);
3521         ShVal = InsertNewInstBefore(
3522             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3523                                    Op->getName()), TheAnd);
3524         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3525       }
3526     }
3527     break;
3528   }
3529   return 0;
3530 }
3531
3532
3533 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3534 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3535 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3536 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3537 /// insert new instructions.
3538 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3539                                            bool isSigned, bool Inside, 
3540                                            Instruction &IB) {
3541   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3542             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3543          "Lo is not <= Hi in range emission code!");
3544     
3545   if (Inside) {
3546     if (Lo == Hi)  // Trivially false.
3547       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3548
3549     // V >= Min && V < Hi --> V < Hi
3550     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3551       ICmpInst::Predicate pred = (isSigned ? 
3552         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3553       return new ICmpInst(pred, V, Hi);
3554     }
3555
3556     // Emit V-Lo <u Hi-Lo
3557     Constant *NegLo = ConstantExpr::getNeg(Lo);
3558     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3559     InsertNewInstBefore(Add, IB);
3560     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3561     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3562   }
3563
3564   if (Lo == Hi)  // Trivially true.
3565     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3566
3567   // V < Min || V >= Hi -> V > Hi-1
3568   Hi = SubOne(cast<ConstantInt>(Hi));
3569   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3570     ICmpInst::Predicate pred = (isSigned ? 
3571         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3572     return new ICmpInst(pred, V, Hi);
3573   }
3574
3575   // Emit V-Lo >u Hi-1-Lo
3576   // Note that Hi has already had one subtracted from it, above.
3577   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3578   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3579   InsertNewInstBefore(Add, IB);
3580   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3581   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3582 }
3583
3584 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3585 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3586 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3587 // not, since all 1s are not contiguous.
3588 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3589   const APInt& V = Val->getValue();
3590   uint32_t BitWidth = Val->getType()->getBitWidth();
3591   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3592
3593   // look for the first zero bit after the run of ones
3594   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3595   // look for the first non-zero bit
3596   ME = V.getActiveBits(); 
3597   return true;
3598 }
3599
3600 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3601 /// where isSub determines whether the operator is a sub.  If we can fold one of
3602 /// the following xforms:
3603 /// 
3604 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3605 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3606 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3607 ///
3608 /// return (A +/- B).
3609 ///
3610 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3611                                         ConstantInt *Mask, bool isSub,
3612                                         Instruction &I) {
3613   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3614   if (!LHSI || LHSI->getNumOperands() != 2 ||
3615       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3616
3617   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3618
3619   switch (LHSI->getOpcode()) {
3620   default: return 0;
3621   case Instruction::And:
3622     if (And(N, Mask) == Mask) {
3623       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3624       if ((Mask->getValue().countLeadingZeros() + 
3625            Mask->getValue().countPopulation()) == 
3626           Mask->getValue().getBitWidth())
3627         break;
3628
3629       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3630       // part, we don't need any explicit masks to take them out of A.  If that
3631       // is all N is, ignore it.
3632       uint32_t MB = 0, ME = 0;
3633       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3634         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3635         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3636         if (MaskedValueIsZero(RHS, Mask))
3637           break;
3638       }
3639     }
3640     return 0;
3641   case Instruction::Or:
3642   case Instruction::Xor:
3643     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3644     if ((Mask->getValue().countLeadingZeros() + 
3645          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3646         && And(N, Mask)->isZero())
3647       break;
3648     return 0;
3649   }
3650   
3651   Instruction *New;
3652   if (isSub)
3653     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3654   else
3655     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3656   return InsertNewInstBefore(New, I);
3657 }
3658
3659 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3660 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3661                                           ICmpInst *LHS, ICmpInst *RHS) {
3662   Value *Val, *Val2;
3663   ConstantInt *LHSCst, *RHSCst;
3664   ICmpInst::Predicate LHSCC, RHSCC;
3665   
3666   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3667   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3668       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3669     return 0;
3670   
3671   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3672   // where C is a power of 2
3673   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3674       LHSCst->getValue().isPowerOf2()) {
3675     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3676     InsertNewInstBefore(NewOr, I);
3677     return new ICmpInst(LHSCC, NewOr, LHSCst);
3678   }
3679   
3680   // From here on, we only handle:
3681   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3682   if (Val != Val2) return 0;
3683   
3684   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3685   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3686       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3687       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3688       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3689     return 0;
3690   
3691   // We can't fold (ugt x, C) & (sgt x, C2).
3692   if (!PredicatesFoldable(LHSCC, RHSCC))
3693     return 0;
3694     
3695   // Ensure that the larger constant is on the RHS.
3696   bool ShouldSwap;
3697   if (ICmpInst::isSignedPredicate(LHSCC) ||
3698       (ICmpInst::isEquality(LHSCC) && 
3699        ICmpInst::isSignedPredicate(RHSCC)))
3700     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3701   else
3702     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3703     
3704   if (ShouldSwap) {
3705     std::swap(LHS, RHS);
3706     std::swap(LHSCst, RHSCst);
3707     std::swap(LHSCC, RHSCC);
3708   }
3709
3710   // At this point, we know we have have two icmp instructions
3711   // comparing a value against two constants and and'ing the result
3712   // together.  Because of the above check, we know that we only have
3713   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3714   // (from the FoldICmpLogical check above), that the two constants 
3715   // are not equal and that the larger constant is on the RHS
3716   assert(LHSCst != RHSCst && "Compares not folded above?");
3717
3718   switch (LHSCC) {
3719   default: assert(0 && "Unknown integer condition code!");
3720   case ICmpInst::ICMP_EQ:
3721     switch (RHSCC) {
3722     default: assert(0 && "Unknown integer condition code!");
3723     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3724     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3725     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3726       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3727     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3728     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3729     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3730       return ReplaceInstUsesWith(I, LHS);
3731     }
3732   case ICmpInst::ICMP_NE:
3733     switch (RHSCC) {
3734     default: assert(0 && "Unknown integer condition code!");
3735     case ICmpInst::ICMP_ULT:
3736       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3737         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3738       break;                        // (X != 13 & X u< 15) -> no change
3739     case ICmpInst::ICMP_SLT:
3740       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3741         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3742       break;                        // (X != 13 & X s< 15) -> no change
3743     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3744     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3745     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3746       return ReplaceInstUsesWith(I, RHS);
3747     case ICmpInst::ICMP_NE:
3748       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3749         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3750         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3751                                                      Val->getName()+".off");
3752         InsertNewInstBefore(Add, I);
3753         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3754                             ConstantInt::get(Add->getType(), 1));
3755       }
3756       break;                        // (X != 13 & X != 15) -> no change
3757     }
3758     break;
3759   case ICmpInst::ICMP_ULT:
3760     switch (RHSCC) {
3761     default: assert(0 && "Unknown integer condition code!");
3762     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3763     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3764       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3765     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3766       break;
3767     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3768     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3769       return ReplaceInstUsesWith(I, LHS);
3770     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3771       break;
3772     }
3773     break;
3774   case ICmpInst::ICMP_SLT:
3775     switch (RHSCC) {
3776     default: assert(0 && "Unknown integer condition code!");
3777     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3778     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3779       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3780     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3781       break;
3782     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3783     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3784       return ReplaceInstUsesWith(I, LHS);
3785     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3786       break;
3787     }
3788     break;
3789   case ICmpInst::ICMP_UGT:
3790     switch (RHSCC) {
3791     default: assert(0 && "Unknown integer condition code!");
3792     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3793     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3794       return ReplaceInstUsesWith(I, RHS);
3795     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3796       break;
3797     case ICmpInst::ICMP_NE:
3798       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3799         return new ICmpInst(LHSCC, Val, RHSCst);
3800       break;                        // (X u> 13 & X != 15) -> no change
3801     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3802       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3803     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3804       break;
3805     }
3806     break;
3807   case ICmpInst::ICMP_SGT:
3808     switch (RHSCC) {
3809     default: assert(0 && "Unknown integer condition code!");
3810     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3811     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3812       return ReplaceInstUsesWith(I, RHS);
3813     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3814       break;
3815     case ICmpInst::ICMP_NE:
3816       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3817         return new ICmpInst(LHSCC, Val, RHSCst);
3818       break;                        // (X s> 13 & X != 15) -> no change
3819     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3820       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3821     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3822       break;
3823     }
3824     break;
3825   }
3826  
3827   return 0;
3828 }
3829
3830
3831 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3832   bool Changed = SimplifyCommutative(I);
3833   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3834
3835   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3836     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3837
3838   // and X, X = X
3839   if (Op0 == Op1)
3840     return ReplaceInstUsesWith(I, Op1);
3841
3842   // See if we can simplify any instructions used by the instruction whose sole 
3843   // purpose is to compute bits we don't care about.
3844   if (!isa<VectorType>(I.getType())) {
3845     if (SimplifyDemandedInstructionBits(I))
3846       return &I;
3847   } else {
3848     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3849       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3850         return ReplaceInstUsesWith(I, I.getOperand(0));
3851     } else if (isa<ConstantAggregateZero>(Op1)) {
3852       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3853     }
3854   }
3855   
3856   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3857     const APInt& AndRHSMask = AndRHS->getValue();
3858     APInt NotAndRHS(~AndRHSMask);
3859
3860     // Optimize a variety of ((val OP C1) & C2) combinations...
3861     if (isa<BinaryOperator>(Op0)) {
3862       Instruction *Op0I = cast<Instruction>(Op0);
3863       Value *Op0LHS = Op0I->getOperand(0);
3864       Value *Op0RHS = Op0I->getOperand(1);
3865       switch (Op0I->getOpcode()) {
3866       case Instruction::Xor:
3867       case Instruction::Or:
3868         // If the mask is only needed on one incoming arm, push it up.
3869         if (Op0I->hasOneUse()) {
3870           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3871             // Not masking anything out for the LHS, move to RHS.
3872             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3873                                                    Op0RHS->getName()+".masked");
3874             InsertNewInstBefore(NewRHS, I);
3875             return BinaryOperator::Create(
3876                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3877           }
3878           if (!isa<Constant>(Op0RHS) &&
3879               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3880             // Not masking anything out for the RHS, move to LHS.
3881             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3882                                                    Op0LHS->getName()+".masked");
3883             InsertNewInstBefore(NewLHS, I);
3884             return BinaryOperator::Create(
3885                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3886           }
3887         }
3888
3889         break;
3890       case Instruction::Add:
3891         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3892         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3893         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3894         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3895           return BinaryOperator::CreateAnd(V, AndRHS);
3896         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3897           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3898         break;
3899
3900       case Instruction::Sub:
3901         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3902         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3903         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3904         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3905           return BinaryOperator::CreateAnd(V, AndRHS);
3906
3907         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3908         // has 1's for all bits that the subtraction with A might affect.
3909         if (Op0I->hasOneUse()) {
3910           uint32_t BitWidth = AndRHSMask.getBitWidth();
3911           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3912           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3913
3914           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3915           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3916               MaskedValueIsZero(Op0LHS, Mask)) {
3917             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3918             InsertNewInstBefore(NewNeg, I);
3919             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3920           }
3921         }
3922         break;
3923
3924       case Instruction::Shl:
3925       case Instruction::LShr:
3926         // (1 << x) & 1 --> zext(x == 0)
3927         // (1 >> x) & 1 --> zext(x == 0)
3928         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3929           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3930                                            Constant::getNullValue(I.getType()));
3931           InsertNewInstBefore(NewICmp, I);
3932           return new ZExtInst(NewICmp, I.getType());
3933         }
3934         break;
3935       }
3936
3937       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3938         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3939           return Res;
3940     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3941       // If this is an integer truncation or change from signed-to-unsigned, and
3942       // if the source is an and/or with immediate, transform it.  This
3943       // frequently occurs for bitfield accesses.
3944       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3945         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3946             CastOp->getNumOperands() == 2)
3947           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3948             if (CastOp->getOpcode() == Instruction::And) {
3949               // Change: and (cast (and X, C1) to T), C2
3950               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3951               // This will fold the two constants together, which may allow 
3952               // other simplifications.
3953               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3954                 CastOp->getOperand(0), I.getType(), 
3955                 CastOp->getName()+".shrunk");
3956               NewCast = InsertNewInstBefore(NewCast, I);
3957               // trunc_or_bitcast(C1)&C2
3958               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3959               C3 = ConstantExpr::getAnd(C3, AndRHS);
3960               return BinaryOperator::CreateAnd(NewCast, C3);
3961             } else if (CastOp->getOpcode() == Instruction::Or) {
3962               // Change: and (cast (or X, C1) to T), C2
3963               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3964               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3965               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3966                 return ReplaceInstUsesWith(I, AndRHS);
3967             }
3968           }
3969       }
3970     }
3971
3972     // Try to fold constant and into select arguments.
3973     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3974       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3975         return R;
3976     if (isa<PHINode>(Op0))
3977       if (Instruction *NV = FoldOpIntoPhi(I))
3978         return NV;
3979   }
3980
3981   Value *Op0NotVal = dyn_castNotVal(Op0);
3982   Value *Op1NotVal = dyn_castNotVal(Op1);
3983
3984   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3985     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3986
3987   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3988   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3989     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3990                                                I.getName()+".demorgan");
3991     InsertNewInstBefore(Or, I);
3992     return BinaryOperator::CreateNot(Or);
3993   }
3994   
3995   {
3996     Value *A = 0, *B = 0, *C = 0, *D = 0;
3997     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3998       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3999         return ReplaceInstUsesWith(I, Op1);
4000     
4001       // (A|B) & ~(A&B) -> A^B
4002       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4003         if ((A == C && B == D) || (A == D && B == C))
4004           return BinaryOperator::CreateXor(A, B);
4005       }
4006     }
4007     
4008     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4009       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4010         return ReplaceInstUsesWith(I, Op0);
4011
4012       // ~(A&B) & (A|B) -> A^B
4013       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4014         if ((A == C && B == D) || (A == D && B == C))
4015           return BinaryOperator::CreateXor(A, B);
4016       }
4017     }
4018     
4019     if (Op0->hasOneUse() &&
4020         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4021       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4022         I.swapOperands();     // Simplify below
4023         std::swap(Op0, Op1);
4024       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4025         cast<BinaryOperator>(Op0)->swapOperands();
4026         I.swapOperands();     // Simplify below
4027         std::swap(Op0, Op1);
4028       }
4029     }
4030
4031     if (Op1->hasOneUse() &&
4032         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4033       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4034         cast<BinaryOperator>(Op1)->swapOperands();
4035         std::swap(A, B);
4036       }
4037       if (A == Op0) {                                // A&(A^B) -> A & ~B
4038         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4039         InsertNewInstBefore(NotB, I);
4040         return BinaryOperator::CreateAnd(A, NotB);
4041       }
4042     }
4043
4044     // (A&((~A)|B)) -> A&B
4045     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4046         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4047       return BinaryOperator::CreateAnd(A, Op1);
4048     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4049         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4050       return BinaryOperator::CreateAnd(A, Op0);
4051   }
4052   
4053   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4054     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4055     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4056       return R;
4057
4058     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4059       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4060         return Res;
4061   }
4062
4063   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4064   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4065     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4066       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4067         const Type *SrcTy = Op0C->getOperand(0)->getType();
4068         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4069             // Only do this if the casts both really cause code to be generated.
4070             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4071                               I.getType(), TD) &&
4072             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4073                               I.getType(), TD)) {
4074           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4075                                                          Op1C->getOperand(0),
4076                                                          I.getName());
4077           InsertNewInstBefore(NewOp, I);
4078           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4079         }
4080       }
4081     
4082   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4083   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4084     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4085       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4086           SI0->getOperand(1) == SI1->getOperand(1) &&
4087           (SI0->hasOneUse() || SI1->hasOneUse())) {
4088         Instruction *NewOp =
4089           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4090                                                         SI1->getOperand(0),
4091                                                         SI0->getName()), I);
4092         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4093                                       SI1->getOperand(1));
4094       }
4095   }
4096
4097   // If and'ing two fcmp, try combine them into one.
4098   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4099     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4100       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4101           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4102         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4103         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4104           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4105             // If either of the constants are nans, then the whole thing returns
4106             // false.
4107             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4108               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4109             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4110                                 RHS->getOperand(0));
4111           }
4112       } else {
4113         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4114         FCmpInst::Predicate Op0CC, Op1CC;
4115         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4116             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4117           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4118             // Swap RHS operands to match LHS.
4119             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4120             std::swap(Op1LHS, Op1RHS);
4121           }
4122           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4123             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4124             if (Op0CC == Op1CC)
4125               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4126             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4127                      Op1CC == FCmpInst::FCMP_FALSE)
4128               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4129             else if (Op0CC == FCmpInst::FCMP_TRUE)
4130               return ReplaceInstUsesWith(I, Op1);
4131             else if (Op1CC == FCmpInst::FCMP_TRUE)
4132               return ReplaceInstUsesWith(I, Op0);
4133             bool Op0Ordered;
4134             bool Op1Ordered;
4135             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4136             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4137             if (Op1Pred == 0) {
4138               std::swap(Op0, Op1);
4139               std::swap(Op0Pred, Op1Pred);
4140               std::swap(Op0Ordered, Op1Ordered);
4141             }
4142             if (Op0Pred == 0) {
4143               // uno && ueq -> uno && (uno || eq) -> ueq
4144               // ord && olt -> ord && (ord && lt) -> olt
4145               if (Op0Ordered == Op1Ordered)
4146                 return ReplaceInstUsesWith(I, Op1);
4147               // uno && oeq -> uno && (ord && eq) -> false
4148               // uno && ord -> false
4149               if (!Op0Ordered)
4150                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4151               // ord && ueq -> ord && (uno || eq) -> oeq
4152               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4153                                                     Op0LHS, Op0RHS));
4154             }
4155           }
4156         }
4157       }
4158     }
4159   }
4160
4161   return Changed ? &I : 0;
4162 }
4163
4164 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4165 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4166 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4167 /// the expression came from the corresponding "byte swapped" byte in some other
4168 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4169 /// we know that the expression deposits the low byte of %X into the high byte
4170 /// of the bswap result and that all other bytes are zero.  This expression is
4171 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4172 /// match.
4173 ///
4174 /// This function returns true if the match was unsuccessful and false if so.
4175 /// On entry to the function the "OverallLeftShift" is a signed integer value
4176 /// indicating the number of bytes that the subexpression is later shifted.  For
4177 /// example, if the expression is later right shifted by 16 bits, the
4178 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4179 /// byte of ByteValues is actually being set.
4180 ///
4181 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4182 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4183 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4184 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4185 /// always in the local (OverallLeftShift) coordinate space.
4186 ///
4187 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4188                               SmallVector<Value*, 8> &ByteValues) {
4189   if (Instruction *I = dyn_cast<Instruction>(V)) {
4190     // If this is an or instruction, it may be an inner node of the bswap.
4191     if (I->getOpcode() == Instruction::Or) {
4192       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4193                                ByteValues) ||
4194              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4195                                ByteValues);
4196     }
4197   
4198     // If this is a logical shift by a constant multiple of 8, recurse with
4199     // OverallLeftShift and ByteMask adjusted.
4200     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4201       unsigned ShAmt = 
4202         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4203       // Ensure the shift amount is defined and of a byte value.
4204       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4205         return true;
4206
4207       unsigned ByteShift = ShAmt >> 3;
4208       if (I->getOpcode() == Instruction::Shl) {
4209         // X << 2 -> collect(X, +2)
4210         OverallLeftShift += ByteShift;
4211         ByteMask >>= ByteShift;
4212       } else {
4213         // X >>u 2 -> collect(X, -2)
4214         OverallLeftShift -= ByteShift;
4215         ByteMask <<= ByteShift;
4216         ByteMask &= (~0U >> (32-ByteValues.size()));
4217       }
4218
4219       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4220       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4221
4222       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4223                                ByteValues);
4224     }
4225
4226     // If this is a logical 'and' with a mask that clears bytes, clear the
4227     // corresponding bytes in ByteMask.
4228     if (I->getOpcode() == Instruction::And &&
4229         isa<ConstantInt>(I->getOperand(1))) {
4230       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4231       unsigned NumBytes = ByteValues.size();
4232       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4233       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4234       
4235       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4236         // If this byte is masked out by a later operation, we don't care what
4237         // the and mask is.
4238         if ((ByteMask & (1 << i)) == 0)
4239           continue;
4240         
4241         // If the AndMask is all zeros for this byte, clear the bit.
4242         APInt MaskB = AndMask & Byte;
4243         if (MaskB == 0) {
4244           ByteMask &= ~(1U << i);
4245           continue;
4246         }
4247         
4248         // If the AndMask is not all ones for this byte, it's not a bytezap.
4249         if (MaskB != Byte)
4250           return true;
4251
4252         // Otherwise, this byte is kept.
4253       }
4254
4255       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4256                                ByteValues);
4257     }
4258   }
4259   
4260   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4261   // the input value to the bswap.  Some observations: 1) if more than one byte
4262   // is demanded from this input, then it could not be successfully assembled
4263   // into a byteswap.  At least one of the two bytes would not be aligned with
4264   // their ultimate destination.
4265   if (!isPowerOf2_32(ByteMask)) return true;
4266   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4267   
4268   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4269   // is demanded, it needs to go into byte 0 of the result.  This means that the
4270   // byte needs to be shifted until it lands in the right byte bucket.  The
4271   // shift amount depends on the position: if the byte is coming from the high
4272   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4273   // low part, it must be shifted left.
4274   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4275   if (InputByteNo < ByteValues.size()/2) {
4276     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4277       return true;
4278   } else {
4279     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4280       return true;
4281   }
4282   
4283   // If the destination byte value is already defined, the values are or'd
4284   // together, which isn't a bswap (unless it's an or of the same bits).
4285   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4286     return true;
4287   ByteValues[DestByteNo] = V;
4288   return false;
4289 }
4290
4291 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4292 /// If so, insert the new bswap intrinsic and return it.
4293 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4294   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4295   if (!ITy || ITy->getBitWidth() % 16 || 
4296       // ByteMask only allows up to 32-byte values.
4297       ITy->getBitWidth() > 32*8) 
4298     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4299   
4300   /// ByteValues - For each byte of the result, we keep track of which value
4301   /// defines each byte.
4302   SmallVector<Value*, 8> ByteValues;
4303   ByteValues.resize(ITy->getBitWidth()/8);
4304     
4305   // Try to find all the pieces corresponding to the bswap.
4306   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4307   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4308     return 0;
4309   
4310   // Check to see if all of the bytes come from the same value.
4311   Value *V = ByteValues[0];
4312   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4313   
4314   // Check to make sure that all of the bytes come from the same value.
4315   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4316     if (ByteValues[i] != V)
4317       return 0;
4318   const Type *Tys[] = { ITy };
4319   Module *M = I.getParent()->getParent()->getParent();
4320   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4321   return CallInst::Create(F, V);
4322 }
4323
4324 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4325 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4326 /// we can simplify this expression to "cond ? C : D or B".
4327 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4328                                          Value *C, Value *D) {
4329   // If A is not a select of -1/0, this cannot match.
4330   Value *Cond = 0;
4331   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4332     return 0;
4333
4334   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4335   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4336     return SelectInst::Create(Cond, C, B);
4337   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4338     return SelectInst::Create(Cond, C, B);
4339   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4340   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4341     return SelectInst::Create(Cond, C, D);
4342   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4343     return SelectInst::Create(Cond, C, D);
4344   return 0;
4345 }
4346
4347 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4348 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4349                                          ICmpInst *LHS, ICmpInst *RHS) {
4350   Value *Val, *Val2;
4351   ConstantInt *LHSCst, *RHSCst;
4352   ICmpInst::Predicate LHSCC, RHSCC;
4353   
4354   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4355   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4356       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4357     return 0;
4358   
4359   // From here on, we only handle:
4360   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4361   if (Val != Val2) return 0;
4362   
4363   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4364   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4365       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4366       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4367       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4368     return 0;
4369   
4370   // We can't fold (ugt x, C) | (sgt x, C2).
4371   if (!PredicatesFoldable(LHSCC, RHSCC))
4372     return 0;
4373   
4374   // Ensure that the larger constant is on the RHS.
4375   bool ShouldSwap;
4376   if (ICmpInst::isSignedPredicate(LHSCC) ||
4377       (ICmpInst::isEquality(LHSCC) && 
4378        ICmpInst::isSignedPredicate(RHSCC)))
4379     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4380   else
4381     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4382   
4383   if (ShouldSwap) {
4384     std::swap(LHS, RHS);
4385     std::swap(LHSCst, RHSCst);
4386     std::swap(LHSCC, RHSCC);
4387   }
4388   
4389   // At this point, we know we have have two icmp instructions
4390   // comparing a value against two constants and or'ing the result
4391   // together.  Because of the above check, we know that we only have
4392   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4393   // FoldICmpLogical check above), that the two constants are not
4394   // equal.
4395   assert(LHSCst != RHSCst && "Compares not folded above?");
4396
4397   switch (LHSCC) {
4398   default: assert(0 && "Unknown integer condition code!");
4399   case ICmpInst::ICMP_EQ:
4400     switch (RHSCC) {
4401     default: assert(0 && "Unknown integer condition code!");
4402     case ICmpInst::ICMP_EQ:
4403       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4404         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4405         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4406                                                      Val->getName()+".off");
4407         InsertNewInstBefore(Add, I);
4408         AddCST = Subtract(AddOne(RHSCst), LHSCst);
4409         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4410       }
4411       break;                         // (X == 13 | X == 15) -> no change
4412     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4413     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4414       break;
4415     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4416     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4417     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4418       return ReplaceInstUsesWith(I, RHS);
4419     }
4420     break;
4421   case ICmpInst::ICMP_NE:
4422     switch (RHSCC) {
4423     default: assert(0 && "Unknown integer condition code!");
4424     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4425     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4426     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4427       return ReplaceInstUsesWith(I, LHS);
4428     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4429     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4430     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4431       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4432     }
4433     break;
4434   case ICmpInst::ICMP_ULT:
4435     switch (RHSCC) {
4436     default: assert(0 && "Unknown integer condition code!");
4437     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4438       break;
4439     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4440       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4441       // this can cause overflow.
4442       if (RHSCst->isMaxValue(false))
4443         return ReplaceInstUsesWith(I, LHS);
4444       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4445     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4446       break;
4447     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4448     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4449       return ReplaceInstUsesWith(I, RHS);
4450     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4451       break;
4452     }
4453     break;
4454   case ICmpInst::ICMP_SLT:
4455     switch (RHSCC) {
4456     default: assert(0 && "Unknown integer condition code!");
4457     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4458       break;
4459     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4460       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4461       // this can cause overflow.
4462       if (RHSCst->isMaxValue(true))
4463         return ReplaceInstUsesWith(I, LHS);
4464       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4465     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4466       break;
4467     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4468     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4469       return ReplaceInstUsesWith(I, RHS);
4470     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4471       break;
4472     }
4473     break;
4474   case ICmpInst::ICMP_UGT:
4475     switch (RHSCC) {
4476     default: assert(0 && "Unknown integer condition code!");
4477     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4478     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4479       return ReplaceInstUsesWith(I, LHS);
4480     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4481       break;
4482     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4483     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4484       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4485     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4486       break;
4487     }
4488     break;
4489   case ICmpInst::ICMP_SGT:
4490     switch (RHSCC) {
4491     default: assert(0 && "Unknown integer condition code!");
4492     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4493     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4494       return ReplaceInstUsesWith(I, LHS);
4495     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4496       break;
4497     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4498     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4499       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4500     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4501       break;
4502     }
4503     break;
4504   }
4505   return 0;
4506 }
4507
4508 /// FoldOrWithConstants - This helper function folds:
4509 ///
4510 ///     ((A | B) & C1) | (B & C2)
4511 ///
4512 /// into:
4513 /// 
4514 ///     (A & C1) | B
4515 ///
4516 /// when the XOR of the two constants is "all ones" (-1).
4517 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4518                                                Value *A, Value *B, Value *C) {
4519   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4520   if (!CI1) return 0;
4521
4522   Value *V1 = 0;
4523   ConstantInt *CI2 = 0;
4524   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4525
4526   APInt Xor = CI1->getValue() ^ CI2->getValue();
4527   if (!Xor.isAllOnesValue()) return 0;
4528
4529   if (V1 == A || V1 == B) {
4530     Instruction *NewOp =
4531       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4532     return BinaryOperator::CreateOr(NewOp, V1);
4533   }
4534
4535   return 0;
4536 }
4537
4538 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4539   bool Changed = SimplifyCommutative(I);
4540   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4541
4542   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4543     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4544
4545   // or X, X = X
4546   if (Op0 == Op1)
4547     return ReplaceInstUsesWith(I, Op0);
4548
4549   // See if we can simplify any instructions used by the instruction whose sole 
4550   // purpose is to compute bits we don't care about.
4551   if (!isa<VectorType>(I.getType())) {
4552     if (SimplifyDemandedInstructionBits(I))
4553       return &I;
4554   } else if (isa<ConstantAggregateZero>(Op1)) {
4555     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4556   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4557     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4558       return ReplaceInstUsesWith(I, I.getOperand(1));
4559   }
4560     
4561
4562   
4563   // or X, -1 == -1
4564   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4565     ConstantInt *C1 = 0; Value *X = 0;
4566     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4567     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4568       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4569       InsertNewInstBefore(Or, I);
4570       Or->takeName(Op0);
4571       return BinaryOperator::CreateAnd(Or, 
4572                ConstantInt::get(RHS->getValue() | C1->getValue()));
4573     }
4574
4575     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4576     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4577       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4578       InsertNewInstBefore(Or, I);
4579       Or->takeName(Op0);
4580       return BinaryOperator::CreateXor(Or,
4581                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4582     }
4583
4584     // Try to fold constant and into select arguments.
4585     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4586       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4587         return R;
4588     if (isa<PHINode>(Op0))
4589       if (Instruction *NV = FoldOpIntoPhi(I))
4590         return NV;
4591   }
4592
4593   Value *A = 0, *B = 0;
4594   ConstantInt *C1 = 0, *C2 = 0;
4595
4596   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4597     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4598       return ReplaceInstUsesWith(I, Op1);
4599   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4600     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4601       return ReplaceInstUsesWith(I, Op0);
4602
4603   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4604   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4605   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4606       match(Op1, m_Or(m_Value(), m_Value())) ||
4607       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4608        match(Op1, m_Shift(m_Value(), m_Value())))) {
4609     if (Instruction *BSwap = MatchBSwap(I))
4610       return BSwap;
4611   }
4612   
4613   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4614   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4615       MaskedValueIsZero(Op1, C1->getValue())) {
4616     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4617     InsertNewInstBefore(NOr, I);
4618     NOr->takeName(Op0);
4619     return BinaryOperator::CreateXor(NOr, C1);
4620   }
4621
4622   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4623   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4624       MaskedValueIsZero(Op0, C1->getValue())) {
4625     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4626     InsertNewInstBefore(NOr, I);
4627     NOr->takeName(Op0);
4628     return BinaryOperator::CreateXor(NOr, C1);
4629   }
4630
4631   // (A & C)|(B & D)
4632   Value *C = 0, *D = 0;
4633   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4634       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4635     Value *V1 = 0, *V2 = 0, *V3 = 0;
4636     C1 = dyn_cast<ConstantInt>(C);
4637     C2 = dyn_cast<ConstantInt>(D);
4638     if (C1 && C2) {  // (A & C1)|(B & C2)
4639       // If we have: ((V + N) & C1) | (V & C2)
4640       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4641       // replace with V+N.
4642       if (C1->getValue() == ~C2->getValue()) {
4643         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4644             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4645           // Add commutes, try both ways.
4646           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4647             return ReplaceInstUsesWith(I, A);
4648           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4649             return ReplaceInstUsesWith(I, A);
4650         }
4651         // Or commutes, try both ways.
4652         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4653             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4654           // Add commutes, try both ways.
4655           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4656             return ReplaceInstUsesWith(I, B);
4657           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4658             return ReplaceInstUsesWith(I, B);
4659         }
4660       }
4661       V1 = 0; V2 = 0; V3 = 0;
4662     }
4663     
4664     // Check to see if we have any common things being and'ed.  If so, find the
4665     // terms for V1 & (V2|V3).
4666     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4667       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4668         V1 = A, V2 = C, V3 = D;
4669       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4670         V1 = A, V2 = B, V3 = C;
4671       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4672         V1 = C, V2 = A, V3 = D;
4673       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4674         V1 = C, V2 = A, V3 = B;
4675       
4676       if (V1) {
4677         Value *Or =
4678           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4679         return BinaryOperator::CreateAnd(V1, Or);
4680       }
4681     }
4682
4683     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4684     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4685       return Match;
4686     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4687       return Match;
4688     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4689       return Match;
4690     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4691       return Match;
4692
4693     // ((A&~B)|(~A&B)) -> A^B
4694     if ((match(C, m_Not(m_Specific(D))) &&
4695          match(B, m_Not(m_Specific(A)))))
4696       return BinaryOperator::CreateXor(A, D);
4697     // ((~B&A)|(~A&B)) -> A^B
4698     if ((match(A, m_Not(m_Specific(D))) &&
4699          match(B, m_Not(m_Specific(C)))))
4700       return BinaryOperator::CreateXor(C, D);
4701     // ((A&~B)|(B&~A)) -> A^B
4702     if ((match(C, m_Not(m_Specific(B))) &&
4703          match(D, m_Not(m_Specific(A)))))
4704       return BinaryOperator::CreateXor(A, B);
4705     // ((~B&A)|(B&~A)) -> A^B
4706     if ((match(A, m_Not(m_Specific(B))) &&
4707          match(D, m_Not(m_Specific(C)))))
4708       return BinaryOperator::CreateXor(C, B);
4709   }
4710   
4711   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4712   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4713     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4714       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4715           SI0->getOperand(1) == SI1->getOperand(1) &&
4716           (SI0->hasOneUse() || SI1->hasOneUse())) {
4717         Instruction *NewOp =
4718         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4719                                                      SI1->getOperand(0),
4720                                                      SI0->getName()), I);
4721         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4722                                       SI1->getOperand(1));
4723       }
4724   }
4725
4726   // ((A|B)&1)|(B&-2) -> (A&1) | B
4727   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4728       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4729     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4730     if (Ret) return Ret;
4731   }
4732   // (B&-2)|((A|B)&1) -> (A&1) | B
4733   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4734       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4735     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4736     if (Ret) return Ret;
4737   }
4738
4739   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4740     if (A == Op1)   // ~A | A == -1
4741       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4742   } else {
4743     A = 0;
4744   }
4745   // Note, A is still live here!
4746   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4747     if (Op0 == B)
4748       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4749
4750     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4751     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4752       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4753                                               I.getName()+".demorgan"), I);
4754       return BinaryOperator::CreateNot(And);
4755     }
4756   }
4757
4758   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4759   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4760     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4761       return R;
4762
4763     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4764       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4765         return Res;
4766   }
4767     
4768   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4769   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4770     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4771       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4772         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4773             !isa<ICmpInst>(Op1C->getOperand(0))) {
4774           const Type *SrcTy = Op0C->getOperand(0)->getType();
4775           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4776               // Only do this if the casts both really cause code to be
4777               // generated.
4778               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4779                                 I.getType(), TD) &&
4780               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4781                                 I.getType(), TD)) {
4782             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4783                                                           Op1C->getOperand(0),
4784                                                           I.getName());
4785             InsertNewInstBefore(NewOp, I);
4786             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4787           }
4788         }
4789       }
4790   }
4791   
4792     
4793   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4794   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4795     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4796       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4797           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4798           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4799         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4800           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4801             // If either of the constants are nans, then the whole thing returns
4802             // true.
4803             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4804               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4805             
4806             // Otherwise, no need to compare the two constants, compare the
4807             // rest.
4808             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4809                                 RHS->getOperand(0));
4810           }
4811       } else {
4812         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4813         FCmpInst::Predicate Op0CC, Op1CC;
4814         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4815             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4816           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4817             // Swap RHS operands to match LHS.
4818             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4819             std::swap(Op1LHS, Op1RHS);
4820           }
4821           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4822             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4823             if (Op0CC == Op1CC)
4824               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4825             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4826                      Op1CC == FCmpInst::FCMP_TRUE)
4827               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4828             else if (Op0CC == FCmpInst::FCMP_FALSE)
4829               return ReplaceInstUsesWith(I, Op1);
4830             else if (Op1CC == FCmpInst::FCMP_FALSE)
4831               return ReplaceInstUsesWith(I, Op0);
4832             bool Op0Ordered;
4833             bool Op1Ordered;
4834             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4835             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4836             if (Op0Ordered == Op1Ordered) {
4837               // If both are ordered or unordered, return a new fcmp with
4838               // or'ed predicates.
4839               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4840                                        Op0LHS, Op0RHS);
4841               if (Instruction *I = dyn_cast<Instruction>(RV))
4842                 return I;
4843               // Otherwise, it's a constant boolean value...
4844               return ReplaceInstUsesWith(I, RV);
4845             }
4846           }
4847         }
4848       }
4849     }
4850   }
4851
4852   return Changed ? &I : 0;
4853 }
4854
4855 namespace {
4856
4857 // XorSelf - Implements: X ^ X --> 0
4858 struct XorSelf {
4859   Value *RHS;
4860   XorSelf(Value *rhs) : RHS(rhs) {}
4861   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4862   Instruction *apply(BinaryOperator &Xor) const {
4863     return &Xor;
4864   }
4865 };
4866
4867 }
4868
4869 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4870   bool Changed = SimplifyCommutative(I);
4871   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4872
4873   if (isa<UndefValue>(Op1)) {
4874     if (isa<UndefValue>(Op0))
4875       // Handle undef ^ undef -> 0 special case. This is a common
4876       // idiom (misuse).
4877       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4878     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4879   }
4880
4881   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4882   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4883     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4884     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4885   }
4886   
4887   // See if we can simplify any instructions used by the instruction whose sole 
4888   // purpose is to compute bits we don't care about.
4889   if (!isa<VectorType>(I.getType())) {
4890     if (SimplifyDemandedInstructionBits(I))
4891       return &I;
4892   } else if (isa<ConstantAggregateZero>(Op1)) {
4893     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4894   }
4895
4896   // Is this a ~ operation?
4897   if (Value *NotOp = dyn_castNotVal(&I)) {
4898     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4899     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4900     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4901       if (Op0I->getOpcode() == Instruction::And || 
4902           Op0I->getOpcode() == Instruction::Or) {
4903         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4904         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4905           Instruction *NotY =
4906             BinaryOperator::CreateNot(Op0I->getOperand(1),
4907                                       Op0I->getOperand(1)->getName()+".not");
4908           InsertNewInstBefore(NotY, I);
4909           if (Op0I->getOpcode() == Instruction::And)
4910             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4911           else
4912             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4913         }
4914       }
4915     }
4916   }
4917   
4918   
4919   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4920     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4921       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4922       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4923         return new ICmpInst(ICI->getInversePredicate(),
4924                             ICI->getOperand(0), ICI->getOperand(1));
4925
4926       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4927         return new FCmpInst(FCI->getInversePredicate(),
4928                             FCI->getOperand(0), FCI->getOperand(1));
4929     }
4930
4931     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4932     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4933       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4934         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4935           Instruction::CastOps Opcode = Op0C->getOpcode();
4936           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4937             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4938                                              Op0C->getDestTy())) {
4939               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4940                                      CI->getOpcode(), CI->getInversePredicate(),
4941                                      CI->getOperand(0), CI->getOperand(1)), I);
4942               NewCI->takeName(CI);
4943               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4944             }
4945           }
4946         }
4947       }
4948     }
4949
4950     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4951       // ~(c-X) == X-c-1 == X+(-c-1)
4952       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4953         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4954           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4955           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4956                                               ConstantInt::get(I.getType(), 1));
4957           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4958         }
4959           
4960       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4961         if (Op0I->getOpcode() == Instruction::Add) {
4962           // ~(X-c) --> (-c-1)-X
4963           if (RHS->isAllOnesValue()) {
4964             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4965             return BinaryOperator::CreateSub(
4966                            ConstantExpr::getSub(NegOp0CI,
4967                                              ConstantInt::get(I.getType(), 1)),
4968                                           Op0I->getOperand(0));
4969           } else if (RHS->getValue().isSignBit()) {
4970             // (X + C) ^ signbit -> (X + C + signbit)
4971             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4972             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4973
4974           }
4975         } else if (Op0I->getOpcode() == Instruction::Or) {
4976           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4977           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4978             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4979             // Anything in both C1 and C2 is known to be zero, remove it from
4980             // NewRHS.
4981             Constant *CommonBits = And(Op0CI, RHS);
4982             NewRHS = ConstantExpr::getAnd(NewRHS, 
4983                                           ConstantExpr::getNot(CommonBits));
4984             AddToWorkList(Op0I);
4985             I.setOperand(0, Op0I->getOperand(0));
4986             I.setOperand(1, NewRHS);
4987             return &I;
4988           }
4989         }
4990       }
4991     }
4992
4993     // Try to fold constant and into select arguments.
4994     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4995       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4996         return R;
4997     if (isa<PHINode>(Op0))
4998       if (Instruction *NV = FoldOpIntoPhi(I))
4999         return NV;
5000   }
5001
5002   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5003     if (X == Op1)
5004       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5005
5006   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5007     if (X == Op0)
5008       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5009
5010   
5011   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5012   if (Op1I) {
5013     Value *A, *B;
5014     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5015       if (A == Op0) {              // B^(B|A) == (A|B)^B
5016         Op1I->swapOperands();
5017         I.swapOperands();
5018         std::swap(Op0, Op1);
5019       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5020         I.swapOperands();     // Simplified below.
5021         std::swap(Op0, Op1);
5022       }
5023     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5024       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5025     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5026       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5027     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5028       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5029         Op1I->swapOperands();
5030         std::swap(A, B);
5031       }
5032       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5033         I.swapOperands();     // Simplified below.
5034         std::swap(Op0, Op1);
5035       }
5036     }
5037   }
5038   
5039   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5040   if (Op0I) {
5041     Value *A, *B;
5042     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5043       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5044         std::swap(A, B);
5045       if (B == Op1) {                                // (A|B)^B == A & ~B
5046         Instruction *NotB =
5047           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5048         return BinaryOperator::CreateAnd(A, NotB);
5049       }
5050     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5051       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5052     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5053       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5054     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5055       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5056         std::swap(A, B);
5057       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5058           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5059         Instruction *N =
5060           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5061         return BinaryOperator::CreateAnd(N, Op1);
5062       }
5063     }
5064   }
5065   
5066   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5067   if (Op0I && Op1I && Op0I->isShift() && 
5068       Op0I->getOpcode() == Op1I->getOpcode() && 
5069       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5070       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5071     Instruction *NewOp =
5072       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5073                                                     Op1I->getOperand(0),
5074                                                     Op0I->getName()), I);
5075     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5076                                   Op1I->getOperand(1));
5077   }
5078     
5079   if (Op0I && Op1I) {
5080     Value *A, *B, *C, *D;
5081     // (A & B)^(A | B) -> A ^ B
5082     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5083         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5084       if ((A == C && B == D) || (A == D && B == C)) 
5085         return BinaryOperator::CreateXor(A, B);
5086     }
5087     // (A | B)^(A & B) -> A ^ B
5088     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5089         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5090       if ((A == C && B == D) || (A == D && B == C)) 
5091         return BinaryOperator::CreateXor(A, B);
5092     }
5093     
5094     // (A & B)^(C & D)
5095     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5096         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5097         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5098       // (X & Y)^(X & Y) -> (Y^Z) & X
5099       Value *X = 0, *Y = 0, *Z = 0;
5100       if (A == C)
5101         X = A, Y = B, Z = D;
5102       else if (A == D)
5103         X = A, Y = B, Z = C;
5104       else if (B == C)
5105         X = B, Y = A, Z = D;
5106       else if (B == D)
5107         X = B, Y = A, Z = C;
5108       
5109       if (X) {
5110         Instruction *NewOp =
5111         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5112         return BinaryOperator::CreateAnd(NewOp, X);
5113       }
5114     }
5115   }
5116     
5117   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5118   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5119     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5120       return R;
5121
5122   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5123   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5124     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5125       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5126         const Type *SrcTy = Op0C->getOperand(0)->getType();
5127         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5128             // Only do this if the casts both really cause code to be generated.
5129             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5130                               I.getType(), TD) &&
5131             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5132                               I.getType(), TD)) {
5133           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5134                                                          Op1C->getOperand(0),
5135                                                          I.getName());
5136           InsertNewInstBefore(NewOp, I);
5137           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5138         }
5139       }
5140   }
5141
5142   return Changed ? &I : 0;
5143 }
5144
5145 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5146 /// overflowed for this type.
5147 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5148                             ConstantInt *In2, bool IsSigned = false) {
5149   Result = cast<ConstantInt>(Add(In1, In2));
5150
5151   if (IsSigned)
5152     if (In2->getValue().isNegative())
5153       return Result->getValue().sgt(In1->getValue());
5154     else
5155       return Result->getValue().slt(In1->getValue());
5156   else
5157     return Result->getValue().ult(In1->getValue());
5158 }
5159
5160 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5161 /// overflowed for this type.
5162 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5163                             ConstantInt *In2, bool IsSigned = false) {
5164   Result = cast<ConstantInt>(Subtract(In1, In2));
5165
5166   if (IsSigned)
5167     if (In2->getValue().isNegative())
5168       return Result->getValue().slt(In1->getValue());
5169     else
5170       return Result->getValue().sgt(In1->getValue());
5171   else
5172     return Result->getValue().ugt(In1->getValue());
5173 }
5174
5175 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5176 /// code necessary to compute the offset from the base pointer (without adding
5177 /// in the base pointer).  Return the result as a signed integer of intptr size.
5178 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5179   TargetData &TD = IC.getTargetData();
5180   gep_type_iterator GTI = gep_type_begin(GEP);
5181   const Type *IntPtrTy = TD.getIntPtrType();
5182   Value *Result = Constant::getNullValue(IntPtrTy);
5183
5184   // Build a mask for high order bits.
5185   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5186   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5187
5188   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5189        ++i, ++GTI) {
5190     Value *Op = *i;
5191     uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
5192     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5193       if (OpC->isZero()) continue;
5194       
5195       // Handle a struct index, which adds its field offset to the pointer.
5196       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5197         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5198         
5199         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5200           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5201         else
5202           Result = IC.InsertNewInstBefore(
5203                    BinaryOperator::CreateAdd(Result,
5204                                              ConstantInt::get(IntPtrTy, Size),
5205                                              GEP->getName()+".offs"), I);
5206         continue;
5207       }
5208       
5209       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5210       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5211       Scale = ConstantExpr::getMul(OC, Scale);
5212       if (Constant *RC = dyn_cast<Constant>(Result))
5213         Result = ConstantExpr::getAdd(RC, Scale);
5214       else {
5215         // Emit an add instruction.
5216         Result = IC.InsertNewInstBefore(
5217            BinaryOperator::CreateAdd(Result, Scale,
5218                                      GEP->getName()+".offs"), I);
5219       }
5220       continue;
5221     }
5222     // Convert to correct type.
5223     if (Op->getType() != IntPtrTy) {
5224       if (Constant *OpC = dyn_cast<Constant>(Op))
5225         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5226       else
5227         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5228                                                  Op->getName()+".c"), I);
5229     }
5230     if (Size != 1) {
5231       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5232       if (Constant *OpC = dyn_cast<Constant>(Op))
5233         Op = ConstantExpr::getMul(OpC, Scale);
5234       else    // We'll let instcombine(mul) convert this to a shl if possible.
5235         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5236                                                   GEP->getName()+".idx"), I);
5237     }
5238
5239     // Emit an add instruction.
5240     if (isa<Constant>(Op) && isa<Constant>(Result))
5241       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5242                                     cast<Constant>(Result));
5243     else
5244       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5245                                                   GEP->getName()+".offs"), I);
5246   }
5247   return Result;
5248 }
5249
5250
5251 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5252 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5253 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5254 /// complex, and scales are involved.  The above expression would also be legal
5255 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5256 /// later form is less amenable to optimization though, and we are allowed to
5257 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5258 ///
5259 /// If we can't emit an optimized form for this expression, this returns null.
5260 /// 
5261 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5262                                           InstCombiner &IC) {
5263   TargetData &TD = IC.getTargetData();
5264   gep_type_iterator GTI = gep_type_begin(GEP);
5265
5266   // Check to see if this gep only has a single variable index.  If so, and if
5267   // any constant indices are a multiple of its scale, then we can compute this
5268   // in terms of the scale of the variable index.  For example, if the GEP
5269   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5270   // because the expression will cross zero at the same point.
5271   unsigned i, e = GEP->getNumOperands();
5272   int64_t Offset = 0;
5273   for (i = 1; i != e; ++i, ++GTI) {
5274     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5275       // Compute the aggregate offset of constant indices.
5276       if (CI->isZero()) continue;
5277
5278       // Handle a struct index, which adds its field offset to the pointer.
5279       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5280         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5281       } else {
5282         uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
5283         Offset += Size*CI->getSExtValue();
5284       }
5285     } else {
5286       // Found our variable index.
5287       break;
5288     }
5289   }
5290   
5291   // If there are no variable indices, we must have a constant offset, just
5292   // evaluate it the general way.
5293   if (i == e) return 0;
5294   
5295   Value *VariableIdx = GEP->getOperand(i);
5296   // Determine the scale factor of the variable element.  For example, this is
5297   // 4 if the variable index is into an array of i32.
5298   uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
5299   
5300   // Verify that there are no other variable indices.  If so, emit the hard way.
5301   for (++i, ++GTI; i != e; ++i, ++GTI) {
5302     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5303     if (!CI) return 0;
5304    
5305     // Compute the aggregate offset of constant indices.
5306     if (CI->isZero()) continue;
5307     
5308     // Handle a struct index, which adds its field offset to the pointer.
5309     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5310       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5311     } else {
5312       uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
5313       Offset += Size*CI->getSExtValue();
5314     }
5315   }
5316   
5317   // Okay, we know we have a single variable index, which must be a
5318   // pointer/array/vector index.  If there is no offset, life is simple, return
5319   // the index.
5320   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5321   if (Offset == 0) {
5322     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5323     // we don't need to bother extending: the extension won't affect where the
5324     // computation crosses zero.
5325     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5326       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5327                                   VariableIdx->getNameStart(), &I);
5328     return VariableIdx;
5329   }
5330   
5331   // Otherwise, there is an index.  The computation we will do will be modulo
5332   // the pointer size, so get it.
5333   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5334   
5335   Offset &= PtrSizeMask;
5336   VariableScale &= PtrSizeMask;
5337
5338   // To do this transformation, any constant index must be a multiple of the
5339   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5340   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5341   // multiple of the variable scale.
5342   int64_t NewOffs = Offset / (int64_t)VariableScale;
5343   if (Offset != NewOffs*(int64_t)VariableScale)
5344     return 0;
5345
5346   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5347   const Type *IntPtrTy = TD.getIntPtrType();
5348   if (VariableIdx->getType() != IntPtrTy)
5349     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5350                                               true /*SExt*/, 
5351                                               VariableIdx->getNameStart(), &I);
5352   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5353   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5354 }
5355
5356
5357 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5358 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5359 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5360                                        ICmpInst::Predicate Cond,
5361                                        Instruction &I) {
5362   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5363
5364   // Look through bitcasts.
5365   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5366     RHS = BCI->getOperand(0);
5367
5368   Value *PtrBase = GEPLHS->getOperand(0);
5369   if (PtrBase == RHS) {
5370     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5371     // This transformation (ignoring the base and scales) is valid because we
5372     // know pointers can't overflow.  See if we can output an optimized form.
5373     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5374     
5375     // If not, synthesize the offset the hard way.
5376     if (Offset == 0)
5377       Offset = EmitGEPOffset(GEPLHS, I, *this);
5378     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5379                         Constant::getNullValue(Offset->getType()));
5380   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5381     // If the base pointers are different, but the indices are the same, just
5382     // compare the base pointer.
5383     if (PtrBase != GEPRHS->getOperand(0)) {
5384       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5385       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5386                         GEPRHS->getOperand(0)->getType();
5387       if (IndicesTheSame)
5388         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5389           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5390             IndicesTheSame = false;
5391             break;
5392           }
5393
5394       // If all indices are the same, just compare the base pointers.
5395       if (IndicesTheSame)
5396         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5397                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5398
5399       // Otherwise, the base pointers are different and the indices are
5400       // different, bail out.
5401       return 0;
5402     }
5403
5404     // If one of the GEPs has all zero indices, recurse.
5405     bool AllZeros = true;
5406     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5407       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5408           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5409         AllZeros = false;
5410         break;
5411       }
5412     if (AllZeros)
5413       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5414                           ICmpInst::getSwappedPredicate(Cond), I);
5415
5416     // If the other GEP has all zero indices, recurse.
5417     AllZeros = true;
5418     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5419       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5420           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5421         AllZeros = false;
5422         break;
5423       }
5424     if (AllZeros)
5425       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5426
5427     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5428       // If the GEPs only differ by one index, compare it.
5429       unsigned NumDifferences = 0;  // Keep track of # differences.
5430       unsigned DiffOperand = 0;     // The operand that differs.
5431       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5432         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5433           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5434                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5435             // Irreconcilable differences.
5436             NumDifferences = 2;
5437             break;
5438           } else {
5439             if (NumDifferences++) break;
5440             DiffOperand = i;
5441           }
5442         }
5443
5444       if (NumDifferences == 0)   // SAME GEP?
5445         return ReplaceInstUsesWith(I, // No comparison is needed here.
5446                                    ConstantInt::get(Type::Int1Ty,
5447                                              ICmpInst::isTrueWhenEqual(Cond)));
5448
5449       else if (NumDifferences == 1) {
5450         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5451         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5452         // Make sure we do a signed comparison here.
5453         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5454       }
5455     }
5456
5457     // Only lower this if the icmp is the only user of the GEP or if we expect
5458     // the result to fold to a constant!
5459     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5460         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5461       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5462       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5463       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5464       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5465     }
5466   }
5467   return 0;
5468 }
5469
5470 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5471 ///
5472 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5473                                                 Instruction *LHSI,
5474                                                 Constant *RHSC) {
5475   if (!isa<ConstantFP>(RHSC)) return 0;
5476   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5477   
5478   // Get the width of the mantissa.  We don't want to hack on conversions that
5479   // might lose information from the integer, e.g. "i64 -> float"
5480   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5481   if (MantissaWidth == -1) return 0;  // Unknown.
5482   
5483   // Check to see that the input is converted from an integer type that is small
5484   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5485   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5486   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5487   
5488   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5489   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5490   if (LHSUnsigned)
5491     ++InputSize;
5492   
5493   // If the conversion would lose info, don't hack on this.
5494   if ((int)InputSize > MantissaWidth)
5495     return 0;
5496   
5497   // Otherwise, we can potentially simplify the comparison.  We know that it
5498   // will always come through as an integer value and we know the constant is
5499   // not a NAN (it would have been previously simplified).
5500   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5501   
5502   ICmpInst::Predicate Pred;
5503   switch (I.getPredicate()) {
5504   default: assert(0 && "Unexpected predicate!");
5505   case FCmpInst::FCMP_UEQ:
5506   case FCmpInst::FCMP_OEQ:
5507     Pred = ICmpInst::ICMP_EQ;
5508     break;
5509   case FCmpInst::FCMP_UGT:
5510   case FCmpInst::FCMP_OGT:
5511     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5512     break;
5513   case FCmpInst::FCMP_UGE:
5514   case FCmpInst::FCMP_OGE:
5515     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5516     break;
5517   case FCmpInst::FCMP_ULT:
5518   case FCmpInst::FCMP_OLT:
5519     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5520     break;
5521   case FCmpInst::FCMP_ULE:
5522   case FCmpInst::FCMP_OLE:
5523     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5524     break;
5525   case FCmpInst::FCMP_UNE:
5526   case FCmpInst::FCMP_ONE:
5527     Pred = ICmpInst::ICMP_NE;
5528     break;
5529   case FCmpInst::FCMP_ORD:
5530     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5531   case FCmpInst::FCMP_UNO:
5532     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5533   }
5534   
5535   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5536   
5537   // Now we know that the APFloat is a normal number, zero or inf.
5538   
5539   // See if the FP constant is too large for the integer.  For example,
5540   // comparing an i8 to 300.0.
5541   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5542   
5543   if (!LHSUnsigned) {
5544     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5545     // and large values.
5546     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5547     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5548                           APFloat::rmNearestTiesToEven);
5549     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5550       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5551           Pred == ICmpInst::ICMP_SLE)
5552         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5553       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5554     }
5555   } else {
5556     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5557     // +INF and large values.
5558     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5559     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5560                           APFloat::rmNearestTiesToEven);
5561     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5562       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5563           Pred == ICmpInst::ICMP_ULE)
5564         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5565       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5566     }
5567   }
5568   
5569   if (!LHSUnsigned) {
5570     // See if the RHS value is < SignedMin.
5571     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5572     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5573                           APFloat::rmNearestTiesToEven);
5574     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5575       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5576           Pred == ICmpInst::ICMP_SGE)
5577         return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5578       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5579     }
5580   }
5581
5582   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5583   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5584   // casting the FP value to the integer value and back, checking for equality.
5585   // Don't do this for zero, because -0.0 is not fractional.
5586   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5587   if (!RHS.isZero() &&
5588       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5589     // If we had a comparison against a fractional value, we have to adjust the
5590     // compare predicate and sometimes the value.  RHSC is rounded towards zero
5591     // at this point.
5592     switch (Pred) {
5593     default: assert(0 && "Unexpected integer comparison!");
5594     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5595       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5596     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5597       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5598     case ICmpInst::ICMP_ULE:
5599       // (float)int <= 4.4   --> int <= 4
5600       // (float)int <= -4.4  --> false
5601       if (RHS.isNegative())
5602         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5603       break;
5604     case ICmpInst::ICMP_SLE:
5605       // (float)int <= 4.4   --> int <= 4
5606       // (float)int <= -4.4  --> int < -4
5607       if (RHS.isNegative())
5608         Pred = ICmpInst::ICMP_SLT;
5609       break;
5610     case ICmpInst::ICMP_ULT:
5611       // (float)int < -4.4   --> false
5612       // (float)int < 4.4    --> int <= 4
5613       if (RHS.isNegative())
5614         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5615       Pred = ICmpInst::ICMP_ULE;
5616       break;
5617     case ICmpInst::ICMP_SLT:
5618       // (float)int < -4.4   --> int < -4
5619       // (float)int < 4.4    --> int <= 4
5620       if (!RHS.isNegative())
5621         Pred = ICmpInst::ICMP_SLE;
5622       break;
5623     case ICmpInst::ICMP_UGT:
5624       // (float)int > 4.4    --> int > 4
5625       // (float)int > -4.4   --> true
5626       if (RHS.isNegative())
5627         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5628       break;
5629     case ICmpInst::ICMP_SGT:
5630       // (float)int > 4.4    --> int > 4
5631       // (float)int > -4.4   --> int >= -4
5632       if (RHS.isNegative())
5633         Pred = ICmpInst::ICMP_SGE;
5634       break;
5635     case ICmpInst::ICMP_UGE:
5636       // (float)int >= -4.4   --> true
5637       // (float)int >= 4.4    --> int > 4
5638       if (!RHS.isNegative())
5639         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5640       Pred = ICmpInst::ICMP_UGT;
5641       break;
5642     case ICmpInst::ICMP_SGE:
5643       // (float)int >= -4.4   --> int >= -4
5644       // (float)int >= 4.4    --> int > 4
5645       if (!RHS.isNegative())
5646         Pred = ICmpInst::ICMP_SGT;
5647       break;
5648     }
5649   }
5650
5651   // Lower this FP comparison into an appropriate integer version of the
5652   // comparison.
5653   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5654 }
5655
5656 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5657   bool Changed = SimplifyCompare(I);
5658   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5659
5660   // Fold trivial predicates.
5661   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5662     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5663   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5664     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5665   
5666   // Simplify 'fcmp pred X, X'
5667   if (Op0 == Op1) {
5668     switch (I.getPredicate()) {
5669     default: assert(0 && "Unknown predicate!");
5670     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5671     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5672     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5673       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5674     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5675     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5676     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5677       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5678       
5679     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5680     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5681     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5682     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5683       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5684       I.setPredicate(FCmpInst::FCMP_UNO);
5685       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5686       return &I;
5687       
5688     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5689     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5690     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5691     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5692       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5693       I.setPredicate(FCmpInst::FCMP_ORD);
5694       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5695       return &I;
5696     }
5697   }
5698     
5699   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5700     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5701
5702   // Handle fcmp with constant RHS
5703   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5704     // If the constant is a nan, see if we can fold the comparison based on it.
5705     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5706       if (CFP->getValueAPF().isNaN()) {
5707         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5708           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5709         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5710                "Comparison must be either ordered or unordered!");
5711         // True if unordered.
5712         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5713       }
5714     }
5715     
5716     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5717       switch (LHSI->getOpcode()) {
5718       case Instruction::PHI:
5719         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5720         // block.  If in the same block, we're encouraging jump threading.  If
5721         // not, we are just pessimizing the code by making an i1 phi.
5722         if (LHSI->getParent() == I.getParent())
5723           if (Instruction *NV = FoldOpIntoPhi(I))
5724             return NV;
5725         break;
5726       case Instruction::SIToFP:
5727       case Instruction::UIToFP:
5728         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5729           return NV;
5730         break;
5731       case Instruction::Select:
5732         // If either operand of the select is a constant, we can fold the
5733         // comparison into the select arms, which will cause one to be
5734         // constant folded and the select turned into a bitwise or.
5735         Value *Op1 = 0, *Op2 = 0;
5736         if (LHSI->hasOneUse()) {
5737           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5738             // Fold the known value into the constant operand.
5739             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5740             // Insert a new FCmp of the other select operand.
5741             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5742                                                       LHSI->getOperand(2), RHSC,
5743                                                       I.getName()), I);
5744           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5745             // Fold the known value into the constant operand.
5746             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5747             // Insert a new FCmp of the other select operand.
5748             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5749                                                       LHSI->getOperand(1), RHSC,
5750                                                       I.getName()), I);
5751           }
5752         }
5753
5754         if (Op1)
5755           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5756         break;
5757       }
5758   }
5759
5760   return Changed ? &I : 0;
5761 }
5762
5763 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5764   bool Changed = SimplifyCompare(I);
5765   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5766   const Type *Ty = Op0->getType();
5767
5768   // icmp X, X
5769   if (Op0 == Op1)
5770     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5771                                                    I.isTrueWhenEqual()));
5772
5773   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5774     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5775   
5776   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5777   // addresses never equal each other!  We already know that Op0 != Op1.
5778   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5779        isa<ConstantPointerNull>(Op0)) &&
5780       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5781        isa<ConstantPointerNull>(Op1)))
5782     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5783                                                    !I.isTrueWhenEqual()));
5784
5785   // icmp's with boolean values can always be turned into bitwise operations
5786   if (Ty == Type::Int1Ty) {
5787     switch (I.getPredicate()) {
5788     default: assert(0 && "Invalid icmp instruction!");
5789     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5790       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5791       InsertNewInstBefore(Xor, I);
5792       return BinaryOperator::CreateNot(Xor);
5793     }
5794     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5795       return BinaryOperator::CreateXor(Op0, Op1);
5796
5797     case ICmpInst::ICMP_UGT:
5798       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5799       // FALL THROUGH
5800     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5801       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5802       InsertNewInstBefore(Not, I);
5803       return BinaryOperator::CreateAnd(Not, Op1);
5804     }
5805     case ICmpInst::ICMP_SGT:
5806       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5807       // FALL THROUGH
5808     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5809       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5810       InsertNewInstBefore(Not, I);
5811       return BinaryOperator::CreateAnd(Not, Op0);
5812     }
5813     case ICmpInst::ICMP_UGE:
5814       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5815       // FALL THROUGH
5816     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5817       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5818       InsertNewInstBefore(Not, I);
5819       return BinaryOperator::CreateOr(Not, Op1);
5820     }
5821     case ICmpInst::ICMP_SGE:
5822       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5823       // FALL THROUGH
5824     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5825       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5826       InsertNewInstBefore(Not, I);
5827       return BinaryOperator::CreateOr(Not, Op0);
5828     }
5829     }
5830   }
5831
5832   // See if we are doing a comparison with a constant.
5833   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5834     Value *A = 0, *B = 0;
5835     
5836     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5837     if (I.isEquality() && CI->isNullValue() &&
5838         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5839       // (icmp cond A B) if cond is equality
5840       return new ICmpInst(I.getPredicate(), A, B);
5841     }
5842     
5843     // If we have an icmp le or icmp ge instruction, turn it into the
5844     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5845     // them being folded in the code below.
5846     switch (I.getPredicate()) {
5847     default: break;
5848     case ICmpInst::ICMP_ULE:
5849       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5850         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5851       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5852     case ICmpInst::ICMP_SLE:
5853       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5854         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5855       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5856     case ICmpInst::ICMP_UGE:
5857       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5858         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5859       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5860     case ICmpInst::ICMP_SGE:
5861       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5862         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5863       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5864     }
5865     
5866     // See if we can fold the comparison based on range information we can get
5867     // by checking whether bits are known to be zero or one in the input.
5868     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5869     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5870     
5871     // If this comparison is a normal comparison, it demands all
5872     // bits, if it is a sign bit comparison, it only demands the sign bit.
5873     bool UnusedBit;
5874     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5875     
5876     if (SimplifyDemandedBits(I.getOperandUse(0), 
5877                              isSignBit ? APInt::getSignBit(BitWidth)
5878                                        : APInt::getAllOnesValue(BitWidth),
5879                              KnownZero, KnownOne, 0))
5880       return &I;
5881         
5882     // Given the known and unknown bits, compute a range that the LHS could be
5883     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5884     // EQ and NE we use unsigned values.
5885     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5886     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5887       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5888     else
5889       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5890     
5891     // If Min and Max are known to be the same, then SimplifyDemandedBits
5892     // figured out that the LHS is a constant.  Just constant fold this now so
5893     // that code below can assume that Min != Max.
5894     if (Min == Max)
5895       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5896                                                           ConstantInt::get(Min),
5897                                                           CI));
5898     
5899     // Based on the range information we know about the LHS, see if we can
5900     // simplify this comparison.  For example, (x&4) < 8  is always true.
5901     const APInt &RHSVal = CI->getValue();
5902     switch (I.getPredicate()) {  // LE/GE have been folded already.
5903     default: assert(0 && "Unknown icmp opcode!");
5904     case ICmpInst::ICMP_EQ:
5905       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5906         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5907       break;
5908     case ICmpInst::ICMP_NE:
5909       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5910         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5911       break;
5912     case ICmpInst::ICMP_ULT:
5913       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5914         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5915       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5916         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5917       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5918         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5919       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5920         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5921         
5922       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5923       if (CI->isMinValue(true))
5924         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5925                             ConstantInt::getAllOnesValue(Op0->getType()));
5926       break;
5927     case ICmpInst::ICMP_UGT:
5928       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5929         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5930       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5931         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5932         
5933       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5934         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5935       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5936         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5937       
5938       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5939       if (CI->isMaxValue(true))
5940         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5941                             ConstantInt::getNullValue(Op0->getType()));
5942       break;
5943     case ICmpInst::ICMP_SLT:
5944       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5945         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5946       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5947         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5948       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5949         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5950       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5951         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5952       break;
5953     case ICmpInst::ICMP_SGT: 
5954       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5955         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5956       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5957         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5958         
5959       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5960         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5961       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5962         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5963       break;
5964     }
5965   }
5966
5967   // Test if the ICmpInst instruction is used exclusively by a select as
5968   // part of a minimum or maximum operation. If so, refrain from doing
5969   // any other folding. This helps out other analyses which understand
5970   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5971   // and CodeGen. And in this case, at least one of the comparison
5972   // operands has at least one user besides the compare (the select),
5973   // which would often largely negate the benefit of folding anyway.
5974   if (I.hasOneUse())
5975     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5976       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5977           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5978         return 0;
5979
5980   // See if we are doing a comparison between a constant and an instruction that
5981   // can be folded into the comparison.
5982   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5983     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5984     // instruction, see if that instruction also has constants so that the 
5985     // instruction can be folded into the icmp 
5986     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5987       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5988         return Res;
5989   }
5990
5991   // Handle icmp with constant (but not simple integer constant) RHS
5992   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5993     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5994       switch (LHSI->getOpcode()) {
5995       case Instruction::GetElementPtr:
5996         if (RHSC->isNullValue()) {
5997           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5998           bool isAllZeros = true;
5999           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6000             if (!isa<Constant>(LHSI->getOperand(i)) ||
6001                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6002               isAllZeros = false;
6003               break;
6004             }
6005           if (isAllZeros)
6006             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6007                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6008         }
6009         break;
6010
6011       case Instruction::PHI:
6012         // Only fold icmp into the PHI if the phi and fcmp are in the same
6013         // block.  If in the same block, we're encouraging jump threading.  If
6014         // not, we are just pessimizing the code by making an i1 phi.
6015         if (LHSI->getParent() == I.getParent())
6016           if (Instruction *NV = FoldOpIntoPhi(I))
6017             return NV;
6018         break;
6019       case Instruction::Select: {
6020         // If either operand of the select is a constant, we can fold the
6021         // comparison into the select arms, which will cause one to be
6022         // constant folded and the select turned into a bitwise or.
6023         Value *Op1 = 0, *Op2 = 0;
6024         if (LHSI->hasOneUse()) {
6025           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6026             // Fold the known value into the constant operand.
6027             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6028             // Insert a new ICmp of the other select operand.
6029             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6030                                                    LHSI->getOperand(2), RHSC,
6031                                                    I.getName()), I);
6032           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6033             // Fold the known value into the constant operand.
6034             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6035             // Insert a new ICmp of the other select operand.
6036             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6037                                                    LHSI->getOperand(1), RHSC,
6038                                                    I.getName()), I);
6039           }
6040         }
6041
6042         if (Op1)
6043           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6044         break;
6045       }
6046       case Instruction::Malloc:
6047         // If we have (malloc != null), and if the malloc has a single use, we
6048         // can assume it is successful and remove the malloc.
6049         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6050           AddToWorkList(LHSI);
6051           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6052                                                          !I.isTrueWhenEqual()));
6053         }
6054         break;
6055       }
6056   }
6057
6058   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6059   if (User *GEP = dyn_castGetElementPtr(Op0))
6060     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6061       return NI;
6062   if (User *GEP = dyn_castGetElementPtr(Op1))
6063     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6064                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6065       return NI;
6066
6067   // Test to see if the operands of the icmp are casted versions of other
6068   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6069   // now.
6070   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6071     if (isa<PointerType>(Op0->getType()) && 
6072         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6073       // We keep moving the cast from the left operand over to the right
6074       // operand, where it can often be eliminated completely.
6075       Op0 = CI->getOperand(0);
6076
6077       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6078       // so eliminate it as well.
6079       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6080         Op1 = CI2->getOperand(0);
6081
6082       // If Op1 is a constant, we can fold the cast into the constant.
6083       if (Op0->getType() != Op1->getType()) {
6084         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6085           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6086         } else {
6087           // Otherwise, cast the RHS right before the icmp
6088           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6089         }
6090       }
6091       return new ICmpInst(I.getPredicate(), Op0, Op1);
6092     }
6093   }
6094   
6095   if (isa<CastInst>(Op0)) {
6096     // Handle the special case of: icmp (cast bool to X), <cst>
6097     // This comes up when you have code like
6098     //   int X = A < B;
6099     //   if (X) ...
6100     // For generality, we handle any zero-extension of any operand comparison
6101     // with a constant or another cast from the same type.
6102     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6103       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6104         return R;
6105   }
6106   
6107   // See if it's the same type of instruction on the left and right.
6108   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6109     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6110       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6111           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6112         switch (Op0I->getOpcode()) {
6113         default: break;
6114         case Instruction::Add:
6115         case Instruction::Sub:
6116         case Instruction::Xor:
6117           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6118             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6119                                 Op1I->getOperand(0));
6120           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6121           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6122             if (CI->getValue().isSignBit()) {
6123               ICmpInst::Predicate Pred = I.isSignedPredicate()
6124                                              ? I.getUnsignedPredicate()
6125                                              : I.getSignedPredicate();
6126               return new ICmpInst(Pred, Op0I->getOperand(0),
6127                                   Op1I->getOperand(0));
6128             }
6129             
6130             if (CI->getValue().isMaxSignedValue()) {
6131               ICmpInst::Predicate Pred = I.isSignedPredicate()
6132                                              ? I.getUnsignedPredicate()
6133                                              : I.getSignedPredicate();
6134               Pred = I.getSwappedPredicate(Pred);
6135               return new ICmpInst(Pred, Op0I->getOperand(0),
6136                                   Op1I->getOperand(0));
6137             }
6138           }
6139           break;
6140         case Instruction::Mul:
6141           if (!I.isEquality())
6142             break;
6143
6144           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6145             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6146             // Mask = -1 >> count-trailing-zeros(Cst).
6147             if (!CI->isZero() && !CI->isOne()) {
6148               const APInt &AP = CI->getValue();
6149               ConstantInt *Mask = ConstantInt::get(
6150                                       APInt::getLowBitsSet(AP.getBitWidth(),
6151                                                            AP.getBitWidth() -
6152                                                       AP.countTrailingZeros()));
6153               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6154                                                             Mask);
6155               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6156                                                             Mask);
6157               InsertNewInstBefore(And1, I);
6158               InsertNewInstBefore(And2, I);
6159               return new ICmpInst(I.getPredicate(), And1, And2);
6160             }
6161           }
6162           break;
6163         }
6164       }
6165     }
6166   }
6167   
6168   // ~x < ~y --> y < x
6169   { Value *A, *B;
6170     if (match(Op0, m_Not(m_Value(A))) &&
6171         match(Op1, m_Not(m_Value(B))))
6172       return new ICmpInst(I.getPredicate(), B, A);
6173   }
6174   
6175   if (I.isEquality()) {
6176     Value *A, *B, *C, *D;
6177     
6178     // -x == -y --> x == y
6179     if (match(Op0, m_Neg(m_Value(A))) &&
6180         match(Op1, m_Neg(m_Value(B))))
6181       return new ICmpInst(I.getPredicate(), A, B);
6182     
6183     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6184       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6185         Value *OtherVal = A == Op1 ? B : A;
6186         return new ICmpInst(I.getPredicate(), OtherVal,
6187                             Constant::getNullValue(A->getType()));
6188       }
6189
6190       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6191         // A^c1 == C^c2 --> A == C^(c1^c2)
6192         ConstantInt *C1, *C2;
6193         if (match(B, m_ConstantInt(C1)) &&
6194             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6195           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6196           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6197           return new ICmpInst(I.getPredicate(), A,
6198                               InsertNewInstBefore(Xor, I));
6199         }
6200         
6201         // A^B == A^D -> B == D
6202         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6203         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6204         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6205         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6206       }
6207     }
6208     
6209     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6210         (A == Op0 || B == Op0)) {
6211       // A == (A^B)  ->  B == 0
6212       Value *OtherVal = A == Op0 ? B : A;
6213       return new ICmpInst(I.getPredicate(), OtherVal,
6214                           Constant::getNullValue(A->getType()));
6215     }
6216
6217     // (A-B) == A  ->  B == 0
6218     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6219       return new ICmpInst(I.getPredicate(), B, 
6220                           Constant::getNullValue(B->getType()));
6221
6222     // A == (A-B)  ->  B == 0
6223     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6224       return new ICmpInst(I.getPredicate(), B,
6225                           Constant::getNullValue(B->getType()));
6226     
6227     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6228     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6229         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6230         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6231       Value *X = 0, *Y = 0, *Z = 0;
6232       
6233       if (A == C) {
6234         X = B; Y = D; Z = A;
6235       } else if (A == D) {
6236         X = B; Y = C; Z = A;
6237       } else if (B == C) {
6238         X = A; Y = D; Z = B;
6239       } else if (B == D) {
6240         X = A; Y = C; Z = B;
6241       }
6242       
6243       if (X) {   // Build (X^Y) & Z
6244         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6245         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6246         I.setOperand(0, Op1);
6247         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6248         return &I;
6249       }
6250     }
6251   }
6252   return Changed ? &I : 0;
6253 }
6254
6255
6256 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6257 /// and CmpRHS are both known to be integer constants.
6258 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6259                                           ConstantInt *DivRHS) {
6260   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6261   const APInt &CmpRHSV = CmpRHS->getValue();
6262   
6263   // FIXME: If the operand types don't match the type of the divide 
6264   // then don't attempt this transform. The code below doesn't have the
6265   // logic to deal with a signed divide and an unsigned compare (and
6266   // vice versa). This is because (x /s C1) <s C2  produces different 
6267   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6268   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6269   // work. :(  The if statement below tests that condition and bails 
6270   // if it finds it. 
6271   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6272   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6273     return 0;
6274   if (DivRHS->isZero())
6275     return 0; // The ProdOV computation fails on divide by zero.
6276   if (DivIsSigned && DivRHS->isAllOnesValue())
6277     return 0; // The overflow computation also screws up here
6278   if (DivRHS->isOne())
6279     return 0; // Not worth bothering, and eliminates some funny cases
6280               // with INT_MIN.
6281
6282   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6283   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6284   // C2 (CI). By solving for X we can turn this into a range check 
6285   // instead of computing a divide. 
6286   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6287
6288   // Determine if the product overflows by seeing if the product is
6289   // not equal to the divide. Make sure we do the same kind of divide
6290   // as in the LHS instruction that we're folding. 
6291   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6292                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6293
6294   // Get the ICmp opcode
6295   ICmpInst::Predicate Pred = ICI.getPredicate();
6296
6297   // Figure out the interval that is being checked.  For example, a comparison
6298   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6299   // Compute this interval based on the constants involved and the signedness of
6300   // the compare/divide.  This computes a half-open interval, keeping track of
6301   // whether either value in the interval overflows.  After analysis each
6302   // overflow variable is set to 0 if it's corresponding bound variable is valid
6303   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6304   int LoOverflow = 0, HiOverflow = 0;
6305   ConstantInt *LoBound = 0, *HiBound = 0;
6306   
6307   if (!DivIsSigned) {  // udiv
6308     // e.g. X/5 op 3  --> [15, 20)
6309     LoBound = Prod;
6310     HiOverflow = LoOverflow = ProdOV;
6311     if (!HiOverflow)
6312       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6313   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6314     if (CmpRHSV == 0) {       // (X / pos) op 0
6315       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6316       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6317       HiBound = DivRHS;
6318     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6319       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6320       HiOverflow = LoOverflow = ProdOV;
6321       if (!HiOverflow)
6322         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6323     } else {                       // (X / pos) op neg
6324       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6325       HiBound = AddOne(Prod);
6326       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6327       if (!LoOverflow) {
6328         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6329         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6330                                      true) ? -1 : 0;
6331        }
6332     }
6333   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6334     if (CmpRHSV == 0) {       // (X / neg) op 0
6335       // e.g. X/-5 op 0  --> [-4, 5)
6336       LoBound = AddOne(DivRHS);
6337       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6338       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6339         HiOverflow = 1;            // [INTMIN+1, overflow)
6340         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6341       }
6342     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6343       // e.g. X/-5 op 3  --> [-19, -14)
6344       HiBound = AddOne(Prod);
6345       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6346       if (!LoOverflow)
6347         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6348     } else {                       // (X / neg) op neg
6349       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6350       LoOverflow = HiOverflow = ProdOV;
6351       if (!HiOverflow)
6352         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6353     }
6354     
6355     // Dividing by a negative swaps the condition.  LT <-> GT
6356     Pred = ICmpInst::getSwappedPredicate(Pred);
6357   }
6358
6359   Value *X = DivI->getOperand(0);
6360   switch (Pred) {
6361   default: assert(0 && "Unhandled icmp opcode!");
6362   case ICmpInst::ICMP_EQ:
6363     if (LoOverflow && HiOverflow)
6364       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6365     else if (HiOverflow)
6366       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6367                           ICmpInst::ICMP_UGE, X, LoBound);
6368     else if (LoOverflow)
6369       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6370                           ICmpInst::ICMP_ULT, X, HiBound);
6371     else
6372       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6373   case ICmpInst::ICMP_NE:
6374     if (LoOverflow && HiOverflow)
6375       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6376     else if (HiOverflow)
6377       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6378                           ICmpInst::ICMP_ULT, X, LoBound);
6379     else if (LoOverflow)
6380       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6381                           ICmpInst::ICMP_UGE, X, HiBound);
6382     else
6383       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6384   case ICmpInst::ICMP_ULT:
6385   case ICmpInst::ICMP_SLT:
6386     if (LoOverflow == +1)   // Low bound is greater than input range.
6387       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6388     if (LoOverflow == -1)   // Low bound is less than input range.
6389       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6390     return new ICmpInst(Pred, X, LoBound);
6391   case ICmpInst::ICMP_UGT:
6392   case ICmpInst::ICMP_SGT:
6393     if (HiOverflow == +1)       // High bound greater than input range.
6394       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6395     else if (HiOverflow == -1)  // High bound less than input range.
6396       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6397     if (Pred == ICmpInst::ICMP_UGT)
6398       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6399     else
6400       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6401   }
6402 }
6403
6404
6405 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6406 ///
6407 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6408                                                           Instruction *LHSI,
6409                                                           ConstantInt *RHS) {
6410   const APInt &RHSV = RHS->getValue();
6411   
6412   switch (LHSI->getOpcode()) {
6413   case Instruction::Trunc:
6414     if (ICI.isEquality() && LHSI->hasOneUse()) {
6415       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6416       // of the high bits truncated out of x are known.
6417       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6418              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6419       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6420       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6421       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6422       
6423       // If all the high bits are known, we can do this xform.
6424       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6425         // Pull in the high bits from known-ones set.
6426         APInt NewRHS(RHS->getValue());
6427         NewRHS.zext(SrcBits);
6428         NewRHS |= KnownOne;
6429         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6430                             ConstantInt::get(NewRHS));
6431       }
6432     }
6433     break;
6434       
6435   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6436     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6437       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6438       // fold the xor.
6439       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6440           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6441         Value *CompareVal = LHSI->getOperand(0);
6442         
6443         // If the sign bit of the XorCST is not set, there is no change to
6444         // the operation, just stop using the Xor.
6445         if (!XorCST->getValue().isNegative()) {
6446           ICI.setOperand(0, CompareVal);
6447           AddToWorkList(LHSI);
6448           return &ICI;
6449         }
6450         
6451         // Was the old condition true if the operand is positive?
6452         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6453         
6454         // If so, the new one isn't.
6455         isTrueIfPositive ^= true;
6456         
6457         if (isTrueIfPositive)
6458           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6459         else
6460           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6461       }
6462
6463       if (LHSI->hasOneUse()) {
6464         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6465         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6466           const APInt &SignBit = XorCST->getValue();
6467           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6468                                          ? ICI.getUnsignedPredicate()
6469                                          : ICI.getSignedPredicate();
6470           return new ICmpInst(Pred, LHSI->getOperand(0),
6471                               ConstantInt::get(RHSV ^ SignBit));
6472         }
6473
6474         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6475         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6476           const APInt &NotSignBit = XorCST->getValue();
6477           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6478                                          ? ICI.getUnsignedPredicate()
6479                                          : ICI.getSignedPredicate();
6480           Pred = ICI.getSwappedPredicate(Pred);
6481           return new ICmpInst(Pred, LHSI->getOperand(0),
6482                               ConstantInt::get(RHSV ^ NotSignBit));
6483         }
6484       }
6485     }
6486     break;
6487   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6488     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6489         LHSI->getOperand(0)->hasOneUse()) {
6490       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6491       
6492       // If the LHS is an AND of a truncating cast, we can widen the
6493       // and/compare to be the input width without changing the value
6494       // produced, eliminating a cast.
6495       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6496         // We can do this transformation if either the AND constant does not
6497         // have its sign bit set or if it is an equality comparison. 
6498         // Extending a relational comparison when we're checking the sign
6499         // bit would not work.
6500         if (Cast->hasOneUse() &&
6501             (ICI.isEquality() ||
6502              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6503           uint32_t BitWidth = 
6504             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6505           APInt NewCST = AndCST->getValue();
6506           NewCST.zext(BitWidth);
6507           APInt NewCI = RHSV;
6508           NewCI.zext(BitWidth);
6509           Instruction *NewAnd = 
6510             BinaryOperator::CreateAnd(Cast->getOperand(0),
6511                                       ConstantInt::get(NewCST),LHSI->getName());
6512           InsertNewInstBefore(NewAnd, ICI);
6513           return new ICmpInst(ICI.getPredicate(), NewAnd,
6514                               ConstantInt::get(NewCI));
6515         }
6516       }
6517       
6518       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6519       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6520       // happens a LOT in code produced by the C front-end, for bitfield
6521       // access.
6522       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6523       if (Shift && !Shift->isShift())
6524         Shift = 0;
6525       
6526       ConstantInt *ShAmt;
6527       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6528       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6529       const Type *AndTy = AndCST->getType();          // Type of the and.
6530       
6531       // We can fold this as long as we can't shift unknown bits
6532       // into the mask.  This can only happen with signed shift
6533       // rights, as they sign-extend.
6534       if (ShAmt) {
6535         bool CanFold = Shift->isLogicalShift();
6536         if (!CanFold) {
6537           // To test for the bad case of the signed shr, see if any
6538           // of the bits shifted in could be tested after the mask.
6539           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6540           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6541           
6542           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6543           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6544                AndCST->getValue()) == 0)
6545             CanFold = true;
6546         }
6547         
6548         if (CanFold) {
6549           Constant *NewCst;
6550           if (Shift->getOpcode() == Instruction::Shl)
6551             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6552           else
6553             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6554           
6555           // Check to see if we are shifting out any of the bits being
6556           // compared.
6557           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6558             // If we shifted bits out, the fold is not going to work out.
6559             // As a special case, check to see if this means that the
6560             // result is always true or false now.
6561             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6562               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6563             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6564               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6565           } else {
6566             ICI.setOperand(1, NewCst);
6567             Constant *NewAndCST;
6568             if (Shift->getOpcode() == Instruction::Shl)
6569               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6570             else
6571               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6572             LHSI->setOperand(1, NewAndCST);
6573             LHSI->setOperand(0, Shift->getOperand(0));
6574             AddToWorkList(Shift); // Shift is dead.
6575             AddUsesToWorkList(ICI);
6576             return &ICI;
6577           }
6578         }
6579       }
6580       
6581       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6582       // preferable because it allows the C<<Y expression to be hoisted out
6583       // of a loop if Y is invariant and X is not.
6584       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6585           ICI.isEquality() && !Shift->isArithmeticShift() &&
6586           !isa<Constant>(Shift->getOperand(0))) {
6587         // Compute C << Y.
6588         Value *NS;
6589         if (Shift->getOpcode() == Instruction::LShr) {
6590           NS = BinaryOperator::CreateShl(AndCST, 
6591                                          Shift->getOperand(1), "tmp");
6592         } else {
6593           // Insert a logical shift.
6594           NS = BinaryOperator::CreateLShr(AndCST,
6595                                           Shift->getOperand(1), "tmp");
6596         }
6597         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6598         
6599         // Compute X & (C << Y).
6600         Instruction *NewAnd = 
6601           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6602         InsertNewInstBefore(NewAnd, ICI);
6603         
6604         ICI.setOperand(0, NewAnd);
6605         return &ICI;
6606       }
6607     }
6608     break;
6609     
6610   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6611     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6612     if (!ShAmt) break;
6613     
6614     uint32_t TypeBits = RHSV.getBitWidth();
6615     
6616     // Check that the shift amount is in range.  If not, don't perform
6617     // undefined shifts.  When the shift is visited it will be
6618     // simplified.
6619     if (ShAmt->uge(TypeBits))
6620       break;
6621     
6622     if (ICI.isEquality()) {
6623       // If we are comparing against bits always shifted out, the
6624       // comparison cannot succeed.
6625       Constant *Comp =
6626         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6627       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6628         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6629         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6630         return ReplaceInstUsesWith(ICI, Cst);
6631       }
6632       
6633       if (LHSI->hasOneUse()) {
6634         // Otherwise strength reduce the shift into an and.
6635         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6636         Constant *Mask =
6637           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6638         
6639         Instruction *AndI =
6640           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6641                                     Mask, LHSI->getName()+".mask");
6642         Value *And = InsertNewInstBefore(AndI, ICI);
6643         return new ICmpInst(ICI.getPredicate(), And,
6644                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6645       }
6646     }
6647     
6648     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6649     bool TrueIfSigned = false;
6650     if (LHSI->hasOneUse() &&
6651         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6652       // (X << 31) <s 0  --> (X&1) != 0
6653       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6654                                            (TypeBits-ShAmt->getZExtValue()-1));
6655       Instruction *AndI =
6656         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6657                                   Mask, LHSI->getName()+".mask");
6658       Value *And = InsertNewInstBefore(AndI, ICI);
6659       
6660       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6661                           And, Constant::getNullValue(And->getType()));
6662     }
6663     break;
6664   }
6665     
6666   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6667   case Instruction::AShr: {
6668     // Only handle equality comparisons of shift-by-constant.
6669     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6670     if (!ShAmt || !ICI.isEquality()) break;
6671
6672     // Check that the shift amount is in range.  If not, don't perform
6673     // undefined shifts.  When the shift is visited it will be
6674     // simplified.
6675     uint32_t TypeBits = RHSV.getBitWidth();
6676     if (ShAmt->uge(TypeBits))
6677       break;
6678     
6679     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6680       
6681     // If we are comparing against bits always shifted out, the
6682     // comparison cannot succeed.
6683     APInt Comp = RHSV << ShAmtVal;
6684     if (LHSI->getOpcode() == Instruction::LShr)
6685       Comp = Comp.lshr(ShAmtVal);
6686     else
6687       Comp = Comp.ashr(ShAmtVal);
6688     
6689     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6690       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6691       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6692       return ReplaceInstUsesWith(ICI, Cst);
6693     }
6694     
6695     // Otherwise, check to see if the bits shifted out are known to be zero.
6696     // If so, we can compare against the unshifted value:
6697     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6698     if (LHSI->hasOneUse() &&
6699         MaskedValueIsZero(LHSI->getOperand(0), 
6700                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6701       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6702                           ConstantExpr::getShl(RHS, ShAmt));
6703     }
6704       
6705     if (LHSI->hasOneUse()) {
6706       // Otherwise strength reduce the shift into an and.
6707       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6708       Constant *Mask = ConstantInt::get(Val);
6709       
6710       Instruction *AndI =
6711         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6712                                   Mask, LHSI->getName()+".mask");
6713       Value *And = InsertNewInstBefore(AndI, ICI);
6714       return new ICmpInst(ICI.getPredicate(), And,
6715                           ConstantExpr::getShl(RHS, ShAmt));
6716     }
6717     break;
6718   }
6719     
6720   case Instruction::SDiv:
6721   case Instruction::UDiv:
6722     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6723     // Fold this div into the comparison, producing a range check. 
6724     // Determine, based on the divide type, what the range is being 
6725     // checked.  If there is an overflow on the low or high side, remember 
6726     // it, otherwise compute the range [low, hi) bounding the new value.
6727     // See: InsertRangeTest above for the kinds of replacements possible.
6728     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6729       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6730                                           DivRHS))
6731         return R;
6732     break;
6733
6734   case Instruction::Add:
6735     // Fold: icmp pred (add, X, C1), C2
6736
6737     if (!ICI.isEquality()) {
6738       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6739       if (!LHSC) break;
6740       const APInt &LHSV = LHSC->getValue();
6741
6742       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6743                             .subtract(LHSV);
6744
6745       if (ICI.isSignedPredicate()) {
6746         if (CR.getLower().isSignBit()) {
6747           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6748                               ConstantInt::get(CR.getUpper()));
6749         } else if (CR.getUpper().isSignBit()) {
6750           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6751                               ConstantInt::get(CR.getLower()));
6752         }
6753       } else {
6754         if (CR.getLower().isMinValue()) {
6755           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6756                               ConstantInt::get(CR.getUpper()));
6757         } else if (CR.getUpper().isMinValue()) {
6758           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6759                               ConstantInt::get(CR.getLower()));
6760         }
6761       }
6762     }
6763     break;
6764   }
6765   
6766   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6767   if (ICI.isEquality()) {
6768     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6769     
6770     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6771     // the second operand is a constant, simplify a bit.
6772     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6773       switch (BO->getOpcode()) {
6774       case Instruction::SRem:
6775         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6776         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6777           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6778           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6779             Instruction *NewRem =
6780               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6781                                          BO->getName());
6782             InsertNewInstBefore(NewRem, ICI);
6783             return new ICmpInst(ICI.getPredicate(), NewRem, 
6784                                 Constant::getNullValue(BO->getType()));
6785           }
6786         }
6787         break;
6788       case Instruction::Add:
6789         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6790         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6791           if (BO->hasOneUse())
6792             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6793                                 Subtract(RHS, BOp1C));
6794         } else if (RHSV == 0) {
6795           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6796           // efficiently invertible, or if the add has just this one use.
6797           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6798           
6799           if (Value *NegVal = dyn_castNegVal(BOp1))
6800             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6801           else if (Value *NegVal = dyn_castNegVal(BOp0))
6802             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6803           else if (BO->hasOneUse()) {
6804             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6805             InsertNewInstBefore(Neg, ICI);
6806             Neg->takeName(BO);
6807             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6808           }
6809         }
6810         break;
6811       case Instruction::Xor:
6812         // For the xor case, we can xor two constants together, eliminating
6813         // the explicit xor.
6814         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6815           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6816                               ConstantExpr::getXor(RHS, BOC));
6817         
6818         // FALLTHROUGH
6819       case Instruction::Sub:
6820         // Replace (([sub|xor] A, B) != 0) with (A != B)
6821         if (RHSV == 0)
6822           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6823                               BO->getOperand(1));
6824         break;
6825         
6826       case Instruction::Or:
6827         // If bits are being or'd in that are not present in the constant we
6828         // are comparing against, then the comparison could never succeed!
6829         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6830           Constant *NotCI = ConstantExpr::getNot(RHS);
6831           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6832             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6833                                                              isICMP_NE));
6834         }
6835         break;
6836         
6837       case Instruction::And:
6838         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6839           // If bits are being compared against that are and'd out, then the
6840           // comparison can never succeed!
6841           if ((RHSV & ~BOC->getValue()) != 0)
6842             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6843                                                              isICMP_NE));
6844           
6845           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6846           if (RHS == BOC && RHSV.isPowerOf2())
6847             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6848                                 ICmpInst::ICMP_NE, LHSI,
6849                                 Constant::getNullValue(RHS->getType()));
6850           
6851           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6852           if (BOC->getValue().isSignBit()) {
6853             Value *X = BO->getOperand(0);
6854             Constant *Zero = Constant::getNullValue(X->getType());
6855             ICmpInst::Predicate pred = isICMP_NE ? 
6856               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6857             return new ICmpInst(pred, X, Zero);
6858           }
6859           
6860           // ((X & ~7) == 0) --> X < 8
6861           if (RHSV == 0 && isHighOnes(BOC)) {
6862             Value *X = BO->getOperand(0);
6863             Constant *NegX = ConstantExpr::getNeg(BOC);
6864             ICmpInst::Predicate pred = isICMP_NE ? 
6865               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6866             return new ICmpInst(pred, X, NegX);
6867           }
6868         }
6869       default: break;
6870       }
6871     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6872       // Handle icmp {eq|ne} <intrinsic>, intcst.
6873       if (II->getIntrinsicID() == Intrinsic::bswap) {
6874         AddToWorkList(II);
6875         ICI.setOperand(0, II->getOperand(1));
6876         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6877         return &ICI;
6878       }
6879     }
6880   }
6881   return 0;
6882 }
6883
6884 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6885 /// We only handle extending casts so far.
6886 ///
6887 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6888   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6889   Value *LHSCIOp        = LHSCI->getOperand(0);
6890   const Type *SrcTy     = LHSCIOp->getType();
6891   const Type *DestTy    = LHSCI->getType();
6892   Value *RHSCIOp;
6893
6894   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6895   // integer type is the same size as the pointer type.
6896   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6897       getTargetData().getPointerSizeInBits() == 
6898          cast<IntegerType>(DestTy)->getBitWidth()) {
6899     Value *RHSOp = 0;
6900     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6901       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6902     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6903       RHSOp = RHSC->getOperand(0);
6904       // If the pointer types don't match, insert a bitcast.
6905       if (LHSCIOp->getType() != RHSOp->getType())
6906         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6907     }
6908
6909     if (RHSOp)
6910       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6911   }
6912   
6913   // The code below only handles extension cast instructions, so far.
6914   // Enforce this.
6915   if (LHSCI->getOpcode() != Instruction::ZExt &&
6916       LHSCI->getOpcode() != Instruction::SExt)
6917     return 0;
6918
6919   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6920   bool isSignedCmp = ICI.isSignedPredicate();
6921
6922   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6923     // Not an extension from the same type?
6924     RHSCIOp = CI->getOperand(0);
6925     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6926       return 0;
6927     
6928     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6929     // and the other is a zext), then we can't handle this.
6930     if (CI->getOpcode() != LHSCI->getOpcode())
6931       return 0;
6932
6933     // Deal with equality cases early.
6934     if (ICI.isEquality())
6935       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6936
6937     // A signed comparison of sign extended values simplifies into a
6938     // signed comparison.
6939     if (isSignedCmp && isSignedExt)
6940       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6941
6942     // The other three cases all fold into an unsigned comparison.
6943     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6944   }
6945
6946   // If we aren't dealing with a constant on the RHS, exit early
6947   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6948   if (!CI)
6949     return 0;
6950
6951   // Compute the constant that would happen if we truncated to SrcTy then
6952   // reextended to DestTy.
6953   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6954   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6955
6956   // If the re-extended constant didn't change...
6957   if (Res2 == CI) {
6958     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6959     // For example, we might have:
6960     //    %A = sext short %X to uint
6961     //    %B = icmp ugt uint %A, 1330
6962     // It is incorrect to transform this into 
6963     //    %B = icmp ugt short %X, 1330 
6964     // because %A may have negative value. 
6965     //
6966     // However, we allow this when the compare is EQ/NE, because they are
6967     // signless.
6968     if (isSignedExt == isSignedCmp || ICI.isEquality())
6969       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6970     return 0;
6971   }
6972
6973   // The re-extended constant changed so the constant cannot be represented 
6974   // in the shorter type. Consequently, we cannot emit a simple comparison.
6975
6976   // First, handle some easy cases. We know the result cannot be equal at this
6977   // point so handle the ICI.isEquality() cases
6978   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6979     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6980   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6981     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6982
6983   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6984   // should have been folded away previously and not enter in here.
6985   Value *Result;
6986   if (isSignedCmp) {
6987     // We're performing a signed comparison.
6988     if (cast<ConstantInt>(CI)->getValue().isNegative())
6989       Result = ConstantInt::getFalse();          // X < (small) --> false
6990     else
6991       Result = ConstantInt::getTrue();           // X < (large) --> true
6992   } else {
6993     // We're performing an unsigned comparison.
6994     if (isSignedExt) {
6995       // We're performing an unsigned comp with a sign extended value.
6996       // This is true if the input is >= 0. [aka >s -1]
6997       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6998       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6999                                    NegOne, ICI.getName()), ICI);
7000     } else {
7001       // Unsigned extend & unsigned compare -> always true.
7002       Result = ConstantInt::getTrue();
7003     }
7004   }
7005
7006   // Finally, return the value computed.
7007   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7008       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7009     return ReplaceInstUsesWith(ICI, Result);
7010
7011   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7012           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7013          "ICmp should be folded!");
7014   if (Constant *CI = dyn_cast<Constant>(Result))
7015     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7016   return BinaryOperator::CreateNot(Result);
7017 }
7018
7019 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7020   return commonShiftTransforms(I);
7021 }
7022
7023 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7024   return commonShiftTransforms(I);
7025 }
7026
7027 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7028   if (Instruction *R = commonShiftTransforms(I))
7029     return R;
7030   
7031   Value *Op0 = I.getOperand(0);
7032   
7033   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7034   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7035     if (CSI->isAllOnesValue())
7036       return ReplaceInstUsesWith(I, CSI);
7037   
7038   // See if we can turn a signed shr into an unsigned shr.
7039   if (!isa<VectorType>(I.getType())) {
7040     if (MaskedValueIsZero(Op0,
7041                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
7042       return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7043
7044     // Arithmetic shifting an all-sign-bit value is a no-op.
7045     unsigned NumSignBits = ComputeNumSignBits(Op0);
7046     if (NumSignBits == Op0->getType()->getPrimitiveSizeInBits())
7047       return ReplaceInstUsesWith(I, Op0);
7048   }
7049
7050   return 0;
7051 }
7052
7053 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7054   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7055   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7056
7057   // shl X, 0 == X and shr X, 0 == X
7058   // shl 0, X == 0 and shr 0, X == 0
7059   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7060       Op0 == Constant::getNullValue(Op0->getType()))
7061     return ReplaceInstUsesWith(I, Op0);
7062   
7063   if (isa<UndefValue>(Op0)) {            
7064     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7065       return ReplaceInstUsesWith(I, Op0);
7066     else                                    // undef << X -> 0, undef >>u X -> 0
7067       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7068   }
7069   if (isa<UndefValue>(Op1)) {
7070     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7071       return ReplaceInstUsesWith(I, Op0);          
7072     else                                     // X << undef, X >>u undef -> 0
7073       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7074   }
7075
7076   // Try to fold constant and into select arguments.
7077   if (isa<Constant>(Op0))
7078     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7079       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7080         return R;
7081
7082   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7083     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7084       return Res;
7085   return 0;
7086 }
7087
7088 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7089                                                BinaryOperator &I) {
7090   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7091
7092   // See if we can simplify any instructions used by the instruction whose sole 
7093   // purpose is to compute bits we don't care about.
7094   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
7095   if (SimplifyDemandedInstructionBits(I))
7096     return &I;
7097   
7098   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7099   // of a signed value.
7100   //
7101   if (Op1->uge(TypeBits)) {
7102     if (I.getOpcode() != Instruction::AShr)
7103       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7104     else {
7105       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7106       return &I;
7107     }
7108   }
7109   
7110   // ((X*C1) << C2) == (X * (C1 << C2))
7111   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7112     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7113       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7114         return BinaryOperator::CreateMul(BO->getOperand(0),
7115                                          ConstantExpr::getShl(BOOp, Op1));
7116   
7117   // Try to fold constant and into select arguments.
7118   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7119     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7120       return R;
7121   if (isa<PHINode>(Op0))
7122     if (Instruction *NV = FoldOpIntoPhi(I))
7123       return NV;
7124   
7125   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7126   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7127     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7128     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7129     // place.  Don't try to do this transformation in this case.  Also, we
7130     // require that the input operand is a shift-by-constant so that we have
7131     // confidence that the shifts will get folded together.  We could do this
7132     // xform in more cases, but it is unlikely to be profitable.
7133     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7134         isa<ConstantInt>(TrOp->getOperand(1))) {
7135       // Okay, we'll do this xform.  Make the shift of shift.
7136       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7137       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7138                                                 I.getName());
7139       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7140
7141       // For logical shifts, the truncation has the effect of making the high
7142       // part of the register be zeros.  Emulate this by inserting an AND to
7143       // clear the top bits as needed.  This 'and' will usually be zapped by
7144       // other xforms later if dead.
7145       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7146       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7147       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7148       
7149       // The mask we constructed says what the trunc would do if occurring
7150       // between the shifts.  We want to know the effect *after* the second
7151       // shift.  We know that it is a logical shift by a constant, so adjust the
7152       // mask as appropriate.
7153       if (I.getOpcode() == Instruction::Shl)
7154         MaskV <<= Op1->getZExtValue();
7155       else {
7156         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7157         MaskV = MaskV.lshr(Op1->getZExtValue());
7158       }
7159
7160       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7161                                                    TI->getName());
7162       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7163
7164       // Return the value truncated to the interesting size.
7165       return new TruncInst(And, I.getType());
7166     }
7167   }
7168   
7169   if (Op0->hasOneUse()) {
7170     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7171       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7172       Value *V1, *V2;
7173       ConstantInt *CC;
7174       switch (Op0BO->getOpcode()) {
7175         default: break;
7176         case Instruction::Add:
7177         case Instruction::And:
7178         case Instruction::Or:
7179         case Instruction::Xor: {
7180           // These operators commute.
7181           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7182           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7183               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7184             Instruction *YS = BinaryOperator::CreateShl(
7185                                             Op0BO->getOperand(0), Op1,
7186                                             Op0BO->getName());
7187             InsertNewInstBefore(YS, I); // (Y << C)
7188             Instruction *X = 
7189               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7190                                      Op0BO->getOperand(1)->getName());
7191             InsertNewInstBefore(X, I);  // (X + (Y << C))
7192             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7193             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7194                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7195           }
7196           
7197           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7198           Value *Op0BOOp1 = Op0BO->getOperand(1);
7199           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7200               match(Op0BOOp1, 
7201                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7202                           m_ConstantInt(CC))) &&
7203               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7204             Instruction *YS = BinaryOperator::CreateShl(
7205                                                      Op0BO->getOperand(0), Op1,
7206                                                      Op0BO->getName());
7207             InsertNewInstBefore(YS, I); // (Y << C)
7208             Instruction *XM =
7209               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7210                                         V1->getName()+".mask");
7211             InsertNewInstBefore(XM, I); // X & (CC << C)
7212             
7213             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7214           }
7215         }
7216           
7217         // FALL THROUGH.
7218         case Instruction::Sub: {
7219           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7220           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7221               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7222             Instruction *YS = BinaryOperator::CreateShl(
7223                                                      Op0BO->getOperand(1), Op1,
7224                                                      Op0BO->getName());
7225             InsertNewInstBefore(YS, I); // (Y << C)
7226             Instruction *X =
7227               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7228                                      Op0BO->getOperand(0)->getName());
7229             InsertNewInstBefore(X, I);  // (X + (Y << C))
7230             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7231             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7232                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7233           }
7234           
7235           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7236           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7237               match(Op0BO->getOperand(0),
7238                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7239                           m_ConstantInt(CC))) && V2 == Op1 &&
7240               cast<BinaryOperator>(Op0BO->getOperand(0))
7241                   ->getOperand(0)->hasOneUse()) {
7242             Instruction *YS = BinaryOperator::CreateShl(
7243                                                      Op0BO->getOperand(1), Op1,
7244                                                      Op0BO->getName());
7245             InsertNewInstBefore(YS, I); // (Y << C)
7246             Instruction *XM =
7247               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7248                                         V1->getName()+".mask");
7249             InsertNewInstBefore(XM, I); // X & (CC << C)
7250             
7251             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7252           }
7253           
7254           break;
7255         }
7256       }
7257       
7258       
7259       // If the operand is an bitwise operator with a constant RHS, and the
7260       // shift is the only use, we can pull it out of the shift.
7261       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7262         bool isValid = true;     // Valid only for And, Or, Xor
7263         bool highBitSet = false; // Transform if high bit of constant set?
7264         
7265         switch (Op0BO->getOpcode()) {
7266           default: isValid = false; break;   // Do not perform transform!
7267           case Instruction::Add:
7268             isValid = isLeftShift;
7269             break;
7270           case Instruction::Or:
7271           case Instruction::Xor:
7272             highBitSet = false;
7273             break;
7274           case Instruction::And:
7275             highBitSet = true;
7276             break;
7277         }
7278         
7279         // If this is a signed shift right, and the high bit is modified
7280         // by the logical operation, do not perform the transformation.
7281         // The highBitSet boolean indicates the value of the high bit of
7282         // the constant which would cause it to be modified for this
7283         // operation.
7284         //
7285         if (isValid && I.getOpcode() == Instruction::AShr)
7286           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7287         
7288         if (isValid) {
7289           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7290           
7291           Instruction *NewShift =
7292             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7293           InsertNewInstBefore(NewShift, I);
7294           NewShift->takeName(Op0BO);
7295           
7296           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7297                                         NewRHS);
7298         }
7299       }
7300     }
7301   }
7302   
7303   // Find out if this is a shift of a shift by a constant.
7304   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7305   if (ShiftOp && !ShiftOp->isShift())
7306     ShiftOp = 0;
7307   
7308   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7309     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7310     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7311     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7312     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7313     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7314     Value *X = ShiftOp->getOperand(0);
7315     
7316     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7317     
7318     const IntegerType *Ty = cast<IntegerType>(I.getType());
7319     
7320     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7321     if (I.getOpcode() == ShiftOp->getOpcode()) {
7322       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7323       // saturates.
7324       if (AmtSum >= TypeBits) {
7325         if (I.getOpcode() != Instruction::AShr)
7326           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7327         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7328       }
7329       
7330       return BinaryOperator::Create(I.getOpcode(), X,
7331                                     ConstantInt::get(Ty, AmtSum));
7332     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7333                I.getOpcode() == Instruction::AShr) {
7334       if (AmtSum >= TypeBits)
7335         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7336       
7337       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7338       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7339     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7340                I.getOpcode() == Instruction::LShr) {
7341       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7342       if (AmtSum >= TypeBits)
7343         AmtSum = TypeBits-1;
7344       
7345       Instruction *Shift =
7346         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7347       InsertNewInstBefore(Shift, I);
7348
7349       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7350       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7351     }
7352     
7353     // Okay, if we get here, one shift must be left, and the other shift must be
7354     // right.  See if the amounts are equal.
7355     if (ShiftAmt1 == ShiftAmt2) {
7356       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7357       if (I.getOpcode() == Instruction::Shl) {
7358         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7359         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7360       }
7361       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7362       if (I.getOpcode() == Instruction::LShr) {
7363         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7364         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7365       }
7366       // We can simplify ((X << C) >>s C) into a trunc + sext.
7367       // NOTE: we could do this for any C, but that would make 'unusual' integer
7368       // types.  For now, just stick to ones well-supported by the code
7369       // generators.
7370       const Type *SExtType = 0;
7371       switch (Ty->getBitWidth() - ShiftAmt1) {
7372       case 1  :
7373       case 8  :
7374       case 16 :
7375       case 32 :
7376       case 64 :
7377       case 128:
7378         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7379         break;
7380       default: break;
7381       }
7382       if (SExtType) {
7383         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7384         InsertNewInstBefore(NewTrunc, I);
7385         return new SExtInst(NewTrunc, Ty);
7386       }
7387       // Otherwise, we can't handle it yet.
7388     } else if (ShiftAmt1 < ShiftAmt2) {
7389       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7390       
7391       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7392       if (I.getOpcode() == Instruction::Shl) {
7393         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7394                ShiftOp->getOpcode() == Instruction::AShr);
7395         Instruction *Shift =
7396           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7397         InsertNewInstBefore(Shift, I);
7398         
7399         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7400         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7401       }
7402       
7403       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7404       if (I.getOpcode() == Instruction::LShr) {
7405         assert(ShiftOp->getOpcode() == Instruction::Shl);
7406         Instruction *Shift =
7407           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7408         InsertNewInstBefore(Shift, I);
7409         
7410         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7411         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7412       }
7413       
7414       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7415     } else {
7416       assert(ShiftAmt2 < ShiftAmt1);
7417       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7418
7419       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7420       if (I.getOpcode() == Instruction::Shl) {
7421         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7422                ShiftOp->getOpcode() == Instruction::AShr);
7423         Instruction *Shift =
7424           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7425                                  ConstantInt::get(Ty, ShiftDiff));
7426         InsertNewInstBefore(Shift, I);
7427         
7428         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7429         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7430       }
7431       
7432       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7433       if (I.getOpcode() == Instruction::LShr) {
7434         assert(ShiftOp->getOpcode() == Instruction::Shl);
7435         Instruction *Shift =
7436           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7437         InsertNewInstBefore(Shift, I);
7438         
7439         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7440         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7441       }
7442       
7443       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7444     }
7445   }
7446   return 0;
7447 }
7448
7449
7450 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7451 /// expression.  If so, decompose it, returning some value X, such that Val is
7452 /// X*Scale+Offset.
7453 ///
7454 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7455                                         int &Offset) {
7456   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7457   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7458     Offset = CI->getZExtValue();
7459     Scale  = 0;
7460     return ConstantInt::get(Type::Int32Ty, 0);
7461   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7462     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7463       if (I->getOpcode() == Instruction::Shl) {
7464         // This is a value scaled by '1 << the shift amt'.
7465         Scale = 1U << RHS->getZExtValue();
7466         Offset = 0;
7467         return I->getOperand(0);
7468       } else if (I->getOpcode() == Instruction::Mul) {
7469         // This value is scaled by 'RHS'.
7470         Scale = RHS->getZExtValue();
7471         Offset = 0;
7472         return I->getOperand(0);
7473       } else if (I->getOpcode() == Instruction::Add) {
7474         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7475         // where C1 is divisible by C2.
7476         unsigned SubScale;
7477         Value *SubVal = 
7478           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7479         Offset += RHS->getZExtValue();
7480         Scale = SubScale;
7481         return SubVal;
7482       }
7483     }
7484   }
7485
7486   // Otherwise, we can't look past this.
7487   Scale = 1;
7488   Offset = 0;
7489   return Val;
7490 }
7491
7492
7493 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7494 /// try to eliminate the cast by moving the type information into the alloc.
7495 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7496                                                    AllocationInst &AI) {
7497   const PointerType *PTy = cast<PointerType>(CI.getType());
7498   
7499   // Remove any uses of AI that are dead.
7500   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7501   
7502   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7503     Instruction *User = cast<Instruction>(*UI++);
7504     if (isInstructionTriviallyDead(User)) {
7505       while (UI != E && *UI == User)
7506         ++UI; // If this instruction uses AI more than once, don't break UI.
7507       
7508       ++NumDeadInst;
7509       DOUT << "IC: DCE: " << *User;
7510       EraseInstFromFunction(*User);
7511     }
7512   }
7513   
7514   // Get the type really allocated and the type casted to.
7515   const Type *AllocElTy = AI.getAllocatedType();
7516   const Type *CastElTy = PTy->getElementType();
7517   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7518
7519   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7520   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7521   if (CastElTyAlign < AllocElTyAlign) return 0;
7522
7523   // If the allocation has multiple uses, only promote it if we are strictly
7524   // increasing the alignment of the resultant allocation.  If we keep it the
7525   // same, we open the door to infinite loops of various kinds.  (A reference
7526   // from a dbg.declare doesn't count as a use for this purpose.)
7527   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7528       CastElTyAlign == AllocElTyAlign) return 0;
7529
7530   uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7531   uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
7532   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7533
7534   // See if we can satisfy the modulus by pulling a scale out of the array
7535   // size argument.
7536   unsigned ArraySizeScale;
7537   int ArrayOffset;
7538   Value *NumElements = // See if the array size is a decomposable linear expr.
7539     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7540  
7541   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7542   // do the xform.
7543   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7544       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7545
7546   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7547   Value *Amt = 0;
7548   if (Scale == 1) {
7549     Amt = NumElements;
7550   } else {
7551     // If the allocation size is constant, form a constant mul expression
7552     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7553     if (isa<ConstantInt>(NumElements))
7554       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7555     // otherwise multiply the amount and the number of elements
7556     else {
7557       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7558       Amt = InsertNewInstBefore(Tmp, AI);
7559     }
7560   }
7561   
7562   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7563     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7564     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7565     Amt = InsertNewInstBefore(Tmp, AI);
7566   }
7567   
7568   AllocationInst *New;
7569   if (isa<MallocInst>(AI))
7570     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7571   else
7572     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7573   InsertNewInstBefore(New, AI);
7574   New->takeName(&AI);
7575   
7576   // If the allocation has one real use plus a dbg.declare, just remove the
7577   // declare.
7578   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7579     EraseInstFromFunction(*DI);
7580   }
7581   // If the allocation has multiple real uses, insert a cast and change all
7582   // things that used it to use the new cast.  This will also hack on CI, but it
7583   // will die soon.
7584   else if (!AI.hasOneUse()) {
7585     AddUsesToWorkList(AI);
7586     // New is the allocation instruction, pointer typed. AI is the original
7587     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7588     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7589     InsertNewInstBefore(NewCast, AI);
7590     AI.replaceAllUsesWith(NewCast);
7591   }
7592   return ReplaceInstUsesWith(CI, New);
7593 }
7594
7595 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7596 /// and return it as type Ty without inserting any new casts and without
7597 /// changing the computed value.  This is used by code that tries to decide
7598 /// whether promoting or shrinking integer operations to wider or smaller types
7599 /// will allow us to eliminate a truncate or extend.
7600 ///
7601 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7602 /// extension operation if Ty is larger.
7603 ///
7604 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7605 /// should return true if trunc(V) can be computed by computing V in the smaller
7606 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7607 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7608 /// efficiently truncated.
7609 ///
7610 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7611 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7612 /// the final result.
7613 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7614                                               unsigned CastOpc,
7615                                               int &NumCastsRemoved){
7616   // We can always evaluate constants in another type.
7617   if (isa<ConstantInt>(V))
7618     return true;
7619   
7620   Instruction *I = dyn_cast<Instruction>(V);
7621   if (!I) return false;
7622   
7623   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7624   
7625   // If this is an extension or truncate, we can often eliminate it.
7626   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7627     // If this is a cast from the destination type, we can trivially eliminate
7628     // it, and this will remove a cast overall.
7629     if (I->getOperand(0)->getType() == Ty) {
7630       // If the first operand is itself a cast, and is eliminable, do not count
7631       // this as an eliminable cast.  We would prefer to eliminate those two
7632       // casts first.
7633       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7634         ++NumCastsRemoved;
7635       return true;
7636     }
7637   }
7638
7639   // We can't extend or shrink something that has multiple uses: doing so would
7640   // require duplicating the instruction in general, which isn't profitable.
7641   if (!I->hasOneUse()) return false;
7642
7643   unsigned Opc = I->getOpcode();
7644   switch (Opc) {
7645   case Instruction::Add:
7646   case Instruction::Sub:
7647   case Instruction::Mul:
7648   case Instruction::And:
7649   case Instruction::Or:
7650   case Instruction::Xor:
7651     // These operators can all arbitrarily be extended or truncated.
7652     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7653                                       NumCastsRemoved) &&
7654            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7655                                       NumCastsRemoved);
7656
7657   case Instruction::Shl:
7658     // If we are truncating the result of this SHL, and if it's a shift of a
7659     // constant amount, we can always perform a SHL in a smaller type.
7660     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7661       uint32_t BitWidth = Ty->getBitWidth();
7662       if (BitWidth < OrigTy->getBitWidth() && 
7663           CI->getLimitedValue(BitWidth) < BitWidth)
7664         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7665                                           NumCastsRemoved);
7666     }
7667     break;
7668   case Instruction::LShr:
7669     // If this is a truncate of a logical shr, we can truncate it to a smaller
7670     // lshr iff we know that the bits we would otherwise be shifting in are
7671     // already zeros.
7672     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7673       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7674       uint32_t BitWidth = Ty->getBitWidth();
7675       if (BitWidth < OrigBitWidth &&
7676           MaskedValueIsZero(I->getOperand(0),
7677             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7678           CI->getLimitedValue(BitWidth) < BitWidth) {
7679         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7680                                           NumCastsRemoved);
7681       }
7682     }
7683     break;
7684   case Instruction::ZExt:
7685   case Instruction::SExt:
7686   case Instruction::Trunc:
7687     // If this is the same kind of case as our original (e.g. zext+zext), we
7688     // can safely replace it.  Note that replacing it does not reduce the number
7689     // of casts in the input.
7690     if (Opc == CastOpc)
7691       return true;
7692
7693     // sext (zext ty1), ty2 -> zext ty2
7694     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7695       return true;
7696     break;
7697   case Instruction::Select: {
7698     SelectInst *SI = cast<SelectInst>(I);
7699     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7700                                       NumCastsRemoved) &&
7701            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7702                                       NumCastsRemoved);
7703   }
7704   case Instruction::PHI: {
7705     // We can change a phi if we can change all operands.
7706     PHINode *PN = cast<PHINode>(I);
7707     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7708       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7709                                       NumCastsRemoved))
7710         return false;
7711     return true;
7712   }
7713   default:
7714     // TODO: Can handle more cases here.
7715     break;
7716   }
7717   
7718   return false;
7719 }
7720
7721 /// EvaluateInDifferentType - Given an expression that 
7722 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7723 /// evaluate the expression.
7724 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7725                                              bool isSigned) {
7726   if (Constant *C = dyn_cast<Constant>(V))
7727     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7728
7729   // Otherwise, it must be an instruction.
7730   Instruction *I = cast<Instruction>(V);
7731   Instruction *Res = 0;
7732   unsigned Opc = I->getOpcode();
7733   switch (Opc) {
7734   case Instruction::Add:
7735   case Instruction::Sub:
7736   case Instruction::Mul:
7737   case Instruction::And:
7738   case Instruction::Or:
7739   case Instruction::Xor:
7740   case Instruction::AShr:
7741   case Instruction::LShr:
7742   case Instruction::Shl: {
7743     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7744     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7745     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7746     break;
7747   }    
7748   case Instruction::Trunc:
7749   case Instruction::ZExt:
7750   case Instruction::SExt:
7751     // If the source type of the cast is the type we're trying for then we can
7752     // just return the source.  There's no need to insert it because it is not
7753     // new.
7754     if (I->getOperand(0)->getType() == Ty)
7755       return I->getOperand(0);
7756     
7757     // Otherwise, must be the same type of cast, so just reinsert a new one.
7758     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7759                            Ty);
7760     break;
7761   case Instruction::Select: {
7762     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7763     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7764     Res = SelectInst::Create(I->getOperand(0), True, False);
7765     break;
7766   }
7767   case Instruction::PHI: {
7768     PHINode *OPN = cast<PHINode>(I);
7769     PHINode *NPN = PHINode::Create(Ty);
7770     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7771       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7772       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7773     }
7774     Res = NPN;
7775     break;
7776   }
7777   default: 
7778     // TODO: Can handle more cases here.
7779     assert(0 && "Unreachable!");
7780     break;
7781   }
7782   
7783   Res->takeName(I);
7784   return InsertNewInstBefore(Res, *I);
7785 }
7786
7787 /// @brief Implement the transforms common to all CastInst visitors.
7788 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7789   Value *Src = CI.getOperand(0);
7790
7791   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7792   // eliminate it now.
7793   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7794     if (Instruction::CastOps opc = 
7795         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7796       // The first cast (CSrc) is eliminable so we need to fix up or replace
7797       // the second cast (CI). CSrc will then have a good chance of being dead.
7798       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7799     }
7800   }
7801
7802   // If we are casting a select then fold the cast into the select
7803   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7804     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7805       return NV;
7806
7807   // If we are casting a PHI then fold the cast into the PHI
7808   if (isa<PHINode>(Src))
7809     if (Instruction *NV = FoldOpIntoPhi(CI))
7810       return NV;
7811   
7812   return 0;
7813 }
7814
7815 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7816 /// or not there is a sequence of GEP indices into the type that will land us at
7817 /// the specified offset.  If so, fill them into NewIndices and return the
7818 /// resultant element type, otherwise return null.
7819 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
7820                                        SmallVectorImpl<Value*> &NewIndices,
7821                                        const TargetData *TD) {
7822   if (!Ty->isSized()) return 0;
7823   
7824   // Start with the index over the outer type.  Note that the type size
7825   // might be zero (even if the offset isn't zero) if the indexed type
7826   // is something like [0 x {int, int}]
7827   const Type *IntPtrTy = TD->getIntPtrType();
7828   int64_t FirstIdx = 0;
7829   if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
7830     FirstIdx = Offset/TySize;
7831     Offset -= FirstIdx*TySize;
7832     
7833     // Handle hosts where % returns negative instead of values [0..TySize).
7834     if (Offset < 0) {
7835       --FirstIdx;
7836       Offset += TySize;
7837       assert(Offset >= 0);
7838     }
7839     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7840   }
7841   
7842   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7843     
7844   // Index into the types.  If we fail, set OrigBase to null.
7845   while (Offset) {
7846     // Indexing into tail padding between struct/array elements.
7847     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
7848       return 0;
7849     
7850     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7851       const StructLayout *SL = TD->getStructLayout(STy);
7852       assert(Offset < (int64_t)SL->getSizeInBytes() &&
7853              "Offset must stay within the indexed type");
7854       
7855       unsigned Elt = SL->getElementContainingOffset(Offset);
7856       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7857       
7858       Offset -= SL->getElementOffset(Elt);
7859       Ty = STy->getElementType(Elt);
7860     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
7861       uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
7862       assert(EltSize && "Cannot index into a zero-sized array");
7863       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7864       Offset %= EltSize;
7865       Ty = AT->getElementType();
7866     } else {
7867       // Otherwise, we can't index into the middle of this atomic type, bail.
7868       return 0;
7869     }
7870   }
7871   
7872   return Ty;
7873 }
7874
7875 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7876 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7877   Value *Src = CI.getOperand(0);
7878   
7879   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7880     // If casting the result of a getelementptr instruction with no offset, turn
7881     // this into a cast of the original pointer!
7882     if (GEP->hasAllZeroIndices()) {
7883       // Changing the cast operand is usually not a good idea but it is safe
7884       // here because the pointer operand is being replaced with another 
7885       // pointer operand so the opcode doesn't need to change.
7886       AddToWorkList(GEP);
7887       CI.setOperand(0, GEP->getOperand(0));
7888       return &CI;
7889     }
7890     
7891     // If the GEP has a single use, and the base pointer is a bitcast, and the
7892     // GEP computes a constant offset, see if we can convert these three
7893     // instructions into fewer.  This typically happens with unions and other
7894     // non-type-safe code.
7895     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7896       if (GEP->hasAllConstantIndices()) {
7897         // We are guaranteed to get a constant from EmitGEPOffset.
7898         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7899         int64_t Offset = OffsetV->getSExtValue();
7900         
7901         // Get the base pointer input of the bitcast, and the type it points to.
7902         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7903         const Type *GEPIdxTy =
7904           cast<PointerType>(OrigBase->getType())->getElementType();
7905         SmallVector<Value*, 8> NewIndices;
7906         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7907           // If we were able to index down into an element, create the GEP
7908           // and bitcast the result.  This eliminates one bitcast, potentially
7909           // two.
7910           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7911                                                         NewIndices.begin(),
7912                                                         NewIndices.end(), "");
7913           InsertNewInstBefore(NGEP, CI);
7914           NGEP->takeName(GEP);
7915           
7916           if (isa<BitCastInst>(CI))
7917             return new BitCastInst(NGEP, CI.getType());
7918           assert(isa<PtrToIntInst>(CI));
7919           return new PtrToIntInst(NGEP, CI.getType());
7920         }
7921       }      
7922     }
7923   }
7924     
7925   return commonCastTransforms(CI);
7926 }
7927
7928
7929 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7930 /// integer types. This function implements the common transforms for all those
7931 /// cases.
7932 /// @brief Implement the transforms common to CastInst with integer operands
7933 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7934   if (Instruction *Result = commonCastTransforms(CI))
7935     return Result;
7936
7937   Value *Src = CI.getOperand(0);
7938   const Type *SrcTy = Src->getType();
7939   const Type *DestTy = CI.getType();
7940   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7941   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7942
7943   // See if we can simplify any instructions used by the LHS whose sole 
7944   // purpose is to compute bits we don't care about.
7945   if (SimplifyDemandedInstructionBits(CI))
7946     return &CI;
7947
7948   // If the source isn't an instruction or has more than one use then we
7949   // can't do anything more. 
7950   Instruction *SrcI = dyn_cast<Instruction>(Src);
7951   if (!SrcI || !Src->hasOneUse())
7952     return 0;
7953
7954   // Attempt to propagate the cast into the instruction for int->int casts.
7955   int NumCastsRemoved = 0;
7956   if (!isa<BitCastInst>(CI) &&
7957       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7958                                  CI.getOpcode(), NumCastsRemoved)) {
7959     // If this cast is a truncate, evaluting in a different type always
7960     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7961     // we need to do an AND to maintain the clear top-part of the computation,
7962     // so we require that the input have eliminated at least one cast.  If this
7963     // is a sign extension, we insert two new casts (to do the extension) so we
7964     // require that two casts have been eliminated.
7965     bool DoXForm = false;
7966     bool JustReplace = false;
7967     switch (CI.getOpcode()) {
7968     default:
7969       // All the others use floating point so we shouldn't actually 
7970       // get here because of the check above.
7971       assert(0 && "Unknown cast type");
7972     case Instruction::Trunc:
7973       DoXForm = true;
7974       break;
7975     case Instruction::ZExt: {
7976       DoXForm = NumCastsRemoved >= 1;
7977       if (!DoXForm && 0) {
7978         // If it's unnecessary to issue an AND to clear the high bits, it's
7979         // always profitable to do this xform.
7980         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
7981         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7982         if (MaskedValueIsZero(TryRes, Mask))
7983           return ReplaceInstUsesWith(CI, TryRes);
7984         
7985         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7986           if (TryI->use_empty())
7987             EraseInstFromFunction(*TryI);
7988       }
7989       break;
7990     }
7991     case Instruction::SExt: {
7992       DoXForm = NumCastsRemoved >= 2;
7993       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
7994         // If we do not have to emit the truncate + sext pair, then it's always
7995         // profitable to do this xform.
7996         //
7997         // It's not safe to eliminate the trunc + sext pair if one of the
7998         // eliminated cast is a truncate. e.g.
7999         // t2 = trunc i32 t1 to i16
8000         // t3 = sext i16 t2 to i32
8001         // !=
8002         // i32 t1
8003         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8004         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8005         if (NumSignBits > (DestBitSize - SrcBitSize))
8006           return ReplaceInstUsesWith(CI, TryRes);
8007         
8008         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8009           if (TryI->use_empty())
8010             EraseInstFromFunction(*TryI);
8011       }
8012       break;
8013     }
8014     }
8015     
8016     if (DoXForm) {
8017       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8018            << " cast: " << CI;
8019       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8020                                            CI.getOpcode() == Instruction::SExt);
8021       if (JustReplace)
8022         // Just replace this cast with the result.
8023         return ReplaceInstUsesWith(CI, Res);
8024
8025       assert(Res->getType() == DestTy);
8026       switch (CI.getOpcode()) {
8027       default: assert(0 && "Unknown cast type!");
8028       case Instruction::Trunc:
8029       case Instruction::BitCast:
8030         // Just replace this cast with the result.
8031         return ReplaceInstUsesWith(CI, Res);
8032       case Instruction::ZExt: {
8033         assert(SrcBitSize < DestBitSize && "Not a zext?");
8034
8035         // If the high bits are already zero, just replace this cast with the
8036         // result.
8037         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8038         if (MaskedValueIsZero(Res, Mask))
8039           return ReplaceInstUsesWith(CI, Res);
8040
8041         // We need to emit an AND to clear the high bits.
8042         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8043                                                             SrcBitSize));
8044         return BinaryOperator::CreateAnd(Res, C);
8045       }
8046       case Instruction::SExt: {
8047         // If the high bits are already filled with sign bit, just replace this
8048         // cast with the result.
8049         unsigned NumSignBits = ComputeNumSignBits(Res);
8050         if (NumSignBits > (DestBitSize - SrcBitSize))
8051           return ReplaceInstUsesWith(CI, Res);
8052
8053         // We need to emit a cast to truncate, then a cast to sext.
8054         return CastInst::Create(Instruction::SExt,
8055             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8056                              CI), DestTy);
8057       }
8058       }
8059     }
8060   }
8061   
8062   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8063   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8064
8065   switch (SrcI->getOpcode()) {
8066   case Instruction::Add:
8067   case Instruction::Mul:
8068   case Instruction::And:
8069   case Instruction::Or:
8070   case Instruction::Xor:
8071     // If we are discarding information, rewrite.
8072     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8073       // Don't insert two casts if they cannot be eliminated.  We allow 
8074       // two casts to be inserted if the sizes are the same.  This could 
8075       // only be converting signedness, which is a noop.
8076       if (DestBitSize == SrcBitSize || 
8077           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8078           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8079         Instruction::CastOps opcode = CI.getOpcode();
8080         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8081         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8082         return BinaryOperator::Create(
8083             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8084       }
8085     }
8086
8087     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8088     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8089         SrcI->getOpcode() == Instruction::Xor &&
8090         Op1 == ConstantInt::getTrue() &&
8091         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8092       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8093       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
8094     }
8095     break;
8096   case Instruction::SDiv:
8097   case Instruction::UDiv:
8098   case Instruction::SRem:
8099   case Instruction::URem:
8100     // If we are just changing the sign, rewrite.
8101     if (DestBitSize == SrcBitSize) {
8102       // Don't insert two casts if they cannot be eliminated.  We allow 
8103       // two casts to be inserted if the sizes are the same.  This could 
8104       // only be converting signedness, which is a noop.
8105       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
8106           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8107         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
8108                                        Op0, DestTy, *SrcI);
8109         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
8110                                        Op1, DestTy, *SrcI);
8111         return BinaryOperator::Create(
8112           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8113       }
8114     }
8115     break;
8116
8117   case Instruction::Shl:
8118     // Allow changing the sign of the source operand.  Do not allow 
8119     // changing the size of the shift, UNLESS the shift amount is a 
8120     // constant.  We must not change variable sized shifts to a smaller 
8121     // size, because it is undefined to shift more bits out than exist 
8122     // in the value.
8123     if (DestBitSize == SrcBitSize ||
8124         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8125       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8126           Instruction::BitCast : Instruction::Trunc);
8127       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8128       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8129       return BinaryOperator::CreateShl(Op0c, Op1c);
8130     }
8131     break;
8132   case Instruction::AShr:
8133     // If this is a signed shr, and if all bits shifted in are about to be
8134     // truncated off, turn it into an unsigned shr to allow greater
8135     // simplifications.
8136     if (DestBitSize < SrcBitSize &&
8137         isa<ConstantInt>(Op1)) {
8138       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8139       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8140         // Insert the new logical shift right.
8141         return BinaryOperator::CreateLShr(Op0, Op1);
8142       }
8143     }
8144     break;
8145   }
8146   return 0;
8147 }
8148
8149 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8150   if (Instruction *Result = commonIntCastTransforms(CI))
8151     return Result;
8152   
8153   Value *Src = CI.getOperand(0);
8154   const Type *Ty = CI.getType();
8155   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8156   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
8157
8158   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8159   if (DestBitWidth == 1) {
8160     Constant *One = ConstantInt::get(Src->getType(), 1);
8161     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8162     Value *Zero = Constant::getNullValue(Src->getType());
8163     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8164   }
8165   
8166   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8167   ConstantInt *ShAmtV = 0;
8168   Value *ShiftOp = 0;
8169   if (Src->hasOneUse() &&
8170       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8171     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8172     
8173     // Get a mask for the bits shifting in.
8174     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8175     if (MaskedValueIsZero(ShiftOp, Mask)) {
8176       if (ShAmt >= DestBitWidth)        // All zeros.
8177         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8178       
8179       // Okay, we can shrink this.  Truncate the input, then return a new
8180       // shift.
8181       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8182       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8183       return BinaryOperator::CreateLShr(V1, V2);
8184     }
8185   }
8186   
8187   return 0;
8188 }
8189
8190 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8191 /// in order to eliminate the icmp.
8192 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8193                                              bool DoXform) {
8194   // If we are just checking for a icmp eq of a single bit and zext'ing it
8195   // to an integer, then shift the bit to the appropriate place and then
8196   // cast to integer to avoid the comparison.
8197   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8198     const APInt &Op1CV = Op1C->getValue();
8199       
8200     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8201     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8202     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8203         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8204       if (!DoXform) return ICI;
8205
8206       Value *In = ICI->getOperand(0);
8207       Value *Sh = ConstantInt::get(In->getType(),
8208                                    In->getType()->getPrimitiveSizeInBits()-1);
8209       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8210                                                         In->getName()+".lobit"),
8211                                CI);
8212       if (In->getType() != CI.getType())
8213         In = CastInst::CreateIntegerCast(In, CI.getType(),
8214                                          false/*ZExt*/, "tmp", &CI);
8215
8216       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8217         Constant *One = ConstantInt::get(In->getType(), 1);
8218         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8219                                                          In->getName()+".not"),
8220                                  CI);
8221       }
8222
8223       return ReplaceInstUsesWith(CI, In);
8224     }
8225       
8226       
8227       
8228     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8229     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8230     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8231     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8232     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8233     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8234     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8235     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8236     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8237         // This only works for EQ and NE
8238         ICI->isEquality()) {
8239       // If Op1C some other power of two, convert:
8240       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8241       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8242       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8243       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8244         
8245       APInt KnownZeroMask(~KnownZero);
8246       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8247         if (!DoXform) return ICI;
8248
8249         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8250         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8251           // (X&4) == 2 --> false
8252           // (X&4) != 2 --> true
8253           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8254           Res = ConstantExpr::getZExt(Res, CI.getType());
8255           return ReplaceInstUsesWith(CI, Res);
8256         }
8257           
8258         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8259         Value *In = ICI->getOperand(0);
8260         if (ShiftAmt) {
8261           // Perform a logical shr by shiftamt.
8262           // Insert the shift to put the result in the low bit.
8263           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8264                                   ConstantInt::get(In->getType(), ShiftAmt),
8265                                                    In->getName()+".lobit"), CI);
8266         }
8267           
8268         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8269           Constant *One = ConstantInt::get(In->getType(), 1);
8270           In = BinaryOperator::CreateXor(In, One, "tmp");
8271           InsertNewInstBefore(cast<Instruction>(In), CI);
8272         }
8273           
8274         if (CI.getType() == In->getType())
8275           return ReplaceInstUsesWith(CI, In);
8276         else
8277           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8278       }
8279     }
8280   }
8281
8282   return 0;
8283 }
8284
8285 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8286   // If one of the common conversion will work ..
8287   if (Instruction *Result = commonIntCastTransforms(CI))
8288     return Result;
8289
8290   Value *Src = CI.getOperand(0);
8291
8292   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8293   // types and if the sizes are just right we can convert this into a logical
8294   // 'and' which will be much cheaper than the pair of casts.
8295   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8296     // Get the sizes of the types involved.  We know that the intermediate type
8297     // will be smaller than A or C, but don't know the relation between A and C.
8298     Value *A = CSrc->getOperand(0);
8299     unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
8300     unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8301     unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8302     // If we're actually extending zero bits, then if
8303     // SrcSize <  DstSize: zext(a & mask)
8304     // SrcSize == DstSize: a & mask
8305     // SrcSize  > DstSize: trunc(a) & mask
8306     if (SrcSize < DstSize) {
8307       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8308       Constant *AndConst = ConstantInt::get(AndValue);
8309       Instruction *And =
8310         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8311       InsertNewInstBefore(And, CI);
8312       return new ZExtInst(And, CI.getType());
8313     } else if (SrcSize == DstSize) {
8314       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8315       return BinaryOperator::CreateAnd(A, ConstantInt::get(AndValue));
8316     } else if (SrcSize > DstSize) {
8317       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8318       InsertNewInstBefore(Trunc, CI);
8319       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8320       return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(AndValue));
8321     }
8322   }
8323
8324   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8325     return transformZExtICmp(ICI, CI);
8326
8327   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8328   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8329     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8330     // of the (zext icmp) will be transformed.
8331     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8332     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8333     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8334         (transformZExtICmp(LHS, CI, false) ||
8335          transformZExtICmp(RHS, CI, false))) {
8336       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8337       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8338       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8339     }
8340   }
8341
8342   return 0;
8343 }
8344
8345 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8346   if (Instruction *I = commonIntCastTransforms(CI))
8347     return I;
8348   
8349   Value *Src = CI.getOperand(0);
8350   
8351   // Canonicalize sign-extend from i1 to a select.
8352   if (Src->getType() == Type::Int1Ty)
8353     return SelectInst::Create(Src,
8354                               ConstantInt::getAllOnesValue(CI.getType()),
8355                               Constant::getNullValue(CI.getType()));
8356
8357   // See if the value being truncated is already sign extended.  If so, just
8358   // eliminate the trunc/sext pair.
8359   if (getOpcode(Src) == Instruction::Trunc) {
8360     Value *Op = cast<User>(Src)->getOperand(0);
8361     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8362     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8363     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8364     unsigned NumSignBits = ComputeNumSignBits(Op);
8365
8366     if (OpBits == DestBits) {
8367       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8368       // bits, it is already ready.
8369       if (NumSignBits > DestBits-MidBits)
8370         return ReplaceInstUsesWith(CI, Op);
8371     } else if (OpBits < DestBits) {
8372       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8373       // bits, just sext from i32.
8374       if (NumSignBits > OpBits-MidBits)
8375         return new SExtInst(Op, CI.getType(), "tmp");
8376     } else {
8377       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8378       // bits, just truncate to i32.
8379       if (NumSignBits > OpBits-MidBits)
8380         return new TruncInst(Op, CI.getType(), "tmp");
8381     }
8382   }
8383
8384   // If the input is a shl/ashr pair of a same constant, then this is a sign
8385   // extension from a smaller value.  If we could trust arbitrary bitwidth
8386   // integers, we could turn this into a truncate to the smaller bit and then
8387   // use a sext for the whole extension.  Since we don't, look deeper and check
8388   // for a truncate.  If the source and dest are the same type, eliminate the
8389   // trunc and extend and just do shifts.  For example, turn:
8390   //   %a = trunc i32 %i to i8
8391   //   %b = shl i8 %a, 6
8392   //   %c = ashr i8 %b, 6
8393   //   %d = sext i8 %c to i32
8394   // into:
8395   //   %a = shl i32 %i, 30
8396   //   %d = ashr i32 %a, 30
8397   Value *A = 0;
8398   ConstantInt *BA = 0, *CA = 0;
8399   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8400                         m_ConstantInt(CA))) &&
8401       BA == CA && isa<TruncInst>(A)) {
8402     Value *I = cast<TruncInst>(A)->getOperand(0);
8403     if (I->getType() == CI.getType()) {
8404       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8405       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8406       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8407       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8408       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8409                                                         CI.getName()), CI);
8410       return BinaryOperator::CreateAShr(I, ShAmtV);
8411     }
8412   }
8413   
8414   return 0;
8415 }
8416
8417 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8418 /// in the specified FP type without changing its value.
8419 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8420   bool losesInfo;
8421   APFloat F = CFP->getValueAPF();
8422   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8423   if (!losesInfo)
8424     return ConstantFP::get(F);
8425   return 0;
8426 }
8427
8428 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8429 /// through it until we get the source value.
8430 static Value *LookThroughFPExtensions(Value *V) {
8431   if (Instruction *I = dyn_cast<Instruction>(V))
8432     if (I->getOpcode() == Instruction::FPExt)
8433       return LookThroughFPExtensions(I->getOperand(0));
8434   
8435   // If this value is a constant, return the constant in the smallest FP type
8436   // that can accurately represent it.  This allows us to turn
8437   // (float)((double)X+2.0) into x+2.0f.
8438   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8439     if (CFP->getType() == Type::PPC_FP128Ty)
8440       return V;  // No constant folding of this.
8441     // See if the value can be truncated to float and then reextended.
8442     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8443       return V;
8444     if (CFP->getType() == Type::DoubleTy)
8445       return V;  // Won't shrink.
8446     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8447       return V;
8448     // Don't try to shrink to various long double types.
8449   }
8450   
8451   return V;
8452 }
8453
8454 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8455   if (Instruction *I = commonCastTransforms(CI))
8456     return I;
8457   
8458   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8459   // smaller than the destination type, we can eliminate the truncate by doing
8460   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8461   // many builtins (sqrt, etc).
8462   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8463   if (OpI && OpI->hasOneUse()) {
8464     switch (OpI->getOpcode()) {
8465     default: break;
8466     case Instruction::Add:
8467     case Instruction::Sub:
8468     case Instruction::Mul:
8469     case Instruction::FDiv:
8470     case Instruction::FRem:
8471       const Type *SrcTy = OpI->getType();
8472       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8473       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8474       if (LHSTrunc->getType() != SrcTy && 
8475           RHSTrunc->getType() != SrcTy) {
8476         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8477         // If the source types were both smaller than the destination type of
8478         // the cast, do this xform.
8479         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8480             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8481           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8482                                       CI.getType(), CI);
8483           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8484                                       CI.getType(), CI);
8485           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8486         }
8487       }
8488       break;  
8489     }
8490   }
8491   return 0;
8492 }
8493
8494 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8495   return commonCastTransforms(CI);
8496 }
8497
8498 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8499   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8500   if (OpI == 0)
8501     return commonCastTransforms(FI);
8502
8503   // fptoui(uitofp(X)) --> X
8504   // fptoui(sitofp(X)) --> X
8505   // This is safe if the intermediate type has enough bits in its mantissa to
8506   // accurately represent all values of X.  For example, do not do this with
8507   // i64->float->i64.  This is also safe for sitofp case, because any negative
8508   // 'X' value would cause an undefined result for the fptoui. 
8509   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8510       OpI->getOperand(0)->getType() == FI.getType() &&
8511       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8512                     OpI->getType()->getFPMantissaWidth())
8513     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8514
8515   return commonCastTransforms(FI);
8516 }
8517
8518 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8519   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8520   if (OpI == 0)
8521     return commonCastTransforms(FI);
8522   
8523   // fptosi(sitofp(X)) --> X
8524   // fptosi(uitofp(X)) --> X
8525   // This is safe if the intermediate type has enough bits in its mantissa to
8526   // accurately represent all values of X.  For example, do not do this with
8527   // i64->float->i64.  This is also safe for sitofp case, because any negative
8528   // 'X' value would cause an undefined result for the fptoui. 
8529   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8530       OpI->getOperand(0)->getType() == FI.getType() &&
8531       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8532                     OpI->getType()->getFPMantissaWidth())
8533     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8534   
8535   return commonCastTransforms(FI);
8536 }
8537
8538 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8539   return commonCastTransforms(CI);
8540 }
8541
8542 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8543   return commonCastTransforms(CI);
8544 }
8545
8546 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8547   // If the destination integer type is smaller than the intptr_t type for
8548   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8549   // trunc to be exposed to other transforms.  Don't do this for extending
8550   // ptrtoint's, because we don't know if the target sign or zero extends its
8551   // pointers.
8552   if (CI.getType()->getPrimitiveSizeInBits() < TD->getPointerSizeInBits()) {
8553     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8554                                                     TD->getIntPtrType(),
8555                                                     "tmp"), CI);
8556     return new TruncInst(P, CI.getType());
8557   }
8558   
8559   return commonPointerCastTransforms(CI);
8560 }
8561
8562 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8563   // If the source integer type is larger than the intptr_t type for
8564   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8565   // allows the trunc to be exposed to other transforms.  Don't do this for
8566   // extending inttoptr's, because we don't know if the target sign or zero
8567   // extends to pointers.
8568   if (CI.getOperand(0)->getType()->getPrimitiveSizeInBits() >
8569       TD->getPointerSizeInBits()) {
8570     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8571                                                  TD->getIntPtrType(),
8572                                                  "tmp"), CI);
8573     return new IntToPtrInst(P, CI.getType());
8574   }
8575   
8576   if (Instruction *I = commonCastTransforms(CI))
8577     return I;
8578   
8579   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8580   if (!DestPointee->isSized()) return 0;
8581
8582   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8583   ConstantInt *Cst;
8584   Value *X;
8585   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8586                                     m_ConstantInt(Cst)))) {
8587     // If the source and destination operands have the same type, see if this
8588     // is a single-index GEP.
8589     if (X->getType() == CI.getType()) {
8590       // Get the size of the pointee type.
8591       uint64_t Size = TD->getTypePaddedSize(DestPointee);
8592
8593       // Convert the constant to intptr type.
8594       APInt Offset = Cst->getValue();
8595       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8596
8597       // If Offset is evenly divisible by Size, we can do this xform.
8598       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8599         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8600         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8601       }
8602     }
8603     // TODO: Could handle other cases, e.g. where add is indexing into field of
8604     // struct etc.
8605   } else if (CI.getOperand(0)->hasOneUse() &&
8606              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8607     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8608     // "inttoptr+GEP" instead of "add+intptr".
8609     
8610     // Get the size of the pointee type.
8611     uint64_t Size = TD->getTypePaddedSize(DestPointee);
8612     
8613     // Convert the constant to intptr type.
8614     APInt Offset = Cst->getValue();
8615     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8616     
8617     // If Offset is evenly divisible by Size, we can do this xform.
8618     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8619       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8620       
8621       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8622                                                             "tmp"), CI);
8623       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8624     }
8625   }
8626   return 0;
8627 }
8628
8629 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8630   // If the operands are integer typed then apply the integer transforms,
8631   // otherwise just apply the common ones.
8632   Value *Src = CI.getOperand(0);
8633   const Type *SrcTy = Src->getType();
8634   const Type *DestTy = CI.getType();
8635
8636   if (SrcTy->isInteger() && DestTy->isInteger()) {
8637     if (Instruction *Result = commonIntCastTransforms(CI))
8638       return Result;
8639   } else if (isa<PointerType>(SrcTy)) {
8640     if (Instruction *I = commonPointerCastTransforms(CI))
8641       return I;
8642   } else {
8643     if (Instruction *Result = commonCastTransforms(CI))
8644       return Result;
8645   }
8646
8647
8648   // Get rid of casts from one type to the same type. These are useless and can
8649   // be replaced by the operand.
8650   if (DestTy == Src->getType())
8651     return ReplaceInstUsesWith(CI, Src);
8652
8653   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8654     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8655     const Type *DstElTy = DstPTy->getElementType();
8656     const Type *SrcElTy = SrcPTy->getElementType();
8657     
8658     // If the address spaces don't match, don't eliminate the bitcast, which is
8659     // required for changing types.
8660     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8661       return 0;
8662     
8663     // If we are casting a malloc or alloca to a pointer to a type of the same
8664     // size, rewrite the allocation instruction to allocate the "right" type.
8665     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8666       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8667         return V;
8668     
8669     // If the source and destination are pointers, and this cast is equivalent
8670     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8671     // This can enhance SROA and other transforms that want type-safe pointers.
8672     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8673     unsigned NumZeros = 0;
8674     while (SrcElTy != DstElTy && 
8675            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8676            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8677       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8678       ++NumZeros;
8679     }
8680
8681     // If we found a path from the src to dest, create the getelementptr now.
8682     if (SrcElTy == DstElTy) {
8683       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8684       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8685                                        ((Instruction*) NULL));
8686     }
8687   }
8688
8689   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8690     if (SVI->hasOneUse()) {
8691       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8692       // a bitconvert to a vector with the same # elts.
8693       if (isa<VectorType>(DestTy) && 
8694           cast<VectorType>(DestTy)->getNumElements() ==
8695                 SVI->getType()->getNumElements() &&
8696           SVI->getType()->getNumElements() ==
8697             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8698         CastInst *Tmp;
8699         // If either of the operands is a cast from CI.getType(), then
8700         // evaluating the shuffle in the casted destination's type will allow
8701         // us to eliminate at least one cast.
8702         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8703              Tmp->getOperand(0)->getType() == DestTy) ||
8704             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8705              Tmp->getOperand(0)->getType() == DestTy)) {
8706           Value *LHS = InsertCastBefore(Instruction::BitCast,
8707                                         SVI->getOperand(0), DestTy, CI);
8708           Value *RHS = InsertCastBefore(Instruction::BitCast,
8709                                         SVI->getOperand(1), DestTy, CI);
8710           // Return a new shuffle vector.  Use the same element ID's, as we
8711           // know the vector types match #elts.
8712           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8713         }
8714       }
8715     }
8716   }
8717   return 0;
8718 }
8719
8720 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8721 ///   %C = or %A, %B
8722 ///   %D = select %cond, %C, %A
8723 /// into:
8724 ///   %C = select %cond, %B, 0
8725 ///   %D = or %A, %C
8726 ///
8727 /// Assuming that the specified instruction is an operand to the select, return
8728 /// a bitmask indicating which operands of this instruction are foldable if they
8729 /// equal the other incoming value of the select.
8730 ///
8731 static unsigned GetSelectFoldableOperands(Instruction *I) {
8732   switch (I->getOpcode()) {
8733   case Instruction::Add:
8734   case Instruction::Mul:
8735   case Instruction::And:
8736   case Instruction::Or:
8737   case Instruction::Xor:
8738     return 3;              // Can fold through either operand.
8739   case Instruction::Sub:   // Can only fold on the amount subtracted.
8740   case Instruction::Shl:   // Can only fold on the shift amount.
8741   case Instruction::LShr:
8742   case Instruction::AShr:
8743     return 1;
8744   default:
8745     return 0;              // Cannot fold
8746   }
8747 }
8748
8749 /// GetSelectFoldableConstant - For the same transformation as the previous
8750 /// function, return the identity constant that goes into the select.
8751 static Constant *GetSelectFoldableConstant(Instruction *I) {
8752   switch (I->getOpcode()) {
8753   default: assert(0 && "This cannot happen!"); abort();
8754   case Instruction::Add:
8755   case Instruction::Sub:
8756   case Instruction::Or:
8757   case Instruction::Xor:
8758   case Instruction::Shl:
8759   case Instruction::LShr:
8760   case Instruction::AShr:
8761     return Constant::getNullValue(I->getType());
8762   case Instruction::And:
8763     return Constant::getAllOnesValue(I->getType());
8764   case Instruction::Mul:
8765     return ConstantInt::get(I->getType(), 1);
8766   }
8767 }
8768
8769 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8770 /// have the same opcode and only one use each.  Try to simplify this.
8771 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8772                                           Instruction *FI) {
8773   if (TI->getNumOperands() == 1) {
8774     // If this is a non-volatile load or a cast from the same type,
8775     // merge.
8776     if (TI->isCast()) {
8777       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8778         return 0;
8779     } else {
8780       return 0;  // unknown unary op.
8781     }
8782
8783     // Fold this by inserting a select from the input values.
8784     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8785                                            FI->getOperand(0), SI.getName()+".v");
8786     InsertNewInstBefore(NewSI, SI);
8787     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8788                             TI->getType());
8789   }
8790
8791   // Only handle binary operators here.
8792   if (!isa<BinaryOperator>(TI))
8793     return 0;
8794
8795   // Figure out if the operations have any operands in common.
8796   Value *MatchOp, *OtherOpT, *OtherOpF;
8797   bool MatchIsOpZero;
8798   if (TI->getOperand(0) == FI->getOperand(0)) {
8799     MatchOp  = TI->getOperand(0);
8800     OtherOpT = TI->getOperand(1);
8801     OtherOpF = FI->getOperand(1);
8802     MatchIsOpZero = true;
8803   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8804     MatchOp  = TI->getOperand(1);
8805     OtherOpT = TI->getOperand(0);
8806     OtherOpF = FI->getOperand(0);
8807     MatchIsOpZero = false;
8808   } else if (!TI->isCommutative()) {
8809     return 0;
8810   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8811     MatchOp  = TI->getOperand(0);
8812     OtherOpT = TI->getOperand(1);
8813     OtherOpF = FI->getOperand(0);
8814     MatchIsOpZero = true;
8815   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8816     MatchOp  = TI->getOperand(1);
8817     OtherOpT = TI->getOperand(0);
8818     OtherOpF = FI->getOperand(1);
8819     MatchIsOpZero = true;
8820   } else {
8821     return 0;
8822   }
8823
8824   // If we reach here, they do have operations in common.
8825   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8826                                          OtherOpF, SI.getName()+".v");
8827   InsertNewInstBefore(NewSI, SI);
8828
8829   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8830     if (MatchIsOpZero)
8831       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8832     else
8833       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8834   }
8835   assert(0 && "Shouldn't get here");
8836   return 0;
8837 }
8838
8839 /// visitSelectInstWithICmp - Visit a SelectInst that has an
8840 /// ICmpInst as its first operand.
8841 ///
8842 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8843                                                    ICmpInst *ICI) {
8844   bool Changed = false;
8845   ICmpInst::Predicate Pred = ICI->getPredicate();
8846   Value *CmpLHS = ICI->getOperand(0);
8847   Value *CmpRHS = ICI->getOperand(1);
8848   Value *TrueVal = SI.getTrueValue();
8849   Value *FalseVal = SI.getFalseValue();
8850
8851   // Check cases where the comparison is with a constant that
8852   // can be adjusted to fit the min/max idiom. We may edit ICI in
8853   // place here, so make sure the select is the only user.
8854   if (ICI->hasOneUse())
8855     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
8856       switch (Pred) {
8857       default: break;
8858       case ICmpInst::ICMP_ULT:
8859       case ICmpInst::ICMP_SLT: {
8860         // X < MIN ? T : F  -->  F
8861         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8862           return ReplaceInstUsesWith(SI, FalseVal);
8863         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
8864         Constant *AdjustedRHS = SubOne(CI);
8865         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8866             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8867           Pred = ICmpInst::getSwappedPredicate(Pred);
8868           CmpRHS = AdjustedRHS;
8869           std::swap(FalseVal, TrueVal);
8870           ICI->setPredicate(Pred);
8871           ICI->setOperand(1, CmpRHS);
8872           SI.setOperand(1, TrueVal);
8873           SI.setOperand(2, FalseVal);
8874           Changed = true;
8875         }
8876         break;
8877       }
8878       case ICmpInst::ICMP_UGT:
8879       case ICmpInst::ICMP_SGT: {
8880         // X > MAX ? T : F  -->  F
8881         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8882           return ReplaceInstUsesWith(SI, FalseVal);
8883         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
8884         Constant *AdjustedRHS = AddOne(CI);
8885         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8886             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8887           Pred = ICmpInst::getSwappedPredicate(Pred);
8888           CmpRHS = AdjustedRHS;
8889           std::swap(FalseVal, TrueVal);
8890           ICI->setPredicate(Pred);
8891           ICI->setOperand(1, CmpRHS);
8892           SI.setOperand(1, TrueVal);
8893           SI.setOperand(2, FalseVal);
8894           Changed = true;
8895         }
8896         break;
8897       }
8898       }
8899
8900       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
8901       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
8902       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
8903       if (match(TrueVal, m_ConstantInt<-1>()) &&
8904           match(FalseVal, m_ConstantInt<0>()))
8905         Pred = ICI->getPredicate();
8906       else if (match(TrueVal, m_ConstantInt<0>()) &&
8907                match(FalseVal, m_ConstantInt<-1>()))
8908         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8909       
8910       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8911         // If we are just checking for a icmp eq of a single bit and zext'ing it
8912         // to an integer, then shift the bit to the appropriate place and then
8913         // cast to integer to avoid the comparison.
8914         const APInt &Op1CV = CI->getValue();
8915     
8916         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
8917         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
8918         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8919             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
8920           Value *In = ICI->getOperand(0);
8921           Value *Sh = ConstantInt::get(In->getType(),
8922                                        In->getType()->getPrimitiveSizeInBits()-1);
8923           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8924                                                           In->getName()+".lobit"),
8925                                    *ICI);
8926           if (In->getType() != SI.getType())
8927             In = CastInst::CreateIntegerCast(In, SI.getType(),
8928                                              true/*SExt*/, "tmp", ICI);
8929     
8930           if (Pred == ICmpInst::ICMP_SGT)
8931             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8932                                        In->getName()+".not"), *ICI);
8933     
8934           return ReplaceInstUsesWith(SI, In);
8935         }
8936       }
8937     }
8938
8939   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8940     // Transform (X == Y) ? X : Y  -> Y
8941     if (Pred == ICmpInst::ICMP_EQ)
8942       return ReplaceInstUsesWith(SI, FalseVal);
8943     // Transform (X != Y) ? X : Y  -> X
8944     if (Pred == ICmpInst::ICMP_NE)
8945       return ReplaceInstUsesWith(SI, TrueVal);
8946     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8947
8948   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8949     // Transform (X == Y) ? Y : X  -> X
8950     if (Pred == ICmpInst::ICMP_EQ)
8951       return ReplaceInstUsesWith(SI, FalseVal);
8952     // Transform (X != Y) ? Y : X  -> Y
8953     if (Pred == ICmpInst::ICMP_NE)
8954       return ReplaceInstUsesWith(SI, TrueVal);
8955     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8956   }
8957
8958   /// NOTE: if we wanted to, this is where to detect integer ABS
8959
8960   return Changed ? &SI : 0;
8961 }
8962
8963 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8964   Value *CondVal = SI.getCondition();
8965   Value *TrueVal = SI.getTrueValue();
8966   Value *FalseVal = SI.getFalseValue();
8967
8968   // select true, X, Y  -> X
8969   // select false, X, Y -> Y
8970   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8971     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8972
8973   // select C, X, X -> X
8974   if (TrueVal == FalseVal)
8975     return ReplaceInstUsesWith(SI, TrueVal);
8976
8977   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8978     return ReplaceInstUsesWith(SI, FalseVal);
8979   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8980     return ReplaceInstUsesWith(SI, TrueVal);
8981   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8982     if (isa<Constant>(TrueVal))
8983       return ReplaceInstUsesWith(SI, TrueVal);
8984     else
8985       return ReplaceInstUsesWith(SI, FalseVal);
8986   }
8987
8988   if (SI.getType() == Type::Int1Ty) {
8989     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8990       if (C->getZExtValue()) {
8991         // Change: A = select B, true, C --> A = or B, C
8992         return BinaryOperator::CreateOr(CondVal, FalseVal);
8993       } else {
8994         // Change: A = select B, false, C --> A = and !B, C
8995         Value *NotCond =
8996           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8997                                              "not."+CondVal->getName()), SI);
8998         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8999       }
9000     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9001       if (C->getZExtValue() == false) {
9002         // Change: A = select B, C, false --> A = and B, C
9003         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9004       } else {
9005         // Change: A = select B, C, true --> A = or !B, C
9006         Value *NotCond =
9007           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9008                                              "not."+CondVal->getName()), SI);
9009         return BinaryOperator::CreateOr(NotCond, TrueVal);
9010       }
9011     }
9012     
9013     // select a, b, a  -> a&b
9014     // select a, a, b  -> a|b
9015     if (CondVal == TrueVal)
9016       return BinaryOperator::CreateOr(CondVal, FalseVal);
9017     else if (CondVal == FalseVal)
9018       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9019   }
9020
9021   // Selecting between two integer constants?
9022   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9023     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9024       // select C, 1, 0 -> zext C to int
9025       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9026         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9027       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9028         // select C, 0, 1 -> zext !C to int
9029         Value *NotCond =
9030           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9031                                                "not."+CondVal->getName()), SI);
9032         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9033       }
9034
9035       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9036
9037         // (x <s 0) ? -1 : 0 -> ashr x, 31
9038         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9039           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9040             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9041               // The comparison constant and the result are not neccessarily the
9042               // same width. Make an all-ones value by inserting a AShr.
9043               Value *X = IC->getOperand(0);
9044               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
9045               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
9046               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
9047                                                         ShAmt, "ones");
9048               InsertNewInstBefore(SRA, SI);
9049
9050               // Then cast to the appropriate width.
9051               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
9052             }
9053           }
9054
9055
9056         // If one of the constants is zero (we know they can't both be) and we
9057         // have an icmp instruction with zero, and we have an 'and' with the
9058         // non-constant value, eliminate this whole mess.  This corresponds to
9059         // cases like this: ((X & 27) ? 27 : 0)
9060         if (TrueValC->isZero() || FalseValC->isZero())
9061           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9062               cast<Constant>(IC->getOperand(1))->isNullValue())
9063             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9064               if (ICA->getOpcode() == Instruction::And &&
9065                   isa<ConstantInt>(ICA->getOperand(1)) &&
9066                   (ICA->getOperand(1) == TrueValC ||
9067                    ICA->getOperand(1) == FalseValC) &&
9068                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9069                 // Okay, now we know that everything is set up, we just don't
9070                 // know whether we have a icmp_ne or icmp_eq and whether the 
9071                 // true or false val is the zero.
9072                 bool ShouldNotVal = !TrueValC->isZero();
9073                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9074                 Value *V = ICA;
9075                 if (ShouldNotVal)
9076                   V = InsertNewInstBefore(BinaryOperator::Create(
9077                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9078                 return ReplaceInstUsesWith(SI, V);
9079               }
9080       }
9081     }
9082
9083   // See if we are selecting two values based on a comparison of the two values.
9084   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9085     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9086       // Transform (X == Y) ? X : Y  -> Y
9087       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9088         // This is not safe in general for floating point:  
9089         // consider X== -0, Y== +0.
9090         // It becomes safe if either operand is a nonzero constant.
9091         ConstantFP *CFPt, *CFPf;
9092         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9093               !CFPt->getValueAPF().isZero()) ||
9094             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9095              !CFPf->getValueAPF().isZero()))
9096         return ReplaceInstUsesWith(SI, FalseVal);
9097       }
9098       // Transform (X != Y) ? X : Y  -> X
9099       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9100         return ReplaceInstUsesWith(SI, TrueVal);
9101       // NOTE: if we wanted to, this is where to detect MIN/MAX
9102
9103     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9104       // Transform (X == Y) ? Y : X  -> X
9105       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9106         // This is not safe in general for floating point:  
9107         // consider X== -0, Y== +0.
9108         // It becomes safe if either operand is a nonzero constant.
9109         ConstantFP *CFPt, *CFPf;
9110         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9111               !CFPt->getValueAPF().isZero()) ||
9112             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9113              !CFPf->getValueAPF().isZero()))
9114           return ReplaceInstUsesWith(SI, FalseVal);
9115       }
9116       // Transform (X != Y) ? Y : X  -> Y
9117       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9118         return ReplaceInstUsesWith(SI, TrueVal);
9119       // NOTE: if we wanted to, this is where to detect MIN/MAX
9120     }
9121     // NOTE: if we wanted to, this is where to detect ABS
9122   }
9123
9124   // See if we are selecting two values based on a comparison of the two values.
9125   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9126     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9127       return Result;
9128
9129   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9130     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9131       if (TI->hasOneUse() && FI->hasOneUse()) {
9132         Instruction *AddOp = 0, *SubOp = 0;
9133
9134         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9135         if (TI->getOpcode() == FI->getOpcode())
9136           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9137             return IV;
9138
9139         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9140         // even legal for FP.
9141         if (TI->getOpcode() == Instruction::Sub &&
9142             FI->getOpcode() == Instruction::Add) {
9143           AddOp = FI; SubOp = TI;
9144         } else if (FI->getOpcode() == Instruction::Sub &&
9145                    TI->getOpcode() == Instruction::Add) {
9146           AddOp = TI; SubOp = FI;
9147         }
9148
9149         if (AddOp) {
9150           Value *OtherAddOp = 0;
9151           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9152             OtherAddOp = AddOp->getOperand(1);
9153           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9154             OtherAddOp = AddOp->getOperand(0);
9155           }
9156
9157           if (OtherAddOp) {
9158             // So at this point we know we have (Y -> OtherAddOp):
9159             //        select C, (add X, Y), (sub X, Z)
9160             Value *NegVal;  // Compute -Z
9161             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9162               NegVal = ConstantExpr::getNeg(C);
9163             } else {
9164               NegVal = InsertNewInstBefore(
9165                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9166             }
9167
9168             Value *NewTrueOp = OtherAddOp;
9169             Value *NewFalseOp = NegVal;
9170             if (AddOp != TI)
9171               std::swap(NewTrueOp, NewFalseOp);
9172             Instruction *NewSel =
9173               SelectInst::Create(CondVal, NewTrueOp,
9174                                  NewFalseOp, SI.getName() + ".p");
9175
9176             NewSel = InsertNewInstBefore(NewSel, SI);
9177             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9178           }
9179         }
9180       }
9181
9182   // See if we can fold the select into one of our operands.
9183   if (SI.getType()->isInteger()) {
9184     // See the comment above GetSelectFoldableOperands for a description of the
9185     // transformation we are doing here.
9186     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9187       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9188           !isa<Constant>(FalseVal))
9189         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9190           unsigned OpToFold = 0;
9191           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9192             OpToFold = 1;
9193           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9194             OpToFold = 2;
9195           }
9196
9197           if (OpToFold) {
9198             Constant *C = GetSelectFoldableConstant(TVI);
9199             Instruction *NewSel =
9200               SelectInst::Create(SI.getCondition(),
9201                                  TVI->getOperand(2-OpToFold), C);
9202             InsertNewInstBefore(NewSel, SI);
9203             NewSel->takeName(TVI);
9204             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9205               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9206             else {
9207               assert(0 && "Unknown instruction!!");
9208             }
9209           }
9210         }
9211
9212     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9213       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9214           !isa<Constant>(TrueVal))
9215         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9216           unsigned OpToFold = 0;
9217           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9218             OpToFold = 1;
9219           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9220             OpToFold = 2;
9221           }
9222
9223           if (OpToFold) {
9224             Constant *C = GetSelectFoldableConstant(FVI);
9225             Instruction *NewSel =
9226               SelectInst::Create(SI.getCondition(), C,
9227                                  FVI->getOperand(2-OpToFold));
9228             InsertNewInstBefore(NewSel, SI);
9229             NewSel->takeName(FVI);
9230             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9231               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9232             else
9233               assert(0 && "Unknown instruction!!");
9234           }
9235         }
9236   }
9237
9238   if (BinaryOperator::isNot(CondVal)) {
9239     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9240     SI.setOperand(1, FalseVal);
9241     SI.setOperand(2, TrueVal);
9242     return &SI;
9243   }
9244
9245   return 0;
9246 }
9247
9248 /// EnforceKnownAlignment - If the specified pointer points to an object that
9249 /// we control, modify the object's alignment to PrefAlign. This isn't
9250 /// often possible though. If alignment is important, a more reliable approach
9251 /// is to simply align all global variables and allocation instructions to
9252 /// their preferred alignment from the beginning.
9253 ///
9254 static unsigned EnforceKnownAlignment(Value *V,
9255                                       unsigned Align, unsigned PrefAlign) {
9256
9257   User *U = dyn_cast<User>(V);
9258   if (!U) return Align;
9259
9260   switch (getOpcode(U)) {
9261   default: break;
9262   case Instruction::BitCast:
9263     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9264   case Instruction::GetElementPtr: {
9265     // If all indexes are zero, it is just the alignment of the base pointer.
9266     bool AllZeroOperands = true;
9267     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9268       if (!isa<Constant>(*i) ||
9269           !cast<Constant>(*i)->isNullValue()) {
9270         AllZeroOperands = false;
9271         break;
9272       }
9273
9274     if (AllZeroOperands) {
9275       // Treat this like a bitcast.
9276       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9277     }
9278     break;
9279   }
9280   }
9281
9282   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9283     // If there is a large requested alignment and we can, bump up the alignment
9284     // of the global.
9285     if (!GV->isDeclaration()) {
9286       if (GV->getAlignment() >= PrefAlign)
9287         Align = GV->getAlignment();
9288       else {
9289         GV->setAlignment(PrefAlign);
9290         Align = PrefAlign;
9291       }
9292     }
9293   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9294     // If there is a requested alignment and if this is an alloca, round up.  We
9295     // don't do this for malloc, because some systems can't respect the request.
9296     if (isa<AllocaInst>(AI)) {
9297       if (AI->getAlignment() >= PrefAlign)
9298         Align = AI->getAlignment();
9299       else {
9300         AI->setAlignment(PrefAlign);
9301         Align = PrefAlign;
9302       }
9303     }
9304   }
9305
9306   return Align;
9307 }
9308
9309 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9310 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9311 /// and it is more than the alignment of the ultimate object, see if we can
9312 /// increase the alignment of the ultimate object, making this check succeed.
9313 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9314                                                   unsigned PrefAlign) {
9315   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9316                       sizeof(PrefAlign) * CHAR_BIT;
9317   APInt Mask = APInt::getAllOnesValue(BitWidth);
9318   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9319   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9320   unsigned TrailZ = KnownZero.countTrailingOnes();
9321   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9322
9323   if (PrefAlign > Align)
9324     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9325   
9326     // We don't need to make any adjustment.
9327   return Align;
9328 }
9329
9330 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9331   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9332   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9333   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9334   unsigned CopyAlign = MI->getAlignment();
9335
9336   if (CopyAlign < MinAlign) {
9337     MI->setAlignment(MinAlign);
9338     return MI;
9339   }
9340   
9341   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9342   // load/store.
9343   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9344   if (MemOpLength == 0) return 0;
9345   
9346   // Source and destination pointer types are always "i8*" for intrinsic.  See
9347   // if the size is something we can handle with a single primitive load/store.
9348   // A single load+store correctly handles overlapping memory in the memmove
9349   // case.
9350   unsigned Size = MemOpLength->getZExtValue();
9351   if (Size == 0) return MI;  // Delete this mem transfer.
9352   
9353   if (Size > 8 || (Size&(Size-1)))
9354     return 0;  // If not 1/2/4/8 bytes, exit.
9355   
9356   // Use an integer load+store unless we can find something better.
9357   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9358   
9359   // Memcpy forces the use of i8* for the source and destination.  That means
9360   // that if you're using memcpy to move one double around, you'll get a cast
9361   // from double* to i8*.  We'd much rather use a double load+store rather than
9362   // an i64 load+store, here because this improves the odds that the source or
9363   // dest address will be promotable.  See if we can find a better type than the
9364   // integer datatype.
9365   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9366     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9367     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9368       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9369       // down through these levels if so.
9370       while (!SrcETy->isSingleValueType()) {
9371         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9372           if (STy->getNumElements() == 1)
9373             SrcETy = STy->getElementType(0);
9374           else
9375             break;
9376         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9377           if (ATy->getNumElements() == 1)
9378             SrcETy = ATy->getElementType();
9379           else
9380             break;
9381         } else
9382           break;
9383       }
9384       
9385       if (SrcETy->isSingleValueType())
9386         NewPtrTy = PointerType::getUnqual(SrcETy);
9387     }
9388   }
9389   
9390   
9391   // If the memcpy/memmove provides better alignment info than we can
9392   // infer, use it.
9393   SrcAlign = std::max(SrcAlign, CopyAlign);
9394   DstAlign = std::max(DstAlign, CopyAlign);
9395   
9396   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9397   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9398   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9399   InsertNewInstBefore(L, *MI);
9400   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9401
9402   // Set the size of the copy to 0, it will be deleted on the next iteration.
9403   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9404   return MI;
9405 }
9406
9407 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9408   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9409   if (MI->getAlignment() < Alignment) {
9410     MI->setAlignment(Alignment);
9411     return MI;
9412   }
9413   
9414   // Extract the length and alignment and fill if they are constant.
9415   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9416   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9417   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9418     return 0;
9419   uint64_t Len = LenC->getZExtValue();
9420   Alignment = MI->getAlignment();
9421   
9422   // If the length is zero, this is a no-op
9423   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9424   
9425   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9426   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9427     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9428     
9429     Value *Dest = MI->getDest();
9430     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9431
9432     // Alignment 0 is identity for alignment 1 for memset, but not store.
9433     if (Alignment == 0) Alignment = 1;
9434     
9435     // Extract the fill value and store.
9436     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9437     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9438                                       Alignment), *MI);
9439     
9440     // Set the size of the copy to 0, it will be deleted on the next iteration.
9441     MI->setLength(Constant::getNullValue(LenC->getType()));
9442     return MI;
9443   }
9444
9445   return 0;
9446 }
9447
9448
9449 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9450 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9451 /// the heavy lifting.
9452 ///
9453 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9454   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9455   if (!II) return visitCallSite(&CI);
9456   
9457   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9458   // visitCallSite.
9459   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9460     bool Changed = false;
9461
9462     // memmove/cpy/set of zero bytes is a noop.
9463     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9464       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9465
9466       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9467         if (CI->getZExtValue() == 1) {
9468           // Replace the instruction with just byte operations.  We would
9469           // transform other cases to loads/stores, but we don't know if
9470           // alignment is sufficient.
9471         }
9472     }
9473
9474     // If we have a memmove and the source operation is a constant global,
9475     // then the source and dest pointers can't alias, so we can change this
9476     // into a call to memcpy.
9477     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9478       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9479         if (GVSrc->isConstant()) {
9480           Module *M = CI.getParent()->getParent()->getParent();
9481           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9482           const Type *Tys[1];
9483           Tys[0] = CI.getOperand(3)->getType();
9484           CI.setOperand(0, 
9485                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9486           Changed = true;
9487         }
9488
9489       // memmove(x,x,size) -> noop.
9490       if (MMI->getSource() == MMI->getDest())
9491         return EraseInstFromFunction(CI);
9492     }
9493
9494     // If we can determine a pointer alignment that is bigger than currently
9495     // set, update the alignment.
9496     if (isa<MemTransferInst>(MI)) {
9497       if (Instruction *I = SimplifyMemTransfer(MI))
9498         return I;
9499     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9500       if (Instruction *I = SimplifyMemSet(MSI))
9501         return I;
9502     }
9503           
9504     if (Changed) return II;
9505   }
9506   
9507   switch (II->getIntrinsicID()) {
9508   default: break;
9509   case Intrinsic::bswap:
9510     // bswap(bswap(x)) -> x
9511     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9512       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9513         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9514     break;
9515   case Intrinsic::ppc_altivec_lvx:
9516   case Intrinsic::ppc_altivec_lvxl:
9517   case Intrinsic::x86_sse_loadu_ps:
9518   case Intrinsic::x86_sse2_loadu_pd:
9519   case Intrinsic::x86_sse2_loadu_dq:
9520     // Turn PPC lvx     -> load if the pointer is known aligned.
9521     // Turn X86 loadups -> load if the pointer is known aligned.
9522     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9523       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9524                                        PointerType::getUnqual(II->getType()),
9525                                        CI);
9526       return new LoadInst(Ptr);
9527     }
9528     break;
9529   case Intrinsic::ppc_altivec_stvx:
9530   case Intrinsic::ppc_altivec_stvxl:
9531     // Turn stvx -> store if the pointer is known aligned.
9532     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9533       const Type *OpPtrTy = 
9534         PointerType::getUnqual(II->getOperand(1)->getType());
9535       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9536       return new StoreInst(II->getOperand(1), Ptr);
9537     }
9538     break;
9539   case Intrinsic::x86_sse_storeu_ps:
9540   case Intrinsic::x86_sse2_storeu_pd:
9541   case Intrinsic::x86_sse2_storeu_dq:
9542     // Turn X86 storeu -> store if the pointer is known aligned.
9543     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9544       const Type *OpPtrTy = 
9545         PointerType::getUnqual(II->getOperand(2)->getType());
9546       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9547       return new StoreInst(II->getOperand(2), Ptr);
9548     }
9549     break;
9550     
9551   case Intrinsic::x86_sse_cvttss2si: {
9552     // These intrinsics only demands the 0th element of its input vector.  If
9553     // we can simplify the input based on that, do so now.
9554     unsigned VWidth =
9555       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9556     APInt DemandedElts(VWidth, 1);
9557     APInt UndefElts(VWidth, 0);
9558     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9559                                               UndefElts)) {
9560       II->setOperand(1, V);
9561       return II;
9562     }
9563     break;
9564   }
9565     
9566   case Intrinsic::ppc_altivec_vperm:
9567     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9568     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9569       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9570       
9571       // Check that all of the elements are integer constants or undefs.
9572       bool AllEltsOk = true;
9573       for (unsigned i = 0; i != 16; ++i) {
9574         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9575             !isa<UndefValue>(Mask->getOperand(i))) {
9576           AllEltsOk = false;
9577           break;
9578         }
9579       }
9580       
9581       if (AllEltsOk) {
9582         // Cast the input vectors to byte vectors.
9583         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9584         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9585         Value *Result = UndefValue::get(Op0->getType());
9586         
9587         // Only extract each element once.
9588         Value *ExtractedElts[32];
9589         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9590         
9591         for (unsigned i = 0; i != 16; ++i) {
9592           if (isa<UndefValue>(Mask->getOperand(i)))
9593             continue;
9594           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9595           Idx &= 31;  // Match the hardware behavior.
9596           
9597           if (ExtractedElts[Idx] == 0) {
9598             Instruction *Elt = 
9599               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9600             InsertNewInstBefore(Elt, CI);
9601             ExtractedElts[Idx] = Elt;
9602           }
9603         
9604           // Insert this value into the result vector.
9605           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9606                                              i, "tmp");
9607           InsertNewInstBefore(cast<Instruction>(Result), CI);
9608         }
9609         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9610       }
9611     }
9612     break;
9613
9614   case Intrinsic::stackrestore: {
9615     // If the save is right next to the restore, remove the restore.  This can
9616     // happen when variable allocas are DCE'd.
9617     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9618       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9619         BasicBlock::iterator BI = SS;
9620         if (&*++BI == II)
9621           return EraseInstFromFunction(CI);
9622       }
9623     }
9624     
9625     // Scan down this block to see if there is another stack restore in the
9626     // same block without an intervening call/alloca.
9627     BasicBlock::iterator BI = II;
9628     TerminatorInst *TI = II->getParent()->getTerminator();
9629     bool CannotRemove = false;
9630     for (++BI; &*BI != TI; ++BI) {
9631       if (isa<AllocaInst>(BI)) {
9632         CannotRemove = true;
9633         break;
9634       }
9635       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9636         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9637           // If there is a stackrestore below this one, remove this one.
9638           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9639             return EraseInstFromFunction(CI);
9640           // Otherwise, ignore the intrinsic.
9641         } else {
9642           // If we found a non-intrinsic call, we can't remove the stack
9643           // restore.
9644           CannotRemove = true;
9645           break;
9646         }
9647       }
9648     }
9649     
9650     // If the stack restore is in a return/unwind block and if there are no
9651     // allocas or calls between the restore and the return, nuke the restore.
9652     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9653       return EraseInstFromFunction(CI);
9654     break;
9655   }
9656   }
9657
9658   return visitCallSite(II);
9659 }
9660
9661 // InvokeInst simplification
9662 //
9663 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9664   return visitCallSite(&II);
9665 }
9666
9667 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9668 /// passed through the varargs area, we can eliminate the use of the cast.
9669 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9670                                          const CastInst * const CI,
9671                                          const TargetData * const TD,
9672                                          const int ix) {
9673   if (!CI->isLosslessCast())
9674     return false;
9675
9676   // The size of ByVal arguments is derived from the type, so we
9677   // can't change to a type with a different size.  If the size were
9678   // passed explicitly we could avoid this check.
9679   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9680     return true;
9681
9682   const Type* SrcTy = 
9683             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9684   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9685   if (!SrcTy->isSized() || !DstTy->isSized())
9686     return false;
9687   if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
9688     return false;
9689   return true;
9690 }
9691
9692 // visitCallSite - Improvements for call and invoke instructions.
9693 //
9694 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9695   bool Changed = false;
9696
9697   // If the callee is a constexpr cast of a function, attempt to move the cast
9698   // to the arguments of the call/invoke.
9699   if (transformConstExprCastCall(CS)) return 0;
9700
9701   Value *Callee = CS.getCalledValue();
9702
9703   if (Function *CalleeF = dyn_cast<Function>(Callee))
9704     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9705       Instruction *OldCall = CS.getInstruction();
9706       // If the call and callee calling conventions don't match, this call must
9707       // be unreachable, as the call is undefined.
9708       new StoreInst(ConstantInt::getTrue(),
9709                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9710                                     OldCall);
9711       if (!OldCall->use_empty())
9712         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9713       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9714         return EraseInstFromFunction(*OldCall);
9715       return 0;
9716     }
9717
9718   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9719     // This instruction is not reachable, just remove it.  We insert a store to
9720     // undef so that we know that this code is not reachable, despite the fact
9721     // that we can't modify the CFG here.
9722     new StoreInst(ConstantInt::getTrue(),
9723                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9724                   CS.getInstruction());
9725
9726     if (!CS.getInstruction()->use_empty())
9727       CS.getInstruction()->
9728         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9729
9730     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9731       // Don't break the CFG, insert a dummy cond branch.
9732       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9733                          ConstantInt::getTrue(), II);
9734     }
9735     return EraseInstFromFunction(*CS.getInstruction());
9736   }
9737
9738   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9739     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9740       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9741         return transformCallThroughTrampoline(CS);
9742
9743   const PointerType *PTy = cast<PointerType>(Callee->getType());
9744   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9745   if (FTy->isVarArg()) {
9746     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9747     // See if we can optimize any arguments passed through the varargs area of
9748     // the call.
9749     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9750            E = CS.arg_end(); I != E; ++I, ++ix) {
9751       CastInst *CI = dyn_cast<CastInst>(*I);
9752       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9753         *I = CI->getOperand(0);
9754         Changed = true;
9755       }
9756     }
9757   }
9758
9759   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9760     // Inline asm calls cannot throw - mark them 'nounwind'.
9761     CS.setDoesNotThrow();
9762     Changed = true;
9763   }
9764
9765   return Changed ? CS.getInstruction() : 0;
9766 }
9767
9768 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9769 // attempt to move the cast to the arguments of the call/invoke.
9770 //
9771 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9772   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9773   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9774   if (CE->getOpcode() != Instruction::BitCast || 
9775       !isa<Function>(CE->getOperand(0)))
9776     return false;
9777   Function *Callee = cast<Function>(CE->getOperand(0));
9778   Instruction *Caller = CS.getInstruction();
9779   const AttrListPtr &CallerPAL = CS.getAttributes();
9780
9781   // Okay, this is a cast from a function to a different type.  Unless doing so
9782   // would cause a type conversion of one of our arguments, change this call to
9783   // be a direct call with arguments casted to the appropriate types.
9784   //
9785   const FunctionType *FT = Callee->getFunctionType();
9786   const Type *OldRetTy = Caller->getType();
9787   const Type *NewRetTy = FT->getReturnType();
9788
9789   if (isa<StructType>(NewRetTy))
9790     return false; // TODO: Handle multiple return values.
9791
9792   // Check to see if we are changing the return type...
9793   if (OldRetTy != NewRetTy) {
9794     if (Callee->isDeclaration() &&
9795         // Conversion is ok if changing from one pointer type to another or from
9796         // a pointer to an integer of the same size.
9797         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9798           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9799       return false;   // Cannot transform this return value.
9800
9801     if (!Caller->use_empty() &&
9802         // void -> non-void is handled specially
9803         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9804       return false;   // Cannot transform this return value.
9805
9806     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9807       Attributes RAttrs = CallerPAL.getRetAttributes();
9808       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9809         return false;   // Attribute not compatible with transformed value.
9810     }
9811
9812     // If the callsite is an invoke instruction, and the return value is used by
9813     // a PHI node in a successor, we cannot change the return type of the call
9814     // because there is no place to put the cast instruction (without breaking
9815     // the critical edge).  Bail out in this case.
9816     if (!Caller->use_empty())
9817       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9818         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9819              UI != E; ++UI)
9820           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9821             if (PN->getParent() == II->getNormalDest() ||
9822                 PN->getParent() == II->getUnwindDest())
9823               return false;
9824   }
9825
9826   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9827   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9828
9829   CallSite::arg_iterator AI = CS.arg_begin();
9830   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9831     const Type *ParamTy = FT->getParamType(i);
9832     const Type *ActTy = (*AI)->getType();
9833
9834     if (!CastInst::isCastable(ActTy, ParamTy))
9835       return false;   // Cannot transform this parameter value.
9836
9837     if (CallerPAL.getParamAttributes(i + 1) 
9838         & Attribute::typeIncompatible(ParamTy))
9839       return false;   // Attribute not compatible with transformed value.
9840
9841     // Converting from one pointer type to another or between a pointer and an
9842     // integer of the same size is safe even if we do not have a body.
9843     bool isConvertible = ActTy == ParamTy ||
9844       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9845        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9846     if (Callee->isDeclaration() && !isConvertible) return false;
9847   }
9848
9849   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9850       Callee->isDeclaration())
9851     return false;   // Do not delete arguments unless we have a function body.
9852
9853   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9854       !CallerPAL.isEmpty())
9855     // In this case we have more arguments than the new function type, but we
9856     // won't be dropping them.  Check that these extra arguments have attributes
9857     // that are compatible with being a vararg call argument.
9858     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9859       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9860         break;
9861       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9862       if (PAttrs & Attribute::VarArgsIncompatible)
9863         return false;
9864     }
9865
9866   // Okay, we decided that this is a safe thing to do: go ahead and start
9867   // inserting cast instructions as necessary...
9868   std::vector<Value*> Args;
9869   Args.reserve(NumActualArgs);
9870   SmallVector<AttributeWithIndex, 8> attrVec;
9871   attrVec.reserve(NumCommonArgs);
9872
9873   // Get any return attributes.
9874   Attributes RAttrs = CallerPAL.getRetAttributes();
9875
9876   // If the return value is not being used, the type may not be compatible
9877   // with the existing attributes.  Wipe out any problematic attributes.
9878   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
9879
9880   // Add the new return attributes.
9881   if (RAttrs)
9882     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
9883
9884   AI = CS.arg_begin();
9885   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9886     const Type *ParamTy = FT->getParamType(i);
9887     if ((*AI)->getType() == ParamTy) {
9888       Args.push_back(*AI);
9889     } else {
9890       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9891           false, ParamTy, false);
9892       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9893       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9894     }
9895
9896     // Add any parameter attributes.
9897     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9898       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9899   }
9900
9901   // If the function takes more arguments than the call was taking, add them
9902   // now...
9903   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9904     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9905
9906   // If we are removing arguments to the function, emit an obnoxious warning...
9907   if (FT->getNumParams() < NumActualArgs) {
9908     if (!FT->isVarArg()) {
9909       cerr << "WARNING: While resolving call to function '"
9910            << Callee->getName() << "' arguments were dropped!\n";
9911     } else {
9912       // Add all of the arguments in their promoted form to the arg list...
9913       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9914         const Type *PTy = getPromotedType((*AI)->getType());
9915         if (PTy != (*AI)->getType()) {
9916           // Must promote to pass through va_arg area!
9917           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9918                                                                 PTy, false);
9919           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9920           InsertNewInstBefore(Cast, *Caller);
9921           Args.push_back(Cast);
9922         } else {
9923           Args.push_back(*AI);
9924         }
9925
9926         // Add any parameter attributes.
9927         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9928           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9929       }
9930     }
9931   }
9932
9933   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
9934     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9935
9936   if (NewRetTy == Type::VoidTy)
9937     Caller->setName("");   // Void type should not have a name.
9938
9939   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
9940
9941   Instruction *NC;
9942   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9943     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9944                             Args.begin(), Args.end(),
9945                             Caller->getName(), Caller);
9946     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9947     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
9948   } else {
9949     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9950                           Caller->getName(), Caller);
9951     CallInst *CI = cast<CallInst>(Caller);
9952     if (CI->isTailCall())
9953       cast<CallInst>(NC)->setTailCall();
9954     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9955     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
9956   }
9957
9958   // Insert a cast of the return type as necessary.
9959   Value *NV = NC;
9960   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9961     if (NV->getType() != Type::VoidTy) {
9962       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9963                                                             OldRetTy, false);
9964       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9965
9966       // If this is an invoke instruction, we should insert it after the first
9967       // non-phi, instruction in the normal successor block.
9968       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9969         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9970         InsertNewInstBefore(NC, *I);
9971       } else {
9972         // Otherwise, it's a call, just insert cast right after the call instr
9973         InsertNewInstBefore(NC, *Caller);
9974       }
9975       AddUsersToWorkList(*Caller);
9976     } else {
9977       NV = UndefValue::get(Caller->getType());
9978     }
9979   }
9980
9981   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9982     Caller->replaceAllUsesWith(NV);
9983   Caller->eraseFromParent();
9984   RemoveFromWorkList(Caller);
9985   return true;
9986 }
9987
9988 // transformCallThroughTrampoline - Turn a call to a function created by the
9989 // init_trampoline intrinsic into a direct call to the underlying function.
9990 //
9991 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9992   Value *Callee = CS.getCalledValue();
9993   const PointerType *PTy = cast<PointerType>(Callee->getType());
9994   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9995   const AttrListPtr &Attrs = CS.getAttributes();
9996
9997   // If the call already has the 'nest' attribute somewhere then give up -
9998   // otherwise 'nest' would occur twice after splicing in the chain.
9999   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10000     return 0;
10001
10002   IntrinsicInst *Tramp =
10003     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10004
10005   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10006   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10007   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10008
10009   const AttrListPtr &NestAttrs = NestF->getAttributes();
10010   if (!NestAttrs.isEmpty()) {
10011     unsigned NestIdx = 1;
10012     const Type *NestTy = 0;
10013     Attributes NestAttr = Attribute::None;
10014
10015     // Look for a parameter marked with the 'nest' attribute.
10016     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10017          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10018       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10019         // Record the parameter type and any other attributes.
10020         NestTy = *I;
10021         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10022         break;
10023       }
10024
10025     if (NestTy) {
10026       Instruction *Caller = CS.getInstruction();
10027       std::vector<Value*> NewArgs;
10028       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10029
10030       SmallVector<AttributeWithIndex, 8> NewAttrs;
10031       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10032
10033       // Insert the nest argument into the call argument list, which may
10034       // mean appending it.  Likewise for attributes.
10035
10036       // Add any result attributes.
10037       if (Attributes Attr = Attrs.getRetAttributes())
10038         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10039
10040       {
10041         unsigned Idx = 1;
10042         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10043         do {
10044           if (Idx == NestIdx) {
10045             // Add the chain argument and attributes.
10046             Value *NestVal = Tramp->getOperand(3);
10047             if (NestVal->getType() != NestTy)
10048               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10049             NewArgs.push_back(NestVal);
10050             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10051           }
10052
10053           if (I == E)
10054             break;
10055
10056           // Add the original argument and attributes.
10057           NewArgs.push_back(*I);
10058           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10059             NewAttrs.push_back
10060               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10061
10062           ++Idx, ++I;
10063         } while (1);
10064       }
10065
10066       // Add any function attributes.
10067       if (Attributes Attr = Attrs.getFnAttributes())
10068         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10069
10070       // The trampoline may have been bitcast to a bogus type (FTy).
10071       // Handle this by synthesizing a new function type, equal to FTy
10072       // with the chain parameter inserted.
10073
10074       std::vector<const Type*> NewTypes;
10075       NewTypes.reserve(FTy->getNumParams()+1);
10076
10077       // Insert the chain's type into the list of parameter types, which may
10078       // mean appending it.
10079       {
10080         unsigned Idx = 1;
10081         FunctionType::param_iterator I = FTy->param_begin(),
10082           E = FTy->param_end();
10083
10084         do {
10085           if (Idx == NestIdx)
10086             // Add the chain's type.
10087             NewTypes.push_back(NestTy);
10088
10089           if (I == E)
10090             break;
10091
10092           // Add the original type.
10093           NewTypes.push_back(*I);
10094
10095           ++Idx, ++I;
10096         } while (1);
10097       }
10098
10099       // Replace the trampoline call with a direct call.  Let the generic
10100       // code sort out any function type mismatches.
10101       FunctionType *NewFTy =
10102         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
10103       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10104         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
10105       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10106
10107       Instruction *NewCaller;
10108       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10109         NewCaller = InvokeInst::Create(NewCallee,
10110                                        II->getNormalDest(), II->getUnwindDest(),
10111                                        NewArgs.begin(), NewArgs.end(),
10112                                        Caller->getName(), Caller);
10113         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10114         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10115       } else {
10116         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10117                                      Caller->getName(), Caller);
10118         if (cast<CallInst>(Caller)->isTailCall())
10119           cast<CallInst>(NewCaller)->setTailCall();
10120         cast<CallInst>(NewCaller)->
10121           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10122         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10123       }
10124       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10125         Caller->replaceAllUsesWith(NewCaller);
10126       Caller->eraseFromParent();
10127       RemoveFromWorkList(Caller);
10128       return 0;
10129     }
10130   }
10131
10132   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10133   // parameter, there is no need to adjust the argument list.  Let the generic
10134   // code sort out any function type mismatches.
10135   Constant *NewCallee =
10136     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10137   CS.setCalledFunction(NewCallee);
10138   return CS.getInstruction();
10139 }
10140
10141 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10142 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10143 /// and a single binop.
10144 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10145   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10146   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10147   unsigned Opc = FirstInst->getOpcode();
10148   Value *LHSVal = FirstInst->getOperand(0);
10149   Value *RHSVal = FirstInst->getOperand(1);
10150     
10151   const Type *LHSType = LHSVal->getType();
10152   const Type *RHSType = RHSVal->getType();
10153   
10154   // Scan to see if all operands are the same opcode, all have one use, and all
10155   // kill their operands (i.e. the operands have one use).
10156   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10157     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10158     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10159         // Verify type of the LHS matches so we don't fold cmp's of different
10160         // types or GEP's with different index types.
10161         I->getOperand(0)->getType() != LHSType ||
10162         I->getOperand(1)->getType() != RHSType)
10163       return 0;
10164
10165     // If they are CmpInst instructions, check their predicates
10166     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10167       if (cast<CmpInst>(I)->getPredicate() !=
10168           cast<CmpInst>(FirstInst)->getPredicate())
10169         return 0;
10170     
10171     // Keep track of which operand needs a phi node.
10172     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10173     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10174   }
10175   
10176   // Otherwise, this is safe to transform!
10177   
10178   Value *InLHS = FirstInst->getOperand(0);
10179   Value *InRHS = FirstInst->getOperand(1);
10180   PHINode *NewLHS = 0, *NewRHS = 0;
10181   if (LHSVal == 0) {
10182     NewLHS = PHINode::Create(LHSType,
10183                              FirstInst->getOperand(0)->getName() + ".pn");
10184     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10185     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10186     InsertNewInstBefore(NewLHS, PN);
10187     LHSVal = NewLHS;
10188   }
10189   
10190   if (RHSVal == 0) {
10191     NewRHS = PHINode::Create(RHSType,
10192                              FirstInst->getOperand(1)->getName() + ".pn");
10193     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10194     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10195     InsertNewInstBefore(NewRHS, PN);
10196     RHSVal = NewRHS;
10197   }
10198   
10199   // Add all operands to the new PHIs.
10200   if (NewLHS || NewRHS) {
10201     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10202       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10203       if (NewLHS) {
10204         Value *NewInLHS = InInst->getOperand(0);
10205         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10206       }
10207       if (NewRHS) {
10208         Value *NewInRHS = InInst->getOperand(1);
10209         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10210       }
10211     }
10212   }
10213     
10214   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10215     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10216   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10217   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10218                          RHSVal);
10219 }
10220
10221 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10222   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10223   
10224   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10225                                         FirstInst->op_end());
10226   // This is true if all GEP bases are allocas and if all indices into them are
10227   // constants.
10228   bool AllBasePointersAreAllocas = true;
10229   
10230   // Scan to see if all operands are the same opcode, all have one use, and all
10231   // kill their operands (i.e. the operands have one use).
10232   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10233     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10234     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10235       GEP->getNumOperands() != FirstInst->getNumOperands())
10236       return 0;
10237
10238     // Keep track of whether or not all GEPs are of alloca pointers.
10239     if (AllBasePointersAreAllocas &&
10240         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10241          !GEP->hasAllConstantIndices()))
10242       AllBasePointersAreAllocas = false;
10243     
10244     // Compare the operand lists.
10245     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10246       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10247         continue;
10248       
10249       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10250       // if one of the PHIs has a constant for the index.  The index may be
10251       // substantially cheaper to compute for the constants, so making it a
10252       // variable index could pessimize the path.  This also handles the case
10253       // for struct indices, which must always be constant.
10254       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10255           isa<ConstantInt>(GEP->getOperand(op)))
10256         return 0;
10257       
10258       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10259         return 0;
10260       FixedOperands[op] = 0;  // Needs a PHI.
10261     }
10262   }
10263   
10264   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10265   // bother doing this transformation.  At best, this will just save a bit of
10266   // offset calculation, but all the predecessors will have to materialize the
10267   // stack address into a register anyway.  We'd actually rather *clone* the
10268   // load up into the predecessors so that we have a load of a gep of an alloca,
10269   // which can usually all be folded into the load.
10270   if (AllBasePointersAreAllocas)
10271     return 0;
10272   
10273   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10274   // that is variable.
10275   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10276   
10277   bool HasAnyPHIs = false;
10278   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10279     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10280     Value *FirstOp = FirstInst->getOperand(i);
10281     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10282                                      FirstOp->getName()+".pn");
10283     InsertNewInstBefore(NewPN, PN);
10284     
10285     NewPN->reserveOperandSpace(e);
10286     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10287     OperandPhis[i] = NewPN;
10288     FixedOperands[i] = NewPN;
10289     HasAnyPHIs = true;
10290   }
10291
10292   
10293   // Add all operands to the new PHIs.
10294   if (HasAnyPHIs) {
10295     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10296       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10297       BasicBlock *InBB = PN.getIncomingBlock(i);
10298       
10299       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10300         if (PHINode *OpPhi = OperandPhis[op])
10301           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10302     }
10303   }
10304   
10305   Value *Base = FixedOperands[0];
10306   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10307                                    FixedOperands.end());
10308 }
10309
10310
10311 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10312 /// sink the load out of the block that defines it.  This means that it must be
10313 /// obvious the value of the load is not changed from the point of the load to
10314 /// the end of the block it is in.
10315 ///
10316 /// Finally, it is safe, but not profitable, to sink a load targetting a
10317 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10318 /// to a register.
10319 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10320   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10321   
10322   for (++BBI; BBI != E; ++BBI)
10323     if (BBI->mayWriteToMemory())
10324       return false;
10325   
10326   // Check for non-address taken alloca.  If not address-taken already, it isn't
10327   // profitable to do this xform.
10328   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10329     bool isAddressTaken = false;
10330     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10331          UI != E; ++UI) {
10332       if (isa<LoadInst>(UI)) continue;
10333       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10334         // If storing TO the alloca, then the address isn't taken.
10335         if (SI->getOperand(1) == AI) continue;
10336       }
10337       isAddressTaken = true;
10338       break;
10339     }
10340     
10341     if (!isAddressTaken && AI->isStaticAlloca())
10342       return false;
10343   }
10344   
10345   // If this load is a load from a GEP with a constant offset from an alloca,
10346   // then we don't want to sink it.  In its present form, it will be
10347   // load [constant stack offset].  Sinking it will cause us to have to
10348   // materialize the stack addresses in each predecessor in a register only to
10349   // do a shared load from register in the successor.
10350   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10351     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10352       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10353         return false;
10354   
10355   return true;
10356 }
10357
10358
10359 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10360 // operator and they all are only used by the PHI, PHI together their
10361 // inputs, and do the operation once, to the result of the PHI.
10362 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10363   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10364
10365   // Scan the instruction, looking for input operations that can be folded away.
10366   // If all input operands to the phi are the same instruction (e.g. a cast from
10367   // the same type or "+42") we can pull the operation through the PHI, reducing
10368   // code size and simplifying code.
10369   Constant *ConstantOp = 0;
10370   const Type *CastSrcTy = 0;
10371   bool isVolatile = false;
10372   if (isa<CastInst>(FirstInst)) {
10373     CastSrcTy = FirstInst->getOperand(0)->getType();
10374   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10375     // Can fold binop, compare or shift here if the RHS is a constant, 
10376     // otherwise call FoldPHIArgBinOpIntoPHI.
10377     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10378     if (ConstantOp == 0)
10379       return FoldPHIArgBinOpIntoPHI(PN);
10380   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10381     isVolatile = LI->isVolatile();
10382     // We can't sink the load if the loaded value could be modified between the
10383     // load and the PHI.
10384     if (LI->getParent() != PN.getIncomingBlock(0) ||
10385         !isSafeAndProfitableToSinkLoad(LI))
10386       return 0;
10387     
10388     // If the PHI is of volatile loads and the load block has multiple
10389     // successors, sinking it would remove a load of the volatile value from
10390     // the path through the other successor.
10391     if (isVolatile &&
10392         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10393       return 0;
10394     
10395   } else if (isa<GetElementPtrInst>(FirstInst)) {
10396     return FoldPHIArgGEPIntoPHI(PN);
10397   } else {
10398     return 0;  // Cannot fold this operation.
10399   }
10400
10401   // Check to see if all arguments are the same operation.
10402   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10403     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10404     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10405     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10406       return 0;
10407     if (CastSrcTy) {
10408       if (I->getOperand(0)->getType() != CastSrcTy)
10409         return 0;  // Cast operation must match.
10410     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10411       // We can't sink the load if the loaded value could be modified between 
10412       // the load and the PHI.
10413       if (LI->isVolatile() != isVolatile ||
10414           LI->getParent() != PN.getIncomingBlock(i) ||
10415           !isSafeAndProfitableToSinkLoad(LI))
10416         return 0;
10417       
10418       // If the PHI is of volatile loads and the load block has multiple
10419       // successors, sinking it would remove a load of the volatile value from
10420       // the path through the other successor.
10421       if (isVolatile &&
10422           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10423         return 0;
10424       
10425     } else if (I->getOperand(1) != ConstantOp) {
10426       return 0;
10427     }
10428   }
10429
10430   // Okay, they are all the same operation.  Create a new PHI node of the
10431   // correct type, and PHI together all of the LHS's of the instructions.
10432   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10433                                    PN.getName()+".in");
10434   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10435
10436   Value *InVal = FirstInst->getOperand(0);
10437   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10438
10439   // Add all operands to the new PHI.
10440   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10441     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10442     if (NewInVal != InVal)
10443       InVal = 0;
10444     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10445   }
10446
10447   Value *PhiVal;
10448   if (InVal) {
10449     // The new PHI unions all of the same values together.  This is really
10450     // common, so we handle it intelligently here for compile-time speed.
10451     PhiVal = InVal;
10452     delete NewPN;
10453   } else {
10454     InsertNewInstBefore(NewPN, PN);
10455     PhiVal = NewPN;
10456   }
10457
10458   // Insert and return the new operation.
10459   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10460     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10461   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10462     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10463   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10464     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10465                            PhiVal, ConstantOp);
10466   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10467   
10468   // If this was a volatile load that we are merging, make sure to loop through
10469   // and mark all the input loads as non-volatile.  If we don't do this, we will
10470   // insert a new volatile load and the old ones will not be deletable.
10471   if (isVolatile)
10472     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10473       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10474   
10475   return new LoadInst(PhiVal, "", isVolatile);
10476 }
10477
10478 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10479 /// that is dead.
10480 static bool DeadPHICycle(PHINode *PN,
10481                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10482   if (PN->use_empty()) return true;
10483   if (!PN->hasOneUse()) return false;
10484
10485   // Remember this node, and if we find the cycle, return.
10486   if (!PotentiallyDeadPHIs.insert(PN))
10487     return true;
10488   
10489   // Don't scan crazily complex things.
10490   if (PotentiallyDeadPHIs.size() == 16)
10491     return false;
10492
10493   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10494     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10495
10496   return false;
10497 }
10498
10499 /// PHIsEqualValue - Return true if this phi node is always equal to
10500 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10501 ///   z = some value; x = phi (y, z); y = phi (x, z)
10502 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10503                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10504   // See if we already saw this PHI node.
10505   if (!ValueEqualPHIs.insert(PN))
10506     return true;
10507   
10508   // Don't scan crazily complex things.
10509   if (ValueEqualPHIs.size() == 16)
10510     return false;
10511  
10512   // Scan the operands to see if they are either phi nodes or are equal to
10513   // the value.
10514   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10515     Value *Op = PN->getIncomingValue(i);
10516     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10517       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10518         return false;
10519     } else if (Op != NonPhiInVal)
10520       return false;
10521   }
10522   
10523   return true;
10524 }
10525
10526
10527 // PHINode simplification
10528 //
10529 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10530   // If LCSSA is around, don't mess with Phi nodes
10531   if (MustPreserveLCSSA) return 0;
10532   
10533   if (Value *V = PN.hasConstantValue())
10534     return ReplaceInstUsesWith(PN, V);
10535
10536   // If all PHI operands are the same operation, pull them through the PHI,
10537   // reducing code size.
10538   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10539       isa<Instruction>(PN.getIncomingValue(1)) &&
10540       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10541       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10542       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10543       // than themselves more than once.
10544       PN.getIncomingValue(0)->hasOneUse())
10545     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10546       return Result;
10547
10548   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10549   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10550   // PHI)... break the cycle.
10551   if (PN.hasOneUse()) {
10552     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10553     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10554       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10555       PotentiallyDeadPHIs.insert(&PN);
10556       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10557         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10558     }
10559    
10560     // If this phi has a single use, and if that use just computes a value for
10561     // the next iteration of a loop, delete the phi.  This occurs with unused
10562     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10563     // common case here is good because the only other things that catch this
10564     // are induction variable analysis (sometimes) and ADCE, which is only run
10565     // late.
10566     if (PHIUser->hasOneUse() &&
10567         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10568         PHIUser->use_back() == &PN) {
10569       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10570     }
10571   }
10572
10573   // We sometimes end up with phi cycles that non-obviously end up being the
10574   // same value, for example:
10575   //   z = some value; x = phi (y, z); y = phi (x, z)
10576   // where the phi nodes don't necessarily need to be in the same block.  Do a
10577   // quick check to see if the PHI node only contains a single non-phi value, if
10578   // so, scan to see if the phi cycle is actually equal to that value.
10579   {
10580     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10581     // Scan for the first non-phi operand.
10582     while (InValNo != NumOperandVals && 
10583            isa<PHINode>(PN.getIncomingValue(InValNo)))
10584       ++InValNo;
10585
10586     if (InValNo != NumOperandVals) {
10587       Value *NonPhiInVal = PN.getOperand(InValNo);
10588       
10589       // Scan the rest of the operands to see if there are any conflicts, if so
10590       // there is no need to recursively scan other phis.
10591       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10592         Value *OpVal = PN.getIncomingValue(InValNo);
10593         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10594           break;
10595       }
10596       
10597       // If we scanned over all operands, then we have one unique value plus
10598       // phi values.  Scan PHI nodes to see if they all merge in each other or
10599       // the value.
10600       if (InValNo == NumOperandVals) {
10601         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10602         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10603           return ReplaceInstUsesWith(PN, NonPhiInVal);
10604       }
10605     }
10606   }
10607   return 0;
10608 }
10609
10610 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10611                                    Instruction *InsertPoint,
10612                                    InstCombiner *IC) {
10613   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10614   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10615   // We must cast correctly to the pointer type. Ensure that we
10616   // sign extend the integer value if it is smaller as this is
10617   // used for address computation.
10618   Instruction::CastOps opcode = 
10619      (VTySize < PtrSize ? Instruction::SExt :
10620       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10621   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10622 }
10623
10624
10625 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10626   Value *PtrOp = GEP.getOperand(0);
10627   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10628   // If so, eliminate the noop.
10629   if (GEP.getNumOperands() == 1)
10630     return ReplaceInstUsesWith(GEP, PtrOp);
10631
10632   if (isa<UndefValue>(GEP.getOperand(0)))
10633     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10634
10635   bool HasZeroPointerIndex = false;
10636   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10637     HasZeroPointerIndex = C->isNullValue();
10638
10639   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10640     return ReplaceInstUsesWith(GEP, PtrOp);
10641
10642   // Eliminate unneeded casts for indices.
10643   bool MadeChange = false;
10644   
10645   gep_type_iterator GTI = gep_type_begin(GEP);
10646   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10647        i != e; ++i, ++GTI) {
10648     if (isa<SequentialType>(*GTI)) {
10649       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10650         if (CI->getOpcode() == Instruction::ZExt ||
10651             CI->getOpcode() == Instruction::SExt) {
10652           const Type *SrcTy = CI->getOperand(0)->getType();
10653           // We can eliminate a cast from i32 to i64 iff the target 
10654           // is a 32-bit pointer target.
10655           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10656             MadeChange = true;
10657             *i = CI->getOperand(0);
10658           }
10659         }
10660       }
10661       // If we are using a wider index than needed for this platform, shrink it
10662       // to what we need.  If narrower, sign-extend it to what we need.
10663       // If the incoming value needs a cast instruction,
10664       // insert it.  This explicit cast can make subsequent optimizations more
10665       // obvious.
10666       Value *Op = *i;
10667       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10668         if (Constant *C = dyn_cast<Constant>(Op)) {
10669           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10670           MadeChange = true;
10671         } else {
10672           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10673                                 GEP);
10674           *i = Op;
10675           MadeChange = true;
10676         }
10677       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10678         if (Constant *C = dyn_cast<Constant>(Op)) {
10679           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10680           MadeChange = true;
10681         } else {
10682           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10683                                 GEP);
10684           *i = Op;
10685           MadeChange = true;
10686         }
10687       }
10688     }
10689   }
10690   if (MadeChange) return &GEP;
10691
10692   // Combine Indices - If the source pointer to this getelementptr instruction
10693   // is a getelementptr instruction, combine the indices of the two
10694   // getelementptr instructions into a single instruction.
10695   //
10696   SmallVector<Value*, 8> SrcGEPOperands;
10697   if (User *Src = dyn_castGetElementPtr(PtrOp))
10698     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10699
10700   if (!SrcGEPOperands.empty()) {
10701     // Note that if our source is a gep chain itself that we wait for that
10702     // chain to be resolved before we perform this transformation.  This
10703     // avoids us creating a TON of code in some cases.
10704     //
10705     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10706         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10707       return 0;   // Wait until our source is folded to completion.
10708
10709     SmallVector<Value*, 8> Indices;
10710
10711     // Find out whether the last index in the source GEP is a sequential idx.
10712     bool EndsWithSequential = false;
10713     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10714            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10715       EndsWithSequential = !isa<StructType>(*I);
10716
10717     // Can we combine the two pointer arithmetics offsets?
10718     if (EndsWithSequential) {
10719       // Replace: gep (gep %P, long B), long A, ...
10720       // With:    T = long A+B; gep %P, T, ...
10721       //
10722       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10723       if (SO1 == Constant::getNullValue(SO1->getType())) {
10724         Sum = GO1;
10725       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10726         Sum = SO1;
10727       } else {
10728         // If they aren't the same type, convert both to an integer of the
10729         // target's pointer size.
10730         if (SO1->getType() != GO1->getType()) {
10731           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10732             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10733           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10734             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10735           } else {
10736             unsigned PS = TD->getPointerSizeInBits();
10737             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10738               // Convert GO1 to SO1's type.
10739               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10740
10741             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10742               // Convert SO1 to GO1's type.
10743               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10744             } else {
10745               const Type *PT = TD->getIntPtrType();
10746               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10747               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10748             }
10749           }
10750         }
10751         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10752           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10753         else {
10754           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10755           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10756         }
10757       }
10758
10759       // Recycle the GEP we already have if possible.
10760       if (SrcGEPOperands.size() == 2) {
10761         GEP.setOperand(0, SrcGEPOperands[0]);
10762         GEP.setOperand(1, Sum);
10763         return &GEP;
10764       } else {
10765         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10766                        SrcGEPOperands.end()-1);
10767         Indices.push_back(Sum);
10768         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10769       }
10770     } else if (isa<Constant>(*GEP.idx_begin()) &&
10771                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10772                SrcGEPOperands.size() != 1) {
10773       // Otherwise we can do the fold if the first index of the GEP is a zero
10774       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10775                      SrcGEPOperands.end());
10776       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10777     }
10778
10779     if (!Indices.empty())
10780       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10781                                        Indices.end(), GEP.getName());
10782
10783   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10784     // GEP of global variable.  If all of the indices for this GEP are
10785     // constants, we can promote this to a constexpr instead of an instruction.
10786
10787     // Scan for nonconstants...
10788     SmallVector<Constant*, 8> Indices;
10789     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10790     for (; I != E && isa<Constant>(*I); ++I)
10791       Indices.push_back(cast<Constant>(*I));
10792
10793     if (I == E) {  // If they are all constants...
10794       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10795                                                     &Indices[0],Indices.size());
10796
10797       // Replace all uses of the GEP with the new constexpr...
10798       return ReplaceInstUsesWith(GEP, CE);
10799     }
10800   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10801     if (!isa<PointerType>(X->getType())) {
10802       // Not interesting.  Source pointer must be a cast from pointer.
10803     } else if (HasZeroPointerIndex) {
10804       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10805       // into     : GEP [10 x i8]* X, i32 0, ...
10806       //
10807       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10808       //           into     : GEP i8* X, ...
10809       // 
10810       // This occurs when the program declares an array extern like "int X[];"
10811       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10812       const PointerType *XTy = cast<PointerType>(X->getType());
10813       if (const ArrayType *CATy =
10814           dyn_cast<ArrayType>(CPTy->getElementType())) {
10815         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10816         if (CATy->getElementType() == XTy->getElementType()) {
10817           // -> GEP i8* X, ...
10818           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10819           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10820                                            GEP.getName());
10821         } else if (const ArrayType *XATy =
10822                  dyn_cast<ArrayType>(XTy->getElementType())) {
10823           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
10824           if (CATy->getElementType() == XATy->getElementType()) {
10825             // -> GEP [10 x i8]* X, i32 0, ...
10826             // At this point, we know that the cast source type is a pointer
10827             // to an array of the same type as the destination pointer
10828             // array.  Because the array type is never stepped over (there
10829             // is a leading zero) we can fold the cast into this GEP.
10830             GEP.setOperand(0, X);
10831             return &GEP;
10832           }
10833         }
10834       }
10835     } else if (GEP.getNumOperands() == 2) {
10836       // Transform things like:
10837       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10838       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10839       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10840       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10841       if (isa<ArrayType>(SrcElTy) &&
10842           TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10843           TD->getTypePaddedSize(ResElTy)) {
10844         Value *Idx[2];
10845         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10846         Idx[1] = GEP.getOperand(1);
10847         Value *V = InsertNewInstBefore(
10848                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10849         // V and GEP are both pointer types --> BitCast
10850         return new BitCastInst(V, GEP.getType());
10851       }
10852       
10853       // Transform things like:
10854       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10855       //   (where tmp = 8*tmp2) into:
10856       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10857       
10858       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10859         uint64_t ArrayEltSize =
10860             TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
10861         
10862         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10863         // allow either a mul, shift, or constant here.
10864         Value *NewIdx = 0;
10865         ConstantInt *Scale = 0;
10866         if (ArrayEltSize == 1) {
10867           NewIdx = GEP.getOperand(1);
10868           Scale = ConstantInt::get(NewIdx->getType(), 1);
10869         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10870           NewIdx = ConstantInt::get(CI->getType(), 1);
10871           Scale = CI;
10872         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10873           if (Inst->getOpcode() == Instruction::Shl &&
10874               isa<ConstantInt>(Inst->getOperand(1))) {
10875             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10876             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10877             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10878             NewIdx = Inst->getOperand(0);
10879           } else if (Inst->getOpcode() == Instruction::Mul &&
10880                      isa<ConstantInt>(Inst->getOperand(1))) {
10881             Scale = cast<ConstantInt>(Inst->getOperand(1));
10882             NewIdx = Inst->getOperand(0);
10883           }
10884         }
10885         
10886         // If the index will be to exactly the right offset with the scale taken
10887         // out, perform the transformation. Note, we don't know whether Scale is
10888         // signed or not. We'll use unsigned version of division/modulo
10889         // operation after making sure Scale doesn't have the sign bit set.
10890         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
10891             Scale->getZExtValue() % ArrayEltSize == 0) {
10892           Scale = ConstantInt::get(Scale->getType(),
10893                                    Scale->getZExtValue() / ArrayEltSize);
10894           if (Scale->getZExtValue() != 1) {
10895             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10896                                                        false /*ZExt*/);
10897             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10898             NewIdx = InsertNewInstBefore(Sc, GEP);
10899           }
10900
10901           // Insert the new GEP instruction.
10902           Value *Idx[2];
10903           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10904           Idx[1] = NewIdx;
10905           Instruction *NewGEP =
10906             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10907           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10908           // The NewGEP must be pointer typed, so must the old one -> BitCast
10909           return new BitCastInst(NewGEP, GEP.getType());
10910         }
10911       }
10912     }
10913   }
10914   
10915   /// See if we can simplify:
10916   ///   X = bitcast A to B*
10917   ///   Y = gep X, <...constant indices...>
10918   /// into a gep of the original struct.  This is important for SROA and alias
10919   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
10920   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
10921     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10922       // Determine how much the GEP moves the pointer.  We are guaranteed to get
10923       // a constant back from EmitGEPOffset.
10924       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10925       int64_t Offset = OffsetV->getSExtValue();
10926       
10927       // If this GEP instruction doesn't move the pointer, just replace the GEP
10928       // with a bitcast of the real input to the dest type.
10929       if (Offset == 0) {
10930         // If the bitcast is of an allocation, and the allocation will be
10931         // converted to match the type of the cast, don't touch this.
10932         if (isa<AllocationInst>(BCI->getOperand(0))) {
10933           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10934           if (Instruction *I = visitBitCast(*BCI)) {
10935             if (I != BCI) {
10936               I->takeName(BCI);
10937               BCI->getParent()->getInstList().insert(BCI, I);
10938               ReplaceInstUsesWith(*BCI, I);
10939             }
10940             return &GEP;
10941           }
10942         }
10943         return new BitCastInst(BCI->getOperand(0), GEP.getType());
10944       }
10945       
10946       // Otherwise, if the offset is non-zero, we need to find out if there is a
10947       // field at Offset in 'A's type.  If so, we can pull the cast through the
10948       // GEP.
10949       SmallVector<Value*, 8> NewIndices;
10950       const Type *InTy =
10951         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10952       if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10953         Instruction *NGEP =
10954            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10955                                      NewIndices.end());
10956         if (NGEP->getType() == GEP.getType()) return NGEP;
10957         InsertNewInstBefore(NGEP, GEP);
10958         NGEP->takeName(&GEP);
10959         return new BitCastInst(NGEP, GEP.getType());
10960       }
10961     }
10962   }    
10963     
10964   return 0;
10965 }
10966
10967 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10968   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10969   if (AI.isArrayAllocation()) {  // Check C != 1
10970     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10971       const Type *NewTy = 
10972         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10973       AllocationInst *New = 0;
10974
10975       // Create and insert the replacement instruction...
10976       if (isa<MallocInst>(AI))
10977         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10978       else {
10979         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10980         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10981       }
10982
10983       InsertNewInstBefore(New, AI);
10984
10985       // Scan to the end of the allocation instructions, to skip over a block of
10986       // allocas if possible...also skip interleaved debug info
10987       //
10988       BasicBlock::iterator It = New;
10989       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
10990
10991       // Now that I is pointing to the first non-allocation-inst in the block,
10992       // insert our getelementptr instruction...
10993       //
10994       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10995       Value *Idx[2];
10996       Idx[0] = NullIdx;
10997       Idx[1] = NullIdx;
10998       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10999                                            New->getName()+".sub", It);
11000
11001       // Now make everything use the getelementptr instead of the original
11002       // allocation.
11003       return ReplaceInstUsesWith(AI, V);
11004     } else if (isa<UndefValue>(AI.getArraySize())) {
11005       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11006     }
11007   }
11008
11009   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11010     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11011     // Note that we only do this for alloca's, because malloc should allocate
11012     // and return a unique pointer, even for a zero byte allocation.
11013     if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
11014       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11015
11016     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11017     if (AI.getAlignment() == 0)
11018       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11019   }
11020
11021   return 0;
11022 }
11023
11024 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11025   Value *Op = FI.getOperand(0);
11026
11027   // free undef -> unreachable.
11028   if (isa<UndefValue>(Op)) {
11029     // Insert a new store to null because we cannot modify the CFG here.
11030     new StoreInst(ConstantInt::getTrue(),
11031                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
11032     return EraseInstFromFunction(FI);
11033   }
11034   
11035   // If we have 'free null' delete the instruction.  This can happen in stl code
11036   // when lots of inlining happens.
11037   if (isa<ConstantPointerNull>(Op))
11038     return EraseInstFromFunction(FI);
11039   
11040   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11041   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11042     FI.setOperand(0, CI->getOperand(0));
11043     return &FI;
11044   }
11045   
11046   // Change free (gep X, 0,0,0,0) into free(X)
11047   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11048     if (GEPI->hasAllZeroIndices()) {
11049       AddToWorkList(GEPI);
11050       FI.setOperand(0, GEPI->getOperand(0));
11051       return &FI;
11052     }
11053   }
11054   
11055   // Change free(malloc) into nothing, if the malloc has a single use.
11056   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11057     if (MI->hasOneUse()) {
11058       EraseInstFromFunction(FI);
11059       return EraseInstFromFunction(*MI);
11060     }
11061
11062   return 0;
11063 }
11064
11065
11066 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11067 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11068                                         const TargetData *TD) {
11069   User *CI = cast<User>(LI.getOperand(0));
11070   Value *CastOp = CI->getOperand(0);
11071
11072   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11073     // Instead of loading constant c string, use corresponding integer value
11074     // directly if string length is small enough.
11075     std::string Str;
11076     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11077       unsigned len = Str.length();
11078       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11079       unsigned numBits = Ty->getPrimitiveSizeInBits();
11080       // Replace LI with immediate integer store.
11081       if ((numBits >> 3) == len + 1) {
11082         APInt StrVal(numBits, 0);
11083         APInt SingleChar(numBits, 0);
11084         if (TD->isLittleEndian()) {
11085           for (signed i = len-1; i >= 0; i--) {
11086             SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11087             StrVal = (StrVal << 8) | SingleChar;
11088           }
11089         } else {
11090           for (unsigned i = 0; i < len; i++) {
11091             SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11092             StrVal = (StrVal << 8) | SingleChar;
11093           }
11094           // Append NULL at the end.
11095           SingleChar = 0;
11096           StrVal = (StrVal << 8) | SingleChar;
11097         }
11098         Value *NL = ConstantInt::get(StrVal);
11099         return IC.ReplaceInstUsesWith(LI, NL);
11100       }
11101     }
11102   }
11103
11104   const PointerType *DestTy = cast<PointerType>(CI->getType());
11105   const Type *DestPTy = DestTy->getElementType();
11106   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11107
11108     // If the address spaces don't match, don't eliminate the cast.
11109     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11110       return 0;
11111
11112     const Type *SrcPTy = SrcTy->getElementType();
11113
11114     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11115          isa<VectorType>(DestPTy)) {
11116       // If the source is an array, the code below will not succeed.  Check to
11117       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11118       // constants.
11119       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11120         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11121           if (ASrcTy->getNumElements() != 0) {
11122             Value *Idxs[2];
11123             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11124             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11125             SrcTy = cast<PointerType>(CastOp->getType());
11126             SrcPTy = SrcTy->getElementType();
11127           }
11128
11129       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11130             isa<VectorType>(SrcPTy)) &&
11131           // Do not allow turning this into a load of an integer, which is then
11132           // casted to a pointer, this pessimizes pointer analysis a lot.
11133           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11134           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11135                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11136
11137         // Okay, we are casting from one integer or pointer type to another of
11138         // the same size.  Instead of casting the pointer before the load, cast
11139         // the result of the loaded value.
11140         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11141                                                              CI->getName(),
11142                                                          LI.isVolatile()),LI);
11143         // Now cast the result of the load.
11144         return new BitCastInst(NewLoad, LI.getType());
11145       }
11146     }
11147   }
11148   return 0;
11149 }
11150
11151 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
11152 /// from this value cannot trap.  If it is not obviously safe to load from the
11153 /// specified pointer, we do a quick local scan of the basic block containing
11154 /// ScanFrom, to determine if the address is already accessed.
11155 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
11156   // If it is an alloca it is always safe to load from.
11157   if (isa<AllocaInst>(V)) return true;
11158
11159   // If it is a global variable it is mostly safe to load from.
11160   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
11161     // Don't try to evaluate aliases.  External weak GV can be null.
11162     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
11163
11164   // Otherwise, be a little bit agressive by scanning the local block where we
11165   // want to check to see if the pointer is already being loaded or stored
11166   // from/to.  If so, the previous load or store would have already trapped,
11167   // so there is no harm doing an extra load (also, CSE will later eliminate
11168   // the load entirely).
11169   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11170
11171   while (BBI != E) {
11172     --BBI;
11173
11174     // If we see a free or a call (which might do a free) the pointer could be
11175     // marked invalid.
11176     if (isa<FreeInst>(BBI) || 
11177         (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)))
11178       return false;
11179     
11180     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11181       if (LI->getOperand(0) == V) return true;
11182     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
11183       if (SI->getOperand(1) == V) return true;
11184     }
11185
11186   }
11187   return false;
11188 }
11189
11190 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11191   Value *Op = LI.getOperand(0);
11192
11193   // Attempt to improve the alignment.
11194   unsigned KnownAlign =
11195     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11196   if (KnownAlign >
11197       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11198                                 LI.getAlignment()))
11199     LI.setAlignment(KnownAlign);
11200
11201   // load (cast X) --> cast (load X) iff safe
11202   if (isa<CastInst>(Op))
11203     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11204       return Res;
11205
11206   // None of the following transforms are legal for volatile loads.
11207   if (LI.isVolatile()) return 0;
11208   
11209   // Do really simple store-to-load forwarding and load CSE, to catch cases
11210   // where there are several consequtive memory accesses to the same location,
11211   // separated by a few arithmetic operations.
11212   BasicBlock::iterator BBI = &LI;
11213   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11214     return ReplaceInstUsesWith(LI, AvailableVal);
11215
11216   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11217     const Value *GEPI0 = GEPI->getOperand(0);
11218     // TODO: Consider a target hook for valid address spaces for this xform.
11219     if (isa<ConstantPointerNull>(GEPI0) &&
11220         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11221       // Insert a new store to null instruction before the load to indicate
11222       // that this code is not reachable.  We do this instead of inserting
11223       // an unreachable instruction directly because we cannot modify the
11224       // CFG.
11225       new StoreInst(UndefValue::get(LI.getType()),
11226                     Constant::getNullValue(Op->getType()), &LI);
11227       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11228     }
11229   } 
11230
11231   if (Constant *C = dyn_cast<Constant>(Op)) {
11232     // load null/undef -> undef
11233     // TODO: Consider a target hook for valid address spaces for this xform.
11234     if (isa<UndefValue>(C) || (C->isNullValue() && 
11235         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11236       // Insert a new store to null instruction before the load to indicate that
11237       // this code is not reachable.  We do this instead of inserting an
11238       // unreachable instruction directly because we cannot modify the CFG.
11239       new StoreInst(UndefValue::get(LI.getType()),
11240                     Constant::getNullValue(Op->getType()), &LI);
11241       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11242     }
11243
11244     // Instcombine load (constant global) into the value loaded.
11245     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11246       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11247         return ReplaceInstUsesWith(LI, GV->getInitializer());
11248
11249     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11250     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11251       if (CE->getOpcode() == Instruction::GetElementPtr) {
11252         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11253           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11254             if (Constant *V = 
11255                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11256               return ReplaceInstUsesWith(LI, V);
11257         if (CE->getOperand(0)->isNullValue()) {
11258           // Insert a new store to null instruction before the load to indicate
11259           // that this code is not reachable.  We do this instead of inserting
11260           // an unreachable instruction directly because we cannot modify the
11261           // CFG.
11262           new StoreInst(UndefValue::get(LI.getType()),
11263                         Constant::getNullValue(Op->getType()), &LI);
11264           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11265         }
11266
11267       } else if (CE->isCast()) {
11268         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11269           return Res;
11270       }
11271     }
11272   }
11273     
11274   // If this load comes from anywhere in a constant global, and if the global
11275   // is all undef or zero, we know what it loads.
11276   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11277     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11278       if (GV->getInitializer()->isNullValue())
11279         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11280       else if (isa<UndefValue>(GV->getInitializer()))
11281         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11282     }
11283   }
11284
11285   if (Op->hasOneUse()) {
11286     // Change select and PHI nodes to select values instead of addresses: this
11287     // helps alias analysis out a lot, allows many others simplifications, and
11288     // exposes redundancy in the code.
11289     //
11290     // Note that we cannot do the transformation unless we know that the
11291     // introduced loads cannot trap!  Something like this is valid as long as
11292     // the condition is always false: load (select bool %C, int* null, int* %G),
11293     // but it would not be valid if we transformed it to load from null
11294     // unconditionally.
11295     //
11296     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11297       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11298       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11299           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11300         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11301                                      SI->getOperand(1)->getName()+".val"), LI);
11302         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11303                                      SI->getOperand(2)->getName()+".val"), LI);
11304         return SelectInst::Create(SI->getCondition(), V1, V2);
11305       }
11306
11307       // load (select (cond, null, P)) -> load P
11308       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11309         if (C->isNullValue()) {
11310           LI.setOperand(0, SI->getOperand(2));
11311           return &LI;
11312         }
11313
11314       // load (select (cond, P, null)) -> load P
11315       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11316         if (C->isNullValue()) {
11317           LI.setOperand(0, SI->getOperand(1));
11318           return &LI;
11319         }
11320     }
11321   }
11322   return 0;
11323 }
11324
11325 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11326 /// when possible.  This makes it generally easy to do alias analysis and/or
11327 /// SROA/mem2reg of the memory object.
11328 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11329   User *CI = cast<User>(SI.getOperand(1));
11330   Value *CastOp = CI->getOperand(0);
11331
11332   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11333   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11334   if (SrcTy == 0) return 0;
11335   
11336   const Type *SrcPTy = SrcTy->getElementType();
11337
11338   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11339     return 0;
11340   
11341   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11342   /// to its first element.  This allows us to handle things like:
11343   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11344   /// on 32-bit hosts.
11345   SmallVector<Value*, 4> NewGEPIndices;
11346   
11347   // If the source is an array, the code below will not succeed.  Check to
11348   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11349   // constants.
11350   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11351     // Index through pointer.
11352     Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11353     NewGEPIndices.push_back(Zero);
11354     
11355     while (1) {
11356       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11357         if (!STy->getNumElements()) /* Struct can be empty {} */
11358           break;
11359         NewGEPIndices.push_back(Zero);
11360         SrcPTy = STy->getElementType(0);
11361       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11362         NewGEPIndices.push_back(Zero);
11363         SrcPTy = ATy->getElementType();
11364       } else {
11365         break;
11366       }
11367     }
11368     
11369     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11370   }
11371
11372   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11373     return 0;
11374   
11375   // If the pointers point into different address spaces or if they point to
11376   // values with different sizes, we can't do the transformation.
11377   if (SrcTy->getAddressSpace() != 
11378         cast<PointerType>(CI->getType())->getAddressSpace() ||
11379       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11380       IC.getTargetData().getTypeSizeInBits(DestPTy))
11381     return 0;
11382
11383   // Okay, we are casting from one integer or pointer type to another of
11384   // the same size.  Instead of casting the pointer before 
11385   // the store, cast the value to be stored.
11386   Value *NewCast;
11387   Value *SIOp0 = SI.getOperand(0);
11388   Instruction::CastOps opcode = Instruction::BitCast;
11389   const Type* CastSrcTy = SIOp0->getType();
11390   const Type* CastDstTy = SrcPTy;
11391   if (isa<PointerType>(CastDstTy)) {
11392     if (CastSrcTy->isInteger())
11393       opcode = Instruction::IntToPtr;
11394   } else if (isa<IntegerType>(CastDstTy)) {
11395     if (isa<PointerType>(SIOp0->getType()))
11396       opcode = Instruction::PtrToInt;
11397   }
11398   
11399   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11400   // emit a GEP to index into its first field.
11401   if (!NewGEPIndices.empty()) {
11402     if (Constant *C = dyn_cast<Constant>(CastOp))
11403       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11404                                               NewGEPIndices.size());
11405     else
11406       CastOp = IC.InsertNewInstBefore(
11407               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11408                                         NewGEPIndices.end()), SI);
11409   }
11410   
11411   if (Constant *C = dyn_cast<Constant>(SIOp0))
11412     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11413   else
11414     NewCast = IC.InsertNewInstBefore(
11415       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11416       SI);
11417   return new StoreInst(NewCast, CastOp);
11418 }
11419
11420 /// equivalentAddressValues - Test if A and B will obviously have the same
11421 /// value. This includes recognizing that %t0 and %t1 will have the same
11422 /// value in code like this:
11423 ///   %t0 = getelementptr \@a, 0, 3
11424 ///   store i32 0, i32* %t0
11425 ///   %t1 = getelementptr \@a, 0, 3
11426 ///   %t2 = load i32* %t1
11427 ///
11428 static bool equivalentAddressValues(Value *A, Value *B) {
11429   // Test if the values are trivially equivalent.
11430   if (A == B) return true;
11431   
11432   // Test if the values come form identical arithmetic instructions.
11433   if (isa<BinaryOperator>(A) ||
11434       isa<CastInst>(A) ||
11435       isa<PHINode>(A) ||
11436       isa<GetElementPtrInst>(A))
11437     if (Instruction *BI = dyn_cast<Instruction>(B))
11438       if (cast<Instruction>(A)->isIdenticalTo(BI))
11439         return true;
11440   
11441   // Otherwise they may not be equivalent.
11442   return false;
11443 }
11444
11445 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11446 // return the llvm.dbg.declare.
11447 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11448   if (!V->hasNUses(2))
11449     return 0;
11450   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11451        UI != E; ++UI) {
11452     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11453       return DI;
11454     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11455       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11456         return DI;
11457       }
11458   }
11459   return 0;
11460 }
11461
11462 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11463   Value *Val = SI.getOperand(0);
11464   Value *Ptr = SI.getOperand(1);
11465
11466   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11467     EraseInstFromFunction(SI);
11468     ++NumCombined;
11469     return 0;
11470   }
11471   
11472   // If the RHS is an alloca with a single use, zapify the store, making the
11473   // alloca dead.
11474   // If the RHS is an alloca with a two uses, the other one being a 
11475   // llvm.dbg.declare, zapify the store and the declare, making the
11476   // alloca dead.  We must do this to prevent declare's from affecting
11477   // codegen.
11478   if (!SI.isVolatile()) {
11479     if (Ptr->hasOneUse()) {
11480       if (isa<AllocaInst>(Ptr)) {
11481         EraseInstFromFunction(SI);
11482         ++NumCombined;
11483         return 0;
11484       }
11485       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11486         if (isa<AllocaInst>(GEP->getOperand(0))) {
11487           if (GEP->getOperand(0)->hasOneUse()) {
11488             EraseInstFromFunction(SI);
11489             ++NumCombined;
11490             return 0;
11491           }
11492           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11493             EraseInstFromFunction(*DI);
11494             EraseInstFromFunction(SI);
11495             ++NumCombined;
11496             return 0;
11497           }
11498         }
11499       }
11500     }
11501     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11502       EraseInstFromFunction(*DI);
11503       EraseInstFromFunction(SI);
11504       ++NumCombined;
11505       return 0;
11506     }
11507   }
11508
11509   // Attempt to improve the alignment.
11510   unsigned KnownAlign =
11511     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11512   if (KnownAlign >
11513       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11514                                 SI.getAlignment()))
11515     SI.setAlignment(KnownAlign);
11516
11517   // Do really simple DSE, to catch cases where there are several consecutive
11518   // stores to the same location, separated by a few arithmetic operations. This
11519   // situation often occurs with bitfield accesses.
11520   BasicBlock::iterator BBI = &SI;
11521   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11522        --ScanInsts) {
11523     --BBI;
11524     // Don't count debug info directives, lest they affect codegen,
11525     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11526     // It is necessary for correctness to skip those that feed into a
11527     // llvm.dbg.declare, as these are not present when debugging is off.
11528     if (isa<DbgInfoIntrinsic>(BBI) ||
11529         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11530       ScanInsts++;
11531       continue;
11532     }    
11533     
11534     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11535       // Prev store isn't volatile, and stores to the same location?
11536       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11537                                                           SI.getOperand(1))) {
11538         ++NumDeadStore;
11539         ++BBI;
11540         EraseInstFromFunction(*PrevSI);
11541         continue;
11542       }
11543       break;
11544     }
11545     
11546     // If this is a load, we have to stop.  However, if the loaded value is from
11547     // the pointer we're loading and is producing the pointer we're storing,
11548     // then *this* store is dead (X = load P; store X -> P).
11549     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11550       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11551           !SI.isVolatile()) {
11552         EraseInstFromFunction(SI);
11553         ++NumCombined;
11554         return 0;
11555       }
11556       // Otherwise, this is a load from some other location.  Stores before it
11557       // may not be dead.
11558       break;
11559     }
11560     
11561     // Don't skip over loads or things that can modify memory.
11562     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11563       break;
11564   }
11565   
11566   
11567   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11568
11569   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11570   if (isa<ConstantPointerNull>(Ptr)) {
11571     if (!isa<UndefValue>(Val)) {
11572       SI.setOperand(0, UndefValue::get(Val->getType()));
11573       if (Instruction *U = dyn_cast<Instruction>(Val))
11574         AddToWorkList(U);  // Dropped a use.
11575       ++NumCombined;
11576     }
11577     return 0;  // Do not modify these!
11578   }
11579
11580   // store undef, Ptr -> noop
11581   if (isa<UndefValue>(Val)) {
11582     EraseInstFromFunction(SI);
11583     ++NumCombined;
11584     return 0;
11585   }
11586
11587   // If the pointer destination is a cast, see if we can fold the cast into the
11588   // source instead.
11589   if (isa<CastInst>(Ptr))
11590     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11591       return Res;
11592   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11593     if (CE->isCast())
11594       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11595         return Res;
11596
11597   
11598   // If this store is the last instruction in the basic block (possibly
11599   // excepting debug info instructions and the pointer bitcasts that feed
11600   // into them), and if the block ends with an unconditional branch, try
11601   // to move it to the successor block.
11602   BBI = &SI; 
11603   do {
11604     ++BBI;
11605   } while (isa<DbgInfoIntrinsic>(BBI) ||
11606            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11607   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11608     if (BI->isUnconditional())
11609       if (SimplifyStoreAtEndOfBlock(SI))
11610         return 0;  // xform done!
11611   
11612   return 0;
11613 }
11614
11615 /// SimplifyStoreAtEndOfBlock - Turn things like:
11616 ///   if () { *P = v1; } else { *P = v2 }
11617 /// into a phi node with a store in the successor.
11618 ///
11619 /// Simplify things like:
11620 ///   *P = v1; if () { *P = v2; }
11621 /// into a phi node with a store in the successor.
11622 ///
11623 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11624   BasicBlock *StoreBB = SI.getParent();
11625   
11626   // Check to see if the successor block has exactly two incoming edges.  If
11627   // so, see if the other predecessor contains a store to the same location.
11628   // if so, insert a PHI node (if needed) and move the stores down.
11629   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11630   
11631   // Determine whether Dest has exactly two predecessors and, if so, compute
11632   // the other predecessor.
11633   pred_iterator PI = pred_begin(DestBB);
11634   BasicBlock *OtherBB = 0;
11635   if (*PI != StoreBB)
11636     OtherBB = *PI;
11637   ++PI;
11638   if (PI == pred_end(DestBB))
11639     return false;
11640   
11641   if (*PI != StoreBB) {
11642     if (OtherBB)
11643       return false;
11644     OtherBB = *PI;
11645   }
11646   if (++PI != pred_end(DestBB))
11647     return false;
11648
11649   // Bail out if all the relevant blocks aren't distinct (this can happen,
11650   // for example, if SI is in an infinite loop)
11651   if (StoreBB == DestBB || OtherBB == DestBB)
11652     return false;
11653
11654   // Verify that the other block ends in a branch and is not otherwise empty.
11655   BasicBlock::iterator BBI = OtherBB->getTerminator();
11656   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11657   if (!OtherBr || BBI == OtherBB->begin())
11658     return false;
11659   
11660   // If the other block ends in an unconditional branch, check for the 'if then
11661   // else' case.  there is an instruction before the branch.
11662   StoreInst *OtherStore = 0;
11663   if (OtherBr->isUnconditional()) {
11664     --BBI;
11665     // Skip over debugging info.
11666     while (isa<DbgInfoIntrinsic>(BBI) ||
11667            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11668       if (BBI==OtherBB->begin())
11669         return false;
11670       --BBI;
11671     }
11672     // If this isn't a store, or isn't a store to the same location, bail out.
11673     OtherStore = dyn_cast<StoreInst>(BBI);
11674     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11675       return false;
11676   } else {
11677     // Otherwise, the other block ended with a conditional branch. If one of the
11678     // destinations is StoreBB, then we have the if/then case.
11679     if (OtherBr->getSuccessor(0) != StoreBB && 
11680         OtherBr->getSuccessor(1) != StoreBB)
11681       return false;
11682     
11683     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11684     // if/then triangle.  See if there is a store to the same ptr as SI that
11685     // lives in OtherBB.
11686     for (;; --BBI) {
11687       // Check to see if we find the matching store.
11688       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11689         if (OtherStore->getOperand(1) != SI.getOperand(1))
11690           return false;
11691         break;
11692       }
11693       // If we find something that may be using or overwriting the stored
11694       // value, or if we run out of instructions, we can't do the xform.
11695       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11696           BBI == OtherBB->begin())
11697         return false;
11698     }
11699     
11700     // In order to eliminate the store in OtherBr, we have to
11701     // make sure nothing reads or overwrites the stored value in
11702     // StoreBB.
11703     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11704       // FIXME: This should really be AA driven.
11705       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11706         return false;
11707     }
11708   }
11709   
11710   // Insert a PHI node now if we need it.
11711   Value *MergedVal = OtherStore->getOperand(0);
11712   if (MergedVal != SI.getOperand(0)) {
11713     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11714     PN->reserveOperandSpace(2);
11715     PN->addIncoming(SI.getOperand(0), SI.getParent());
11716     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11717     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11718   }
11719   
11720   // Advance to a place where it is safe to insert the new store and
11721   // insert it.
11722   BBI = DestBB->getFirstNonPHI();
11723   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11724                                     OtherStore->isVolatile()), *BBI);
11725   
11726   // Nuke the old stores.
11727   EraseInstFromFunction(SI);
11728   EraseInstFromFunction(*OtherStore);
11729   ++NumCombined;
11730   return true;
11731 }
11732
11733
11734 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11735   // Change br (not X), label True, label False to: br X, label False, True
11736   Value *X = 0;
11737   BasicBlock *TrueDest;
11738   BasicBlock *FalseDest;
11739   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11740       !isa<Constant>(X)) {
11741     // Swap Destinations and condition...
11742     BI.setCondition(X);
11743     BI.setSuccessor(0, FalseDest);
11744     BI.setSuccessor(1, TrueDest);
11745     return &BI;
11746   }
11747
11748   // Cannonicalize fcmp_one -> fcmp_oeq
11749   FCmpInst::Predicate FPred; Value *Y;
11750   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11751                              TrueDest, FalseDest)))
11752     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11753          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11754       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11755       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11756       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11757       NewSCC->takeName(I);
11758       // Swap Destinations and condition...
11759       BI.setCondition(NewSCC);
11760       BI.setSuccessor(0, FalseDest);
11761       BI.setSuccessor(1, TrueDest);
11762       RemoveFromWorkList(I);
11763       I->eraseFromParent();
11764       AddToWorkList(NewSCC);
11765       return &BI;
11766     }
11767
11768   // Cannonicalize icmp_ne -> icmp_eq
11769   ICmpInst::Predicate IPred;
11770   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11771                       TrueDest, FalseDest)))
11772     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11773          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11774          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11775       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11776       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11777       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11778       NewSCC->takeName(I);
11779       // Swap Destinations and condition...
11780       BI.setCondition(NewSCC);
11781       BI.setSuccessor(0, FalseDest);
11782       BI.setSuccessor(1, TrueDest);
11783       RemoveFromWorkList(I);
11784       I->eraseFromParent();;
11785       AddToWorkList(NewSCC);
11786       return &BI;
11787     }
11788
11789   return 0;
11790 }
11791
11792 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11793   Value *Cond = SI.getCondition();
11794   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11795     if (I->getOpcode() == Instruction::Add)
11796       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11797         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11798         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11799           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11800                                                 AddRHS));
11801         SI.setOperand(0, I->getOperand(0));
11802         AddToWorkList(I);
11803         return &SI;
11804       }
11805   }
11806   return 0;
11807 }
11808
11809 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11810   Value *Agg = EV.getAggregateOperand();
11811
11812   if (!EV.hasIndices())
11813     return ReplaceInstUsesWith(EV, Agg);
11814
11815   if (Constant *C = dyn_cast<Constant>(Agg)) {
11816     if (isa<UndefValue>(C))
11817       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11818       
11819     if (isa<ConstantAggregateZero>(C))
11820       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11821
11822     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11823       // Extract the element indexed by the first index out of the constant
11824       Value *V = C->getOperand(*EV.idx_begin());
11825       if (EV.getNumIndices() > 1)
11826         // Extract the remaining indices out of the constant indexed by the
11827         // first index
11828         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11829       else
11830         return ReplaceInstUsesWith(EV, V);
11831     }
11832     return 0; // Can't handle other constants
11833   } 
11834   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11835     // We're extracting from an insertvalue instruction, compare the indices
11836     const unsigned *exti, *exte, *insi, *inse;
11837     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11838          exte = EV.idx_end(), inse = IV->idx_end();
11839          exti != exte && insi != inse;
11840          ++exti, ++insi) {
11841       if (*insi != *exti)
11842         // The insert and extract both reference distinctly different elements.
11843         // This means the extract is not influenced by the insert, and we can
11844         // replace the aggregate operand of the extract with the aggregate
11845         // operand of the insert. i.e., replace
11846         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11847         // %E = extractvalue { i32, { i32 } } %I, 0
11848         // with
11849         // %E = extractvalue { i32, { i32 } } %A, 0
11850         return ExtractValueInst::Create(IV->getAggregateOperand(),
11851                                         EV.idx_begin(), EV.idx_end());
11852     }
11853     if (exti == exte && insi == inse)
11854       // Both iterators are at the end: Index lists are identical. Replace
11855       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11856       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11857       // with "i32 42"
11858       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11859     if (exti == exte) {
11860       // The extract list is a prefix of the insert list. i.e. replace
11861       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11862       // %E = extractvalue { i32, { i32 } } %I, 1
11863       // with
11864       // %X = extractvalue { i32, { i32 } } %A, 1
11865       // %E = insertvalue { i32 } %X, i32 42, 0
11866       // by switching the order of the insert and extract (though the
11867       // insertvalue should be left in, since it may have other uses).
11868       Value *NewEV = InsertNewInstBefore(
11869         ExtractValueInst::Create(IV->getAggregateOperand(),
11870                                  EV.idx_begin(), EV.idx_end()),
11871         EV);
11872       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11873                                      insi, inse);
11874     }
11875     if (insi == inse)
11876       // The insert list is a prefix of the extract list
11877       // We can simply remove the common indices from the extract and make it
11878       // operate on the inserted value instead of the insertvalue result.
11879       // i.e., replace
11880       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11881       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11882       // with
11883       // %E extractvalue { i32 } { i32 42 }, 0
11884       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11885                                       exti, exte);
11886   }
11887   // Can't simplify extracts from other values. Note that nested extracts are
11888   // already simplified implicitely by the above (extract ( extract (insert) )
11889   // will be translated into extract ( insert ( extract ) ) first and then just
11890   // the value inserted, if appropriate).
11891   return 0;
11892 }
11893
11894 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11895 /// is to leave as a vector operation.
11896 static bool CheapToScalarize(Value *V, bool isConstant) {
11897   if (isa<ConstantAggregateZero>(V)) 
11898     return true;
11899   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11900     if (isConstant) return true;
11901     // If all elts are the same, we can extract.
11902     Constant *Op0 = C->getOperand(0);
11903     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11904       if (C->getOperand(i) != Op0)
11905         return false;
11906     return true;
11907   }
11908   Instruction *I = dyn_cast<Instruction>(V);
11909   if (!I) return false;
11910   
11911   // Insert element gets simplified to the inserted element or is deleted if
11912   // this is constant idx extract element and its a constant idx insertelt.
11913   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11914       isa<ConstantInt>(I->getOperand(2)))
11915     return true;
11916   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11917     return true;
11918   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11919     if (BO->hasOneUse() &&
11920         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11921          CheapToScalarize(BO->getOperand(1), isConstant)))
11922       return true;
11923   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11924     if (CI->hasOneUse() &&
11925         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11926          CheapToScalarize(CI->getOperand(1), isConstant)))
11927       return true;
11928   
11929   return false;
11930 }
11931
11932 /// Read and decode a shufflevector mask.
11933 ///
11934 /// It turns undef elements into values that are larger than the number of
11935 /// elements in the input.
11936 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11937   unsigned NElts = SVI->getType()->getNumElements();
11938   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11939     return std::vector<unsigned>(NElts, 0);
11940   if (isa<UndefValue>(SVI->getOperand(2)))
11941     return std::vector<unsigned>(NElts, 2*NElts);
11942
11943   std::vector<unsigned> Result;
11944   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11945   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11946     if (isa<UndefValue>(*i))
11947       Result.push_back(NElts*2);  // undef -> 8
11948     else
11949       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
11950   return Result;
11951 }
11952
11953 /// FindScalarElement - Given a vector and an element number, see if the scalar
11954 /// value is already around as a register, for example if it were inserted then
11955 /// extracted from the vector.
11956 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11957   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11958   const VectorType *PTy = cast<VectorType>(V->getType());
11959   unsigned Width = PTy->getNumElements();
11960   if (EltNo >= Width)  // Out of range access.
11961     return UndefValue::get(PTy->getElementType());
11962   
11963   if (isa<UndefValue>(V))
11964     return UndefValue::get(PTy->getElementType());
11965   else if (isa<ConstantAggregateZero>(V))
11966     return Constant::getNullValue(PTy->getElementType());
11967   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11968     return CP->getOperand(EltNo);
11969   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11970     // If this is an insert to a variable element, we don't know what it is.
11971     if (!isa<ConstantInt>(III->getOperand(2))) 
11972       return 0;
11973     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11974     
11975     // If this is an insert to the element we are looking for, return the
11976     // inserted value.
11977     if (EltNo == IIElt) 
11978       return III->getOperand(1);
11979     
11980     // Otherwise, the insertelement doesn't modify the value, recurse on its
11981     // vector input.
11982     return FindScalarElement(III->getOperand(0), EltNo);
11983   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11984     unsigned LHSWidth =
11985       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11986     unsigned InEl = getShuffleMask(SVI)[EltNo];
11987     if (InEl < LHSWidth)
11988       return FindScalarElement(SVI->getOperand(0), InEl);
11989     else if (InEl < LHSWidth*2)
11990       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
11991     else
11992       return UndefValue::get(PTy->getElementType());
11993   }
11994   
11995   // Otherwise, we don't know.
11996   return 0;
11997 }
11998
11999 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12000   // If vector val is undef, replace extract with scalar undef.
12001   if (isa<UndefValue>(EI.getOperand(0)))
12002     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12003
12004   // If vector val is constant 0, replace extract with scalar 0.
12005   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12006     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12007   
12008   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12009     // If vector val is constant with all elements the same, replace EI with
12010     // that element. When the elements are not identical, we cannot replace yet
12011     // (we do that below, but only when the index is constant).
12012     Constant *op0 = C->getOperand(0);
12013     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12014       if (C->getOperand(i) != op0) {
12015         op0 = 0; 
12016         break;
12017       }
12018     if (op0)
12019       return ReplaceInstUsesWith(EI, op0);
12020   }
12021   
12022   // If extracting a specified index from the vector, see if we can recursively
12023   // find a previously computed scalar that was inserted into the vector.
12024   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12025     unsigned IndexVal = IdxC->getZExtValue();
12026     unsigned VectorWidth = 
12027       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12028       
12029     // If this is extracting an invalid index, turn this into undef, to avoid
12030     // crashing the code below.
12031     if (IndexVal >= VectorWidth)
12032       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12033     
12034     // This instruction only demands the single element from the input vector.
12035     // If the input vector has a single use, simplify it based on this use
12036     // property.
12037     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12038       APInt UndefElts(VectorWidth, 0);
12039       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12040       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12041                                                 DemandedMask, UndefElts)) {
12042         EI.setOperand(0, V);
12043         return &EI;
12044       }
12045     }
12046     
12047     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
12048       return ReplaceInstUsesWith(EI, Elt);
12049     
12050     // If the this extractelement is directly using a bitcast from a vector of
12051     // the same number of elements, see if we can find the source element from
12052     // it.  In this case, we will end up needing to bitcast the scalars.
12053     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12054       if (const VectorType *VT = 
12055               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12056         if (VT->getNumElements() == VectorWidth)
12057           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12058             return new BitCastInst(Elt, EI.getType());
12059     }
12060   }
12061   
12062   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12063     if (I->hasOneUse()) {
12064       // Push extractelement into predecessor operation if legal and
12065       // profitable to do so
12066       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12067         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12068         if (CheapToScalarize(BO, isConstantElt)) {
12069           ExtractElementInst *newEI0 = 
12070             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12071                                    EI.getName()+".lhs");
12072           ExtractElementInst *newEI1 =
12073             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12074                                    EI.getName()+".rhs");
12075           InsertNewInstBefore(newEI0, EI);
12076           InsertNewInstBefore(newEI1, EI);
12077           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12078         }
12079       } else if (isa<LoadInst>(I)) {
12080         unsigned AS = 
12081           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12082         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12083                                          PointerType::get(EI.getType(), AS),EI);
12084         GetElementPtrInst *GEP =
12085           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12086         InsertNewInstBefore(GEP, EI);
12087         return new LoadInst(GEP);
12088       }
12089     }
12090     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12091       // Extracting the inserted element?
12092       if (IE->getOperand(2) == EI.getOperand(1))
12093         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12094       // If the inserted and extracted elements are constants, they must not
12095       // be the same value, extract from the pre-inserted value instead.
12096       if (isa<Constant>(IE->getOperand(2)) &&
12097           isa<Constant>(EI.getOperand(1))) {
12098         AddUsesToWorkList(EI);
12099         EI.setOperand(0, IE->getOperand(0));
12100         return &EI;
12101       }
12102     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12103       // If this is extracting an element from a shufflevector, figure out where
12104       // it came from and extract from the appropriate input element instead.
12105       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12106         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12107         Value *Src;
12108         unsigned LHSWidth =
12109           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12110
12111         if (SrcIdx < LHSWidth)
12112           Src = SVI->getOperand(0);
12113         else if (SrcIdx < LHSWidth*2) {
12114           SrcIdx -= LHSWidth;
12115           Src = SVI->getOperand(1);
12116         } else {
12117           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12118         }
12119         return new ExtractElementInst(Src, SrcIdx);
12120       }
12121     }
12122   }
12123   return 0;
12124 }
12125
12126 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12127 /// elements from either LHS or RHS, return the shuffle mask and true. 
12128 /// Otherwise, return false.
12129 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12130                                          std::vector<Constant*> &Mask) {
12131   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12132          "Invalid CollectSingleShuffleElements");
12133   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12134
12135   if (isa<UndefValue>(V)) {
12136     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12137     return true;
12138   } else if (V == LHS) {
12139     for (unsigned i = 0; i != NumElts; ++i)
12140       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12141     return true;
12142   } else if (V == RHS) {
12143     for (unsigned i = 0; i != NumElts; ++i)
12144       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12145     return true;
12146   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12147     // If this is an insert of an extract from some other vector, include it.
12148     Value *VecOp    = IEI->getOperand(0);
12149     Value *ScalarOp = IEI->getOperand(1);
12150     Value *IdxOp    = IEI->getOperand(2);
12151     
12152     if (!isa<ConstantInt>(IdxOp))
12153       return false;
12154     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12155     
12156     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12157       // Okay, we can handle this if the vector we are insertinting into is
12158       // transitively ok.
12159       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12160         // If so, update the mask to reflect the inserted undef.
12161         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12162         return true;
12163       }      
12164     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12165       if (isa<ConstantInt>(EI->getOperand(1)) &&
12166           EI->getOperand(0)->getType() == V->getType()) {
12167         unsigned ExtractedIdx =
12168           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12169         
12170         // This must be extracting from either LHS or RHS.
12171         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12172           // Okay, we can handle this if the vector we are insertinting into is
12173           // transitively ok.
12174           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12175             // If so, update the mask to reflect the inserted value.
12176             if (EI->getOperand(0) == LHS) {
12177               Mask[InsertedIdx % NumElts] = 
12178                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12179             } else {
12180               assert(EI->getOperand(0) == RHS);
12181               Mask[InsertedIdx % NumElts] = 
12182                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12183               
12184             }
12185             return true;
12186           }
12187         }
12188       }
12189     }
12190   }
12191   // TODO: Handle shufflevector here!
12192   
12193   return false;
12194 }
12195
12196 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12197 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12198 /// that computes V and the LHS value of the shuffle.
12199 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12200                                      Value *&RHS) {
12201   assert(isa<VectorType>(V->getType()) && 
12202          (RHS == 0 || V->getType() == RHS->getType()) &&
12203          "Invalid shuffle!");
12204   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12205
12206   if (isa<UndefValue>(V)) {
12207     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12208     return V;
12209   } else if (isa<ConstantAggregateZero>(V)) {
12210     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12211     return V;
12212   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12213     // If this is an insert of an extract from some other vector, include it.
12214     Value *VecOp    = IEI->getOperand(0);
12215     Value *ScalarOp = IEI->getOperand(1);
12216     Value *IdxOp    = IEI->getOperand(2);
12217     
12218     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12219       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12220           EI->getOperand(0)->getType() == V->getType()) {
12221         unsigned ExtractedIdx =
12222           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12223         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12224         
12225         // Either the extracted from or inserted into vector must be RHSVec,
12226         // otherwise we'd end up with a shuffle of three inputs.
12227         if (EI->getOperand(0) == RHS || RHS == 0) {
12228           RHS = EI->getOperand(0);
12229           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
12230           Mask[InsertedIdx % NumElts] = 
12231             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12232           return V;
12233         }
12234         
12235         if (VecOp == RHS) {
12236           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
12237           // Everything but the extracted element is replaced with the RHS.
12238           for (unsigned i = 0; i != NumElts; ++i) {
12239             if (i != InsertedIdx)
12240               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12241           }
12242           return V;
12243         }
12244         
12245         // If this insertelement is a chain that comes from exactly these two
12246         // vectors, return the vector and the effective shuffle.
12247         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12248           return EI->getOperand(0);
12249         
12250       }
12251     }
12252   }
12253   // TODO: Handle shufflevector here!
12254   
12255   // Otherwise, can't do anything fancy.  Return an identity vector.
12256   for (unsigned i = 0; i != NumElts; ++i)
12257     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12258   return V;
12259 }
12260
12261 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12262   Value *VecOp    = IE.getOperand(0);
12263   Value *ScalarOp = IE.getOperand(1);
12264   Value *IdxOp    = IE.getOperand(2);
12265   
12266   // Inserting an undef or into an undefined place, remove this.
12267   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12268     ReplaceInstUsesWith(IE, VecOp);
12269   
12270   // If the inserted element was extracted from some other vector, and if the 
12271   // indexes are constant, try to turn this into a shufflevector operation.
12272   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12273     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12274         EI->getOperand(0)->getType() == IE.getType()) {
12275       unsigned NumVectorElts = IE.getType()->getNumElements();
12276       unsigned ExtractedIdx =
12277         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12278       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12279       
12280       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12281         return ReplaceInstUsesWith(IE, VecOp);
12282       
12283       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12284         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12285       
12286       // If we are extracting a value from a vector, then inserting it right
12287       // back into the same place, just use the input vector.
12288       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12289         return ReplaceInstUsesWith(IE, VecOp);      
12290       
12291       // We could theoretically do this for ANY input.  However, doing so could
12292       // turn chains of insertelement instructions into a chain of shufflevector
12293       // instructions, and right now we do not merge shufflevectors.  As such,
12294       // only do this in a situation where it is clear that there is benefit.
12295       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12296         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12297         // the values of VecOp, except then one read from EIOp0.
12298         // Build a new shuffle mask.
12299         std::vector<Constant*> Mask;
12300         if (isa<UndefValue>(VecOp))
12301           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12302         else {
12303           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12304           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12305                                                        NumVectorElts));
12306         } 
12307         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12308         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12309                                      ConstantVector::get(Mask));
12310       }
12311       
12312       // If this insertelement isn't used by some other insertelement, turn it
12313       // (and any insertelements it points to), into one big shuffle.
12314       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12315         std::vector<Constant*> Mask;
12316         Value *RHS = 0;
12317         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12318         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12319         // We now have a shuffle of LHS, RHS, Mask.
12320         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12321       }
12322     }
12323   }
12324
12325   return 0;
12326 }
12327
12328
12329 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12330   Value *LHS = SVI.getOperand(0);
12331   Value *RHS = SVI.getOperand(1);
12332   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12333
12334   bool MadeChange = false;
12335
12336   // Undefined shuffle mask -> undefined value.
12337   if (isa<UndefValue>(SVI.getOperand(2)))
12338     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12339
12340   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12341
12342   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12343     return 0;
12344
12345   APInt UndefElts(VWidth, 0);
12346   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12347   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12348     LHS = SVI.getOperand(0);
12349     RHS = SVI.getOperand(1);
12350     MadeChange = true;
12351   }
12352   
12353   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12354   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12355   if (LHS == RHS || isa<UndefValue>(LHS)) {
12356     if (isa<UndefValue>(LHS) && LHS == RHS) {
12357       // shuffle(undef,undef,mask) -> undef.
12358       return ReplaceInstUsesWith(SVI, LHS);
12359     }
12360     
12361     // Remap any references to RHS to use LHS.
12362     std::vector<Constant*> Elts;
12363     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12364       if (Mask[i] >= 2*e)
12365         Elts.push_back(UndefValue::get(Type::Int32Ty));
12366       else {
12367         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12368             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12369           Mask[i] = 2*e;     // Turn into undef.
12370           Elts.push_back(UndefValue::get(Type::Int32Ty));
12371         } else {
12372           Mask[i] = Mask[i] % e;  // Force to LHS.
12373           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12374         }
12375       }
12376     }
12377     SVI.setOperand(0, SVI.getOperand(1));
12378     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12379     SVI.setOperand(2, ConstantVector::get(Elts));
12380     LHS = SVI.getOperand(0);
12381     RHS = SVI.getOperand(1);
12382     MadeChange = true;
12383   }
12384   
12385   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12386   bool isLHSID = true, isRHSID = true;
12387     
12388   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12389     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12390     // Is this an identity shuffle of the LHS value?
12391     isLHSID &= (Mask[i] == i);
12392       
12393     // Is this an identity shuffle of the RHS value?
12394     isRHSID &= (Mask[i]-e == i);
12395   }
12396
12397   // Eliminate identity shuffles.
12398   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12399   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12400   
12401   // If the LHS is a shufflevector itself, see if we can combine it with this
12402   // one without producing an unusual shuffle.  Here we are really conservative:
12403   // we are absolutely afraid of producing a shuffle mask not in the input
12404   // program, because the code gen may not be smart enough to turn a merged
12405   // shuffle into two specific shuffles: it may produce worse code.  As such,
12406   // we only merge two shuffles if the result is one of the two input shuffle
12407   // masks.  In this case, merging the shuffles just removes one instruction,
12408   // which we know is safe.  This is good for things like turning:
12409   // (splat(splat)) -> splat.
12410   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12411     if (isa<UndefValue>(RHS)) {
12412       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12413
12414       std::vector<unsigned> NewMask;
12415       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12416         if (Mask[i] >= 2*e)
12417           NewMask.push_back(2*e);
12418         else
12419           NewMask.push_back(LHSMask[Mask[i]]);
12420       
12421       // If the result mask is equal to the src shuffle or this shuffle mask, do
12422       // the replacement.
12423       if (NewMask == LHSMask || NewMask == Mask) {
12424         unsigned LHSInNElts =
12425           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12426         std::vector<Constant*> Elts;
12427         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12428           if (NewMask[i] >= LHSInNElts*2) {
12429             Elts.push_back(UndefValue::get(Type::Int32Ty));
12430           } else {
12431             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12432           }
12433         }
12434         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12435                                      LHSSVI->getOperand(1),
12436                                      ConstantVector::get(Elts));
12437       }
12438     }
12439   }
12440
12441   return MadeChange ? &SVI : 0;
12442 }
12443
12444
12445
12446
12447 /// TryToSinkInstruction - Try to move the specified instruction from its
12448 /// current block into the beginning of DestBlock, which can only happen if it's
12449 /// safe to move the instruction past all of the instructions between it and the
12450 /// end of its block.
12451 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12452   assert(I->hasOneUse() && "Invariants didn't hold!");
12453
12454   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12455   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12456     return false;
12457
12458   // Do not sink alloca instructions out of the entry block.
12459   if (isa<AllocaInst>(I) && I->getParent() ==
12460         &DestBlock->getParent()->getEntryBlock())
12461     return false;
12462
12463   // We can only sink load instructions if there is nothing between the load and
12464   // the end of block that could change the value.
12465   if (I->mayReadFromMemory()) {
12466     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12467          Scan != E; ++Scan)
12468       if (Scan->mayWriteToMemory())
12469         return false;
12470   }
12471
12472   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12473
12474   CopyPrecedingStopPoint(I, InsertPos);
12475   I->moveBefore(InsertPos);
12476   ++NumSunkInst;
12477   return true;
12478 }
12479
12480
12481 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12482 /// all reachable code to the worklist.
12483 ///
12484 /// This has a couple of tricks to make the code faster and more powerful.  In
12485 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12486 /// them to the worklist (this significantly speeds up instcombine on code where
12487 /// many instructions are dead or constant).  Additionally, if we find a branch
12488 /// whose condition is a known constant, we only visit the reachable successors.
12489 ///
12490 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12491                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12492                                        InstCombiner &IC,
12493                                        const TargetData *TD) {
12494   SmallVector<BasicBlock*, 256> Worklist;
12495   Worklist.push_back(BB);
12496
12497   while (!Worklist.empty()) {
12498     BB = Worklist.back();
12499     Worklist.pop_back();
12500     
12501     // We have now visited this block!  If we've already been here, ignore it.
12502     if (!Visited.insert(BB)) continue;
12503
12504     DbgInfoIntrinsic *DBI_Prev = NULL;
12505     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12506       Instruction *Inst = BBI++;
12507       
12508       // DCE instruction if trivially dead.
12509       if (isInstructionTriviallyDead(Inst)) {
12510         ++NumDeadInst;
12511         DOUT << "IC: DCE: " << *Inst;
12512         Inst->eraseFromParent();
12513         continue;
12514       }
12515       
12516       // ConstantProp instruction if trivially constant.
12517       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12518         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12519         Inst->replaceAllUsesWith(C);
12520         ++NumConstProp;
12521         Inst->eraseFromParent();
12522         continue;
12523       }
12524      
12525       // If there are two consecutive llvm.dbg.stoppoint calls then
12526       // it is likely that the optimizer deleted code in between these
12527       // two intrinsics. 
12528       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12529       if (DBI_Next) {
12530         if (DBI_Prev
12531             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12532             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12533           IC.RemoveFromWorkList(DBI_Prev);
12534           DBI_Prev->eraseFromParent();
12535         }
12536         DBI_Prev = DBI_Next;
12537       } else {
12538         DBI_Prev = 0;
12539       }
12540
12541       IC.AddToWorkList(Inst);
12542     }
12543
12544     // Recursively visit successors.  If this is a branch or switch on a
12545     // constant, only visit the reachable successor.
12546     TerminatorInst *TI = BB->getTerminator();
12547     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12548       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12549         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12550         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12551         Worklist.push_back(ReachableBB);
12552         continue;
12553       }
12554     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12555       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12556         // See if this is an explicit destination.
12557         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12558           if (SI->getCaseValue(i) == Cond) {
12559             BasicBlock *ReachableBB = SI->getSuccessor(i);
12560             Worklist.push_back(ReachableBB);
12561             continue;
12562           }
12563         
12564         // Otherwise it is the default destination.
12565         Worklist.push_back(SI->getSuccessor(0));
12566         continue;
12567       }
12568     }
12569     
12570     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12571       Worklist.push_back(TI->getSuccessor(i));
12572   }
12573 }
12574
12575 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12576   bool Changed = false;
12577   TD = &getAnalysis<TargetData>();
12578   
12579   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12580              << F.getNameStr() << "\n");
12581
12582   {
12583     // Do a depth-first traversal of the function, populate the worklist with
12584     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12585     // track of which blocks we visit.
12586     SmallPtrSet<BasicBlock*, 64> Visited;
12587     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12588
12589     // Do a quick scan over the function.  If we find any blocks that are
12590     // unreachable, remove any instructions inside of them.  This prevents
12591     // the instcombine code from having to deal with some bad special cases.
12592     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12593       if (!Visited.count(BB)) {
12594         Instruction *Term = BB->getTerminator();
12595         while (Term != BB->begin()) {   // Remove instrs bottom-up
12596           BasicBlock::iterator I = Term; --I;
12597
12598           DOUT << "IC: DCE: " << *I;
12599           // A debug intrinsic shouldn't force another iteration if we weren't
12600           // going to do one without it.
12601           if (!isa<DbgInfoIntrinsic>(I)) {
12602             ++NumDeadInst;
12603             Changed = true;
12604           }
12605           if (!I->use_empty())
12606             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12607           I->eraseFromParent();
12608         }
12609       }
12610   }
12611
12612   while (!Worklist.empty()) {
12613     Instruction *I = RemoveOneFromWorkList();
12614     if (I == 0) continue;  // skip null values.
12615
12616     // Check to see if we can DCE the instruction.
12617     if (isInstructionTriviallyDead(I)) {
12618       // Add operands to the worklist.
12619       if (I->getNumOperands() < 4)
12620         AddUsesToWorkList(*I);
12621       ++NumDeadInst;
12622
12623       DOUT << "IC: DCE: " << *I;
12624
12625       I->eraseFromParent();
12626       RemoveFromWorkList(I);
12627       Changed = true;
12628       continue;
12629     }
12630
12631     // Instruction isn't dead, see if we can constant propagate it.
12632     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12633       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12634
12635       // Add operands to the worklist.
12636       AddUsesToWorkList(*I);
12637       ReplaceInstUsesWith(*I, C);
12638
12639       ++NumConstProp;
12640       I->eraseFromParent();
12641       RemoveFromWorkList(I);
12642       Changed = true;
12643       continue;
12644     }
12645
12646     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12647       // See if we can constant fold its operands.
12648       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12649         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12650           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12651             if (NewC != CE) {
12652               i->set(NewC);
12653               Changed = true;
12654             }
12655     }
12656
12657     // See if we can trivially sink this instruction to a successor basic block.
12658     if (I->hasOneUse()) {
12659       BasicBlock *BB = I->getParent();
12660       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12661       if (UserParent != BB) {
12662         bool UserIsSuccessor = false;
12663         // See if the user is one of our successors.
12664         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12665           if (*SI == UserParent) {
12666             UserIsSuccessor = true;
12667             break;
12668           }
12669
12670         // If the user is one of our immediate successors, and if that successor
12671         // only has us as a predecessors (we'd have to split the critical edge
12672         // otherwise), we can keep going.
12673         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12674             next(pred_begin(UserParent)) == pred_end(UserParent))
12675           // Okay, the CFG is simple enough, try to sink this instruction.
12676           Changed |= TryToSinkInstruction(I, UserParent);
12677       }
12678     }
12679
12680     // Now that we have an instruction, try combining it to simplify it...
12681 #ifndef NDEBUG
12682     std::string OrigI;
12683 #endif
12684     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12685     if (Instruction *Result = visit(*I)) {
12686       ++NumCombined;
12687       // Should we replace the old instruction with a new one?
12688       if (Result != I) {
12689         DOUT << "IC: Old = " << *I
12690              << "    New = " << *Result;
12691
12692         // Everything uses the new instruction now.
12693         I->replaceAllUsesWith(Result);
12694
12695         // Push the new instruction and any users onto the worklist.
12696         AddToWorkList(Result);
12697         AddUsersToWorkList(*Result);
12698
12699         // Move the name to the new instruction first.
12700         Result->takeName(I);
12701
12702         // Insert the new instruction into the basic block...
12703         BasicBlock *InstParent = I->getParent();
12704         BasicBlock::iterator InsertPos = I;
12705
12706         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12707           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12708             ++InsertPos;
12709
12710         InstParent->getInstList().insert(InsertPos, Result);
12711
12712         // Make sure that we reprocess all operands now that we reduced their
12713         // use counts.
12714         AddUsesToWorkList(*I);
12715
12716         // Instructions can end up on the worklist more than once.  Make sure
12717         // we do not process an instruction that has been deleted.
12718         RemoveFromWorkList(I);
12719
12720         // Erase the old instruction.
12721         InstParent->getInstList().erase(I);
12722       } else {
12723 #ifndef NDEBUG
12724         DOUT << "IC: Mod = " << OrigI
12725              << "    New = " << *I;
12726 #endif
12727
12728         // If the instruction was modified, it's possible that it is now dead.
12729         // if so, remove it.
12730         if (isInstructionTriviallyDead(I)) {
12731           // Make sure we process all operands now that we are reducing their
12732           // use counts.
12733           AddUsesToWorkList(*I);
12734
12735           // Instructions may end up in the worklist more than once.  Erase all
12736           // occurrences of this instruction.
12737           RemoveFromWorkList(I);
12738           I->eraseFromParent();
12739         } else {
12740           AddToWorkList(I);
12741           AddUsersToWorkList(*I);
12742         }
12743       }
12744       Changed = true;
12745     }
12746   }
12747
12748   assert(WorklistMap.empty() && "Worklist empty, but map not?");
12749     
12750   // Do an explicit clear, this shrinks the map if needed.
12751   WorklistMap.clear();
12752   return Changed;
12753 }
12754
12755
12756 bool InstCombiner::runOnFunction(Function &F) {
12757   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12758   
12759   bool EverMadeChange = false;
12760
12761   // Iterate while there is work to do.
12762   unsigned Iteration = 0;
12763   while (DoOneIteration(F, Iteration++))
12764     EverMadeChange = true;
12765   return EverMadeChange;
12766 }
12767
12768 FunctionPass *llvm::createInstructionCombiningPass() {
12769   return new InstCombiner();
12770 }