Don't do the X * 0.0 -> 0.0 transformation in instcombine, because
[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 *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
227     Instruction *visitSelectInst(SelectInst &SI);
228     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
229     Instruction *visitCallInst(CallInst &CI);
230     Instruction *visitInvokeInst(InvokeInst &II);
231     Instruction *visitPHINode(PHINode &PN);
232     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
233     Instruction *visitAllocationInst(AllocationInst &AI);
234     Instruction *visitFreeInst(FreeInst &FI);
235     Instruction *visitLoadInst(LoadInst &LI);
236     Instruction *visitStoreInst(StoreInst &SI);
237     Instruction *visitBranchInst(BranchInst &BI);
238     Instruction *visitSwitchInst(SwitchInst &SI);
239     Instruction *visitInsertElementInst(InsertElementInst &IE);
240     Instruction *visitExtractElementInst(ExtractElementInst &EI);
241     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
242     Instruction *visitExtractValueInst(ExtractValueInst &EV);
243
244     // visitInstruction - Specify what to return for unhandled instructions...
245     Instruction *visitInstruction(Instruction &I) { return 0; }
246
247   private:
248     Instruction *visitCallSite(CallSite CS);
249     bool transformConstExprCastCall(CallSite CS);
250     Instruction *transformCallThroughTrampoline(CallSite CS);
251     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
252                                    bool DoXform = true);
253     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
254     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
255
256
257   public:
258     // InsertNewInstBefore - insert an instruction New before instruction Old
259     // in the program.  Add the new instruction to the worklist.
260     //
261     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
262       assert(New && New->getParent() == 0 &&
263              "New instruction already inserted into a basic block!");
264       BasicBlock *BB = Old.getParent();
265       BB->getInstList().insert(&Old, New);  // Insert inst
266       AddToWorkList(New);
267       return New;
268     }
269
270     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
271     /// This also adds the cast to the worklist.  Finally, this returns the
272     /// cast.
273     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
274                             Instruction &Pos) {
275       if (V->getType() == Ty) return V;
276
277       if (Constant *CV = dyn_cast<Constant>(V))
278         return ConstantExpr::getCast(opc, CV, Ty);
279       
280       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
281       AddToWorkList(C);
282       return C;
283     }
284         
285     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
286       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
287     }
288
289
290     // ReplaceInstUsesWith - This method is to be used when an instruction is
291     // found to be dead, replacable with another preexisting expression.  Here
292     // we add all uses of I to the worklist, replace all uses of I with the new
293     // value, then return I, so that the inst combiner will know that I was
294     // modified.
295     //
296     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
297       AddUsersToWorkList(I);         // Add all modified instrs to worklist
298       if (&I != V) {
299         I.replaceAllUsesWith(V);
300         return &I;
301       } else {
302         // If we are replacing the instruction with itself, this must be in a
303         // segment of unreachable code, so just clobber the instruction.
304         I.replaceAllUsesWith(UndefValue::get(I.getType()));
305         return &I;
306       }
307     }
308
309     // EraseInstFromFunction - When dealing with an instruction that has side
310     // effects or produces a void value, we can't rely on DCE to delete the
311     // instruction.  Instead, visit methods should return the value returned by
312     // this function.
313     Instruction *EraseInstFromFunction(Instruction &I) {
314       assert(I.use_empty() && "Cannot erase instruction that is used!");
315       AddUsesToWorkList(I);
316       RemoveFromWorkList(&I);
317       I.eraseFromParent();
318       return 0;  // Don't do anything with FI
319     }
320         
321     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
322                            APInt &KnownOne, unsigned Depth = 0) const {
323       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
324     }
325     
326     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
327                            unsigned Depth = 0) const {
328       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
329     }
330     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
331       return llvm::ComputeNumSignBits(Op, TD, Depth);
332     }
333
334   private:
335
336     /// SimplifyCommutative - This performs a few simplifications for 
337     /// commutative operators.
338     bool SimplifyCommutative(BinaryOperator &I);
339
340     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
341     /// most-complex to least-complex order.
342     bool SimplifyCompare(CmpInst &I);
343
344     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
345     /// based on the demanded bits.
346     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
347                                    APInt& KnownZero, APInt& KnownOne,
348                                    unsigned Depth);
349     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
350                               APInt& KnownZero, APInt& KnownOne,
351                               unsigned Depth=0);
352         
353     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
354     /// SimplifyDemandedBits knows about.  See if the instruction has any
355     /// properties that allow us to simplify its operands.
356     bool SimplifyDemandedInstructionBits(Instruction &Inst);
357         
358     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
359                                       APInt& UndefElts, unsigned Depth = 0);
360       
361     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
362     // PHI node as operand #0, see if we can fold the instruction into the PHI
363     // (which is only possible if all operands to the PHI are constants).
364     Instruction *FoldOpIntoPhi(Instruction &I);
365
366     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
367     // operator and they all are only used by the PHI, PHI together their
368     // inputs, and do the operation once, to the result of the PHI.
369     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
370     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
371     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
372
373     
374     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
375                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
376     
377     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
378                               bool isSub, Instruction &I);
379     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
380                                  bool isSigned, bool Inside, Instruction &IB);
381     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
382     Instruction *MatchBSwap(BinaryOperator &I);
383     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
384     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
385     Instruction *SimplifyMemSet(MemSetInst *MI);
386
387
388     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
389
390     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
391                                     unsigned CastOpc, int &NumCastsRemoved);
392     unsigned GetOrEnforceKnownAlignment(Value *V,
393                                         unsigned PrefAlign = 0);
394
395   };
396 }
397
398 char InstCombiner::ID = 0;
399 static RegisterPass<InstCombiner>
400 X("instcombine", "Combine redundant instructions");
401
402 // getComplexity:  Assign a complexity or rank value to LLVM Values...
403 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
404 static unsigned getComplexity(Value *V) {
405   if (isa<Instruction>(V)) {
406     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
407       return 3;
408     return 4;
409   }
410   if (isa<Argument>(V)) return 3;
411   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
412 }
413
414 // isOnlyUse - Return true if this instruction will be deleted if we stop using
415 // it.
416 static bool isOnlyUse(Value *V) {
417   return V->hasOneUse() || isa<Constant>(V);
418 }
419
420 // getPromotedType - Return the specified type promoted as it would be to pass
421 // though a va_arg area...
422 static const Type *getPromotedType(const Type *Ty) {
423   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
424     if (ITy->getBitWidth() < 32)
425       return Type::Int32Ty;
426   }
427   return Ty;
428 }
429
430 /// getBitCastOperand - If the specified operand is a CastInst, a constant
431 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
432 /// operand value, otherwise return null.
433 static Value *getBitCastOperand(Value *V) {
434   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
435     // BitCastInst?
436     return I->getOperand(0);
437   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
438     // GetElementPtrInst?
439     if (GEP->hasAllZeroIndices())
440       return GEP->getOperand(0);
441   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
442     if (CE->getOpcode() == Instruction::BitCast)
443       // BitCast ConstantExp?
444       return CE->getOperand(0);
445     else if (CE->getOpcode() == Instruction::GetElementPtr) {
446       // GetElementPtr ConstantExp?
447       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
448            I != E; ++I) {
449         ConstantInt *CI = dyn_cast<ConstantInt>(I);
450         if (!CI || !CI->isZero())
451           // Any non-zero indices? Not cast-like.
452           return 0;
453       }
454       // All-zero indices? This is just like casting.
455       return CE->getOperand(0);
456     }
457   }
458   return 0;
459 }
460
461 /// This function is a wrapper around CastInst::isEliminableCastPair. It
462 /// simply extracts arguments and returns what that function returns.
463 static Instruction::CastOps 
464 isEliminableCastPair(
465   const CastInst *CI, ///< The first cast instruction
466   unsigned opcode,       ///< The opcode of the second cast instruction
467   const Type *DstTy,     ///< The target type for the second cast instruction
468   TargetData *TD         ///< The target data for pointer size
469 ) {
470   
471   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
472   const Type *MidTy = CI->getType();                  // B from above
473
474   // Get the opcodes of the two Cast instructions
475   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
476   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
477
478   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
479                                                 DstTy, TD->getIntPtrType());
480   
481   // We don't want to form an inttoptr or ptrtoint that converts to an integer
482   // type that differs from the pointer size.
483   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
484       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
485     Res = 0;
486   
487   return Instruction::CastOps(Res);
488 }
489
490 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
491 /// in any code being generated.  It does not require codegen if V is simple
492 /// enough or if the cast can be folded into other casts.
493 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
494                               const Type *Ty, TargetData *TD) {
495   if (V->getType() == Ty || isa<Constant>(V)) return false;
496   
497   // If this is another cast that can be eliminated, it isn't codegen either.
498   if (const CastInst *CI = dyn_cast<CastInst>(V))
499     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
500       return false;
501   return true;
502 }
503
504 // SimplifyCommutative - This performs a few simplifications for commutative
505 // operators:
506 //
507 //  1. Order operands such that they are listed from right (least complex) to
508 //     left (most complex).  This puts constants before unary operators before
509 //     binary operators.
510 //
511 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
512 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
513 //
514 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
515   bool Changed = false;
516   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
517     Changed = !I.swapOperands();
518
519   if (!I.isAssociative()) return Changed;
520   Instruction::BinaryOps Opcode = I.getOpcode();
521   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
522     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
523       if (isa<Constant>(I.getOperand(1))) {
524         Constant *Folded = ConstantExpr::get(I.getOpcode(),
525                                              cast<Constant>(I.getOperand(1)),
526                                              cast<Constant>(Op->getOperand(1)));
527         I.setOperand(0, Op->getOperand(0));
528         I.setOperand(1, Folded);
529         return true;
530       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
531         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
532             isOnlyUse(Op) && isOnlyUse(Op1)) {
533           Constant *C1 = cast<Constant>(Op->getOperand(1));
534           Constant *C2 = cast<Constant>(Op1->getOperand(1));
535
536           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
537           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
538           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
539                                                     Op1->getOperand(0),
540                                                     Op1->getName(), &I);
541           AddToWorkList(New);
542           I.setOperand(0, New);
543           I.setOperand(1, Folded);
544           return true;
545         }
546     }
547   return Changed;
548 }
549
550 /// SimplifyCompare - For a CmpInst this function just orders the operands
551 /// so that theyare listed from right (least complex) to left (most complex).
552 /// This puts constants before unary operators before binary operators.
553 bool InstCombiner::SimplifyCompare(CmpInst &I) {
554   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
555     return false;
556   I.swapOperands();
557   // Compare instructions are not associative so there's nothing else we can do.
558   return true;
559 }
560
561 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
562 // if the LHS is a constant zero (which is the 'negate' form).
563 //
564 static inline Value *dyn_castNegVal(Value *V) {
565   if (BinaryOperator::isNeg(V))
566     return BinaryOperator::getNegArgument(V);
567
568   // Constants can be considered to be negated values if they can be folded.
569   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
570     return ConstantExpr::getNeg(C);
571
572   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
573     if (C->getType()->getElementType()->isInteger())
574       return ConstantExpr::getNeg(C);
575
576   return 0;
577 }
578
579 static inline Value *dyn_castNotVal(Value *V) {
580   if (BinaryOperator::isNot(V))
581     return BinaryOperator::getNotArgument(V);
582
583   // Constants can be considered to be not'ed values...
584   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
585     return ConstantInt::get(~C->getValue());
586   return 0;
587 }
588
589 // dyn_castFoldableMul - If this value is a multiply that can be folded into
590 // other computations (because it has a constant operand), return the
591 // non-constant operand of the multiply, and set CST to point to the multiplier.
592 // Otherwise, return null.
593 //
594 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
595   if (V->hasOneUse() && V->getType()->isInteger())
596     if (Instruction *I = dyn_cast<Instruction>(V)) {
597       if (I->getOpcode() == Instruction::Mul)
598         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
599           return I->getOperand(0);
600       if (I->getOpcode() == Instruction::Shl)
601         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
602           // The multiplier is really 1 << CST.
603           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
604           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
605           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
606           return I->getOperand(0);
607         }
608     }
609   return 0;
610 }
611
612 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
613 /// expression, return it.
614 static User *dyn_castGetElementPtr(Value *V) {
615   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
616   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
617     if (CE->getOpcode() == Instruction::GetElementPtr)
618       return cast<User>(V);
619   return false;
620 }
621
622 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
623 /// opcode value. Otherwise return UserOp1.
624 static unsigned getOpcode(const Value *V) {
625   if (const Instruction *I = dyn_cast<Instruction>(V))
626     return I->getOpcode();
627   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
628     return CE->getOpcode();
629   // Use UserOp1 to mean there's no opcode.
630   return Instruction::UserOp1;
631 }
632
633 /// AddOne - Add one to a ConstantInt
634 static ConstantInt *AddOne(ConstantInt *C) {
635   APInt Val(C->getValue());
636   return ConstantInt::get(++Val);
637 }
638 /// SubOne - Subtract one from a ConstantInt
639 static ConstantInt *SubOne(ConstantInt *C) {
640   APInt Val(C->getValue());
641   return ConstantInt::get(--Val);
642 }
643 /// Add - Add two ConstantInts together
644 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
645   return ConstantInt::get(C1->getValue() + C2->getValue());
646 }
647 /// And - Bitwise AND two ConstantInts together
648 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
649   return ConstantInt::get(C1->getValue() & C2->getValue());
650 }
651 /// Subtract - Subtract one ConstantInt from another
652 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
653   return ConstantInt::get(C1->getValue() - C2->getValue());
654 }
655 /// Multiply - Multiply two ConstantInts together
656 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
657   return ConstantInt::get(C1->getValue() * C2->getValue());
658 }
659 /// MultiplyOverflows - True if the multiply can not be expressed in an int
660 /// this size.
661 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
662   uint32_t W = C1->getBitWidth();
663   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
664   if (sign) {
665     LHSExt.sext(W * 2);
666     RHSExt.sext(W * 2);
667   } else {
668     LHSExt.zext(W * 2);
669     RHSExt.zext(W * 2);
670   }
671
672   APInt MulExt = LHSExt * RHSExt;
673
674   if (sign) {
675     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
676     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
677     return MulExt.slt(Min) || MulExt.sgt(Max);
678   } else 
679     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
680 }
681
682
683 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
684 /// specified instruction is a constant integer.  If so, check to see if there
685 /// are any bits set in the constant that are not demanded.  If so, shrink the
686 /// constant and return true.
687 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
688                                    APInt Demanded) {
689   assert(I && "No instruction?");
690   assert(OpNo < I->getNumOperands() && "Operand index too large");
691
692   // If the operand is not a constant integer, nothing to do.
693   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
694   if (!OpC) return false;
695
696   // If there are no bits set that aren't demanded, nothing to do.
697   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
698   if ((~Demanded & OpC->getValue()) == 0)
699     return false;
700
701   // This instruction is producing bits that are not demanded. Shrink the RHS.
702   Demanded &= OpC->getValue();
703   I->setOperand(OpNo, ConstantInt::get(Demanded));
704   return true;
705 }
706
707 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
708 // set of known zero and one bits, compute the maximum and minimum values that
709 // could have the specified known zero and known one bits, returning them in
710 // min/max.
711 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
712                                                    const APInt& KnownOne,
713                                                    APInt& Min, APInt& Max) {
714   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
715          KnownZero.getBitWidth() == Min.getBitWidth() &&
716          KnownZero.getBitWidth() == Max.getBitWidth() &&
717          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
718   APInt UnknownBits = ~(KnownZero|KnownOne);
719
720   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
721   // bit if it is unknown.
722   Min = KnownOne;
723   Max = KnownOne|UnknownBits;
724   
725   if (UnknownBits.isNegative()) { // Sign bit is unknown
726     Min.set(Min.getBitWidth()-1);
727     Max.clear(Max.getBitWidth()-1);
728   }
729 }
730
731 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
732 // a set of known zero and one bits, compute the maximum and minimum values that
733 // could have the specified known zero and known one bits, returning them in
734 // min/max.
735 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
736                                                      const APInt &KnownOne,
737                                                      APInt &Min, APInt &Max) {
738   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
739          KnownZero.getBitWidth() == Min.getBitWidth() &&
740          KnownZero.getBitWidth() == Max.getBitWidth() &&
741          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
742   APInt UnknownBits = ~(KnownZero|KnownOne);
743   
744   // The minimum value is when the unknown bits are all zeros.
745   Min = KnownOne;
746   // The maximum value is when the unknown bits are all ones.
747   Max = KnownOne|UnknownBits;
748 }
749
750 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
751 /// SimplifyDemandedBits knows about.  See if the instruction has any
752 /// properties that allow us to simplify its operands.
753 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
754   unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
755   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
756   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
757   
758   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
759                                      KnownZero, KnownOne, 0);
760   if (V == 0) return false;
761   if (V == &Inst) return true;
762   ReplaceInstUsesWith(Inst, V);
763   return true;
764 }
765
766 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
767 /// specified instruction operand if possible, updating it in place.  It returns
768 /// true if it made any change and false otherwise.
769 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
770                                         APInt &KnownZero, APInt &KnownOne,
771                                         unsigned Depth) {
772   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
773                                           KnownZero, KnownOne, Depth);
774   if (NewVal == 0) return false;
775   U.set(NewVal);
776   return true;
777 }
778
779
780 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
781 /// value based on the demanded bits.  When this function is called, it is known
782 /// that only the bits set in DemandedMask of the result of V are ever used
783 /// downstream. Consequently, depending on the mask and V, it may be possible
784 /// to replace V with a constant or one of its operands. In such cases, this
785 /// function does the replacement and returns true. In all other cases, it
786 /// returns false after analyzing the expression and setting KnownOne and known
787 /// to be one in the expression.  KnownZero contains all the bits that are known
788 /// to be zero in the expression. These are provided to potentially allow the
789 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
790 /// the expression. KnownOne and KnownZero always follow the invariant that 
791 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
792 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
793 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
794 /// and KnownOne must all be the same.
795 ///
796 /// This returns null if it did not change anything and it permits no
797 /// simplification.  This returns V itself if it did some simplification of V's
798 /// operands based on the information about what bits are demanded. This returns
799 /// some other non-null value if it found out that V is equal to another value
800 /// in the context where the specified bits are demanded, but not for all users.
801 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
802                                              APInt &KnownZero, APInt &KnownOne,
803                                              unsigned Depth) {
804   assert(V != 0 && "Null pointer of Value???");
805   assert(Depth <= 6 && "Limit Search Depth");
806   uint32_t BitWidth = DemandedMask.getBitWidth();
807   const Type *VTy = V->getType();
808   assert((TD || !isa<PointerType>(VTy)) &&
809          "SimplifyDemandedBits needs to know bit widths!");
810   assert((!TD || TD->getTypeSizeInBits(VTy) == BitWidth) &&
811          (!isa<IntegerType>(VTy) ||
812           VTy->getPrimitiveSizeInBits() == BitWidth) &&
813          KnownZero.getBitWidth() == BitWidth &&
814          KnownOne.getBitWidth() == BitWidth &&
815          "Value *V, DemandedMask, KnownZero and KnownOne \
816           must have same BitWidth");
817   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
818     // We know all of the bits for a constant!
819     KnownOne = CI->getValue() & DemandedMask;
820     KnownZero = ~KnownOne & DemandedMask;
821     return 0;
822   }
823   if (isa<ConstantPointerNull>(V)) {
824     // We know all of the bits for a constant!
825     KnownOne.clear();
826     KnownZero = DemandedMask;
827     return 0;
828   }
829
830   KnownZero.clear();
831   KnownOne.clear();
832   if (DemandedMask == 0) {   // Not demanding any bits from V.
833     if (isa<UndefValue>(V))
834       return 0;
835     return UndefValue::get(VTy);
836   }
837   
838   if (Depth == 6)        // Limit search depth.
839     return 0;
840   
841   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
842   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
843
844   Instruction *I = dyn_cast<Instruction>(V);
845   if (!I) {
846     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
847     return 0;        // Only analyze instructions.
848   }
849
850   // If there are multiple uses of this value and we aren't at the root, then
851   // we can't do any simplifications of the operands, because DemandedMask
852   // only reflects the bits demanded by *one* of the users.
853   if (Depth != 0 && !I->hasOneUse()) {
854     // Despite the fact that we can't simplify this instruction in all User's
855     // context, we can at least compute the knownzero/knownone bits, and we can
856     // do simplifications that apply to *just* the one user if we know that
857     // this instruction has a simpler value in that context.
858     if (I->getOpcode() == Instruction::And) {
859       // If either the LHS or the RHS are Zero, the result is zero.
860       ComputeMaskedBits(I->getOperand(1), DemandedMask,
861                         RHSKnownZero, RHSKnownOne, Depth+1);
862       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
863                         LHSKnownZero, LHSKnownOne, Depth+1);
864       
865       // If all of the demanded bits are known 1 on one side, return the other.
866       // These bits cannot contribute to the result of the 'and' in this
867       // context.
868       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
869           (DemandedMask & ~LHSKnownZero))
870         return I->getOperand(0);
871       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
872           (DemandedMask & ~RHSKnownZero))
873         return I->getOperand(1);
874       
875       // If all of the demanded bits in the inputs are known zeros, return zero.
876       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
877         return Constant::getNullValue(VTy);
878       
879     } else if (I->getOpcode() == Instruction::Or) {
880       // We can simplify (X|Y) -> X or Y in the user's context if we know that
881       // only bits from X or Y are demanded.
882       
883       // If either the LHS or the RHS are One, the result is One.
884       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
885                         RHSKnownZero, RHSKnownOne, Depth+1);
886       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
887                         LHSKnownZero, LHSKnownOne, Depth+1);
888       
889       // If all of the demanded bits are known zero on one side, return the
890       // other.  These bits cannot contribute to the result of the 'or' in this
891       // context.
892       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
893           (DemandedMask & ~LHSKnownOne))
894         return I->getOperand(0);
895       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
896           (DemandedMask & ~RHSKnownOne))
897         return I->getOperand(1);
898       
899       // If all of the potentially set bits on one side are known to be set on
900       // the other side, just use the 'other' side.
901       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
902           (DemandedMask & (~RHSKnownZero)))
903         return I->getOperand(0);
904       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
905           (DemandedMask & (~LHSKnownZero)))
906         return I->getOperand(1);
907     }
908     
909     // Compute the KnownZero/KnownOne bits to simplify things downstream.
910     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
911     return 0;
912   }
913   
914   // If this is the root being simplified, allow it to have multiple uses,
915   // just set the DemandedMask to all bits so that we can try to simplify the
916   // operands.  This allows visitTruncInst (for example) to simplify the
917   // operand of a trunc without duplicating all the logic below.
918   if (Depth == 0 && !V->hasOneUse())
919     DemandedMask = APInt::getAllOnesValue(BitWidth);
920   
921   switch (I->getOpcode()) {
922   default:
923     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
924     break;
925   case Instruction::And:
926     // If either the LHS or the RHS are Zero, the result is zero.
927     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
928                              RHSKnownZero, RHSKnownOne, Depth+1) ||
929         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
930                              LHSKnownZero, LHSKnownOne, Depth+1))
931       return I;
932     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
933     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
934
935     // If all of the demanded bits are known 1 on one side, return the other.
936     // These bits cannot contribute to the result of the 'and'.
937     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
938         (DemandedMask & ~LHSKnownZero))
939       return I->getOperand(0);
940     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
941         (DemandedMask & ~RHSKnownZero))
942       return I->getOperand(1);
943     
944     // If all of the demanded bits in the inputs are known zeros, return zero.
945     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
946       return Constant::getNullValue(VTy);
947       
948     // If the RHS is a constant, see if we can simplify it.
949     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
950       return I;
951       
952     // Output known-1 bits are only known if set in both the LHS & RHS.
953     RHSKnownOne &= LHSKnownOne;
954     // Output known-0 are known to be clear if zero in either the LHS | RHS.
955     RHSKnownZero |= LHSKnownZero;
956     break;
957   case Instruction::Or:
958     // If either the LHS or the RHS are One, the result is One.
959     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
960                              RHSKnownZero, RHSKnownOne, Depth+1) ||
961         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
962                              LHSKnownZero, LHSKnownOne, Depth+1))
963       return I;
964     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
965     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
966     
967     // If all of the demanded bits are known zero on one side, return the other.
968     // These bits cannot contribute to the result of the 'or'.
969     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
970         (DemandedMask & ~LHSKnownOne))
971       return I->getOperand(0);
972     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
973         (DemandedMask & ~RHSKnownOne))
974       return I->getOperand(1);
975
976     // If all of the potentially set bits on one side are known to be set on
977     // the other side, just use the 'other' side.
978     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
979         (DemandedMask & (~RHSKnownZero)))
980       return I->getOperand(0);
981     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
982         (DemandedMask & (~LHSKnownZero)))
983       return I->getOperand(1);
984         
985     // If the RHS is a constant, see if we can simplify it.
986     if (ShrinkDemandedConstant(I, 1, DemandedMask))
987       return I;
988           
989     // Output known-0 bits are only known if clear in both the LHS & RHS.
990     RHSKnownZero &= LHSKnownZero;
991     // Output known-1 are known to be set if set in either the LHS | RHS.
992     RHSKnownOne |= LHSKnownOne;
993     break;
994   case Instruction::Xor: {
995     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
996                              RHSKnownZero, RHSKnownOne, Depth+1) ||
997         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
998                              LHSKnownZero, LHSKnownOne, Depth+1))
999       return I;
1000     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1001     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1002     
1003     // If all of the demanded bits are known zero on one side, return the other.
1004     // These bits cannot contribute to the result of the 'xor'.
1005     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1006       return I->getOperand(0);
1007     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1008       return I->getOperand(1);
1009     
1010     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1011     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1012                          (RHSKnownOne & LHSKnownOne);
1013     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1014     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1015                         (RHSKnownOne & LHSKnownZero);
1016     
1017     // If all of the demanded bits are known to be zero on one side or the
1018     // other, turn this into an *inclusive* or.
1019     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1020     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1021       Instruction *Or =
1022         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1023                                  I->getName());
1024       return InsertNewInstBefore(Or, *I);
1025     }
1026     
1027     // If all of the demanded bits on one side are known, and all of the set
1028     // bits on that side are also known to be set on the other side, turn this
1029     // into an AND, as we know the bits will be cleared.
1030     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1031     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1032       // all known
1033       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1034         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1035         Instruction *And = 
1036           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1037         return InsertNewInstBefore(And, *I);
1038       }
1039     }
1040     
1041     // If the RHS is a constant, see if we can simplify it.
1042     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1043     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1044       return I;
1045     
1046     RHSKnownZero = KnownZeroOut;
1047     RHSKnownOne  = KnownOneOut;
1048     break;
1049   }
1050   case Instruction::Select:
1051     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1052                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1053         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1054                              LHSKnownZero, LHSKnownOne, Depth+1))
1055       return I;
1056     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1057     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1058     
1059     // If the operands are constants, see if we can simplify them.
1060     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1061         ShrinkDemandedConstant(I, 2, DemandedMask))
1062       return I;
1063     
1064     // Only known if known in both the LHS and RHS.
1065     RHSKnownOne &= LHSKnownOne;
1066     RHSKnownZero &= LHSKnownZero;
1067     break;
1068   case Instruction::Trunc: {
1069     unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1070     DemandedMask.zext(truncBf);
1071     RHSKnownZero.zext(truncBf);
1072     RHSKnownOne.zext(truncBf);
1073     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1074                              RHSKnownZero, RHSKnownOne, Depth+1))
1075       return I;
1076     DemandedMask.trunc(BitWidth);
1077     RHSKnownZero.trunc(BitWidth);
1078     RHSKnownOne.trunc(BitWidth);
1079     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1080     break;
1081   }
1082   case Instruction::BitCast:
1083     if (!I->getOperand(0)->getType()->isInteger())
1084       return false;  // vector->int or fp->int?
1085     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1086                              RHSKnownZero, RHSKnownOne, Depth+1))
1087       return I;
1088     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1089     break;
1090   case Instruction::ZExt: {
1091     // Compute the bits in the result that are not present in the input.
1092     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1093     
1094     DemandedMask.trunc(SrcBitWidth);
1095     RHSKnownZero.trunc(SrcBitWidth);
1096     RHSKnownOne.trunc(SrcBitWidth);
1097     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1098                              RHSKnownZero, RHSKnownOne, Depth+1))
1099       return I;
1100     DemandedMask.zext(BitWidth);
1101     RHSKnownZero.zext(BitWidth);
1102     RHSKnownOne.zext(BitWidth);
1103     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1104     // The top bits are known to be zero.
1105     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1106     break;
1107   }
1108   case Instruction::SExt: {
1109     // Compute the bits in the result that are not present in the input.
1110     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1111     
1112     APInt InputDemandedBits = DemandedMask & 
1113                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1114
1115     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1116     // If any of the sign extended bits are demanded, we know that the sign
1117     // bit is demanded.
1118     if ((NewBits & DemandedMask) != 0)
1119       InputDemandedBits.set(SrcBitWidth-1);
1120       
1121     InputDemandedBits.trunc(SrcBitWidth);
1122     RHSKnownZero.trunc(SrcBitWidth);
1123     RHSKnownOne.trunc(SrcBitWidth);
1124     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1125                              RHSKnownZero, RHSKnownOne, Depth+1))
1126       return I;
1127     InputDemandedBits.zext(BitWidth);
1128     RHSKnownZero.zext(BitWidth);
1129     RHSKnownOne.zext(BitWidth);
1130     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1131       
1132     // If the sign bit of the input is known set or clear, then we know the
1133     // top bits of the result.
1134
1135     // If the input sign bit is known zero, or if the NewBits are not demanded
1136     // convert this into a zero extension.
1137     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1138       // Convert to ZExt cast
1139       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1140       return InsertNewInstBefore(NewCast, *I);
1141     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1142       RHSKnownOne |= NewBits;
1143     }
1144     break;
1145   }
1146   case Instruction::Add: {
1147     // Figure out what the input bits are.  If the top bits of the and result
1148     // are not demanded, then the add doesn't demand them from its input
1149     // either.
1150     unsigned NLZ = DemandedMask.countLeadingZeros();
1151       
1152     // If there is a constant on the RHS, there are a variety of xformations
1153     // we can do.
1154     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1155       // If null, this should be simplified elsewhere.  Some of the xforms here
1156       // won't work if the RHS is zero.
1157       if (RHS->isZero())
1158         break;
1159       
1160       // If the top bit of the output is demanded, demand everything from the
1161       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1162       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1163
1164       // Find information about known zero/one bits in the input.
1165       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1166                                LHSKnownZero, LHSKnownOne, Depth+1))
1167         return I;
1168
1169       // If the RHS of the add has bits set that can't affect the input, reduce
1170       // the constant.
1171       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1172         return I;
1173       
1174       // Avoid excess work.
1175       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1176         break;
1177       
1178       // Turn it into OR if input bits are zero.
1179       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1180         Instruction *Or =
1181           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1182                                    I->getName());
1183         return InsertNewInstBefore(Or, *I);
1184       }
1185       
1186       // We can say something about the output known-zero and known-one bits,
1187       // depending on potential carries from the input constant and the
1188       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1189       // bits set and the RHS constant is 0x01001, then we know we have a known
1190       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1191       
1192       // To compute this, we first compute the potential carry bits.  These are
1193       // the bits which may be modified.  I'm not aware of a better way to do
1194       // this scan.
1195       const APInt &RHSVal = RHS->getValue();
1196       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1197       
1198       // Now that we know which bits have carries, compute the known-1/0 sets.
1199       
1200       // Bits are known one if they are known zero in one operand and one in the
1201       // other, and there is no input carry.
1202       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1203                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1204       
1205       // Bits are known zero if they are known zero in both operands and there
1206       // is no input carry.
1207       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1208     } else {
1209       // If the high-bits of this ADD are not demanded, then it does not demand
1210       // the high bits of its LHS or RHS.
1211       if (DemandedMask[BitWidth-1] == 0) {
1212         // Right fill the mask of bits for this ADD to demand the most
1213         // significant bit and all those below it.
1214         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1215         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1216                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1217             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1218                                  LHSKnownZero, LHSKnownOne, Depth+1))
1219           return I;
1220       }
1221     }
1222     break;
1223   }
1224   case Instruction::Sub:
1225     // If the high-bits of this SUB are not demanded, then it does not demand
1226     // the high bits of its LHS or RHS.
1227     if (DemandedMask[BitWidth-1] == 0) {
1228       // Right fill the mask of bits for this SUB to demand the most
1229       // significant bit and all those below it.
1230       uint32_t NLZ = DemandedMask.countLeadingZeros();
1231       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1232       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1233                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1234           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1235                                LHSKnownZero, LHSKnownOne, Depth+1))
1236         return I;
1237     }
1238     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1239     // the known zeros and ones.
1240     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1241     break;
1242   case Instruction::Shl:
1243     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1244       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1245       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1246       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1247                                RHSKnownZero, RHSKnownOne, Depth+1))
1248         return I;
1249       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1250       RHSKnownZero <<= ShiftAmt;
1251       RHSKnownOne  <<= ShiftAmt;
1252       // low bits known zero.
1253       if (ShiftAmt)
1254         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1255     }
1256     break;
1257   case Instruction::LShr:
1258     // For a logical shift right
1259     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1260       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1261       
1262       // Unsigned shift right.
1263       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1264       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1265                                RHSKnownZero, RHSKnownOne, Depth+1))
1266         return I;
1267       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1268       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1269       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1270       if (ShiftAmt) {
1271         // Compute the new bits that are at the top now.
1272         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1273         RHSKnownZero |= HighBits;  // high bits known zero.
1274       }
1275     }
1276     break;
1277   case Instruction::AShr:
1278     // If this is an arithmetic shift right and only the low-bit is set, we can
1279     // always convert this into a logical shr, even if the shift amount is
1280     // variable.  The low bit of the shift cannot be an input sign bit unless
1281     // the shift amount is >= the size of the datatype, which is undefined.
1282     if (DemandedMask == 1) {
1283       // Perform the logical shift right.
1284       Instruction *NewVal = BinaryOperator::CreateLShr(
1285                         I->getOperand(0), I->getOperand(1), I->getName());
1286       return InsertNewInstBefore(NewVal, *I);
1287     }    
1288
1289     // If the sign bit is the only bit demanded by this ashr, then there is no
1290     // need to do it, the shift doesn't change the high bit.
1291     if (DemandedMask.isSignBit())
1292       return I->getOperand(0);
1293     
1294     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1295       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1296       
1297       // Signed shift right.
1298       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1299       // If any of the "high bits" are demanded, we should set the sign bit as
1300       // demanded.
1301       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1302         DemandedMaskIn.set(BitWidth-1);
1303       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1304                                RHSKnownZero, RHSKnownOne, Depth+1))
1305         return I;
1306       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1307       // Compute the new bits that are at the top now.
1308       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1309       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1310       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1311         
1312       // Handle the sign bits.
1313       APInt SignBit(APInt::getSignBit(BitWidth));
1314       // Adjust to where it is now in the mask.
1315       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1316         
1317       // If the input sign bit is known to be zero, or if none of the top bits
1318       // are demanded, turn this into an unsigned shift right.
1319       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1320           (HighBits & ~DemandedMask) == HighBits) {
1321         // Perform the logical shift right.
1322         Instruction *NewVal = BinaryOperator::CreateLShr(
1323                           I->getOperand(0), SA, I->getName());
1324         return InsertNewInstBefore(NewVal, *I);
1325       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1326         RHSKnownOne |= HighBits;
1327       }
1328     }
1329     break;
1330   case Instruction::SRem:
1331     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1332       APInt RA = Rem->getValue().abs();
1333       if (RA.isPowerOf2()) {
1334         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1335           return I->getOperand(0);
1336
1337         APInt LowBits = RA - 1;
1338         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1339         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1340                                  LHSKnownZero, LHSKnownOne, Depth+1))
1341           return I;
1342
1343         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1344           LHSKnownZero |= ~LowBits;
1345
1346         KnownZero |= LHSKnownZero & DemandedMask;
1347
1348         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1349       }
1350     }
1351     break;
1352   case Instruction::URem: {
1353     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1354     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1355     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1356                              KnownZero2, KnownOne2, Depth+1) ||
1357         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1358                              KnownZero2, KnownOne2, Depth+1))
1359       return I;
1360
1361     unsigned Leaders = KnownZero2.countLeadingOnes();
1362     Leaders = std::max(Leaders,
1363                        KnownZero2.countLeadingOnes());
1364     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1365     break;
1366   }
1367   case Instruction::Call:
1368     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1369       switch (II->getIntrinsicID()) {
1370       default: break;
1371       case Intrinsic::bswap: {
1372         // If the only bits demanded come from one byte of the bswap result,
1373         // just shift the input byte into position to eliminate the bswap.
1374         unsigned NLZ = DemandedMask.countLeadingZeros();
1375         unsigned NTZ = DemandedMask.countTrailingZeros();
1376           
1377         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1378         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1379         // have 14 leading zeros, round to 8.
1380         NLZ &= ~7;
1381         NTZ &= ~7;
1382         // If we need exactly one byte, we can do this transformation.
1383         if (BitWidth-NLZ-NTZ == 8) {
1384           unsigned ResultBit = NTZ;
1385           unsigned InputBit = BitWidth-NTZ-8;
1386           
1387           // Replace this with either a left or right shift to get the byte into
1388           // the right place.
1389           Instruction *NewVal;
1390           if (InputBit > ResultBit)
1391             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1392                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1393           else
1394             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1395                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1396           NewVal->takeName(I);
1397           return InsertNewInstBefore(NewVal, *I);
1398         }
1399           
1400         // TODO: Could compute known zero/one bits based on the input.
1401         break;
1402       }
1403       }
1404     }
1405     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1406     break;
1407   }
1408   
1409   // If the client is only demanding bits that we know, return the known
1410   // constant.
1411   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1412     Constant *C = ConstantInt::get(RHSKnownOne);
1413     if (isa<PointerType>(V->getType()))
1414       C = ConstantExpr::getIntToPtr(C, V->getType());
1415     return C;
1416   }
1417   return false;
1418 }
1419
1420
1421 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1422 /// any number of elements. DemandedElts contains the set of elements that are
1423 /// actually used by the caller.  This method analyzes which elements of the
1424 /// operand are undef and returns that information in UndefElts.
1425 ///
1426 /// If the information about demanded elements can be used to simplify the
1427 /// operation, the operation is simplified, then the resultant value is
1428 /// returned.  This returns null if no change was made.
1429 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1430                                                 APInt& UndefElts,
1431                                                 unsigned Depth) {
1432   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1433   APInt EltMask(APInt::getAllOnesValue(VWidth));
1434   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1435
1436   if (isa<UndefValue>(V)) {
1437     // If the entire vector is undefined, just return this info.
1438     UndefElts = EltMask;
1439     return 0;
1440   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1441     UndefElts = EltMask;
1442     return UndefValue::get(V->getType());
1443   }
1444
1445   UndefElts = 0;
1446   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1447     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1448     Constant *Undef = UndefValue::get(EltTy);
1449
1450     std::vector<Constant*> Elts;
1451     for (unsigned i = 0; i != VWidth; ++i)
1452       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1453         Elts.push_back(Undef);
1454         UndefElts.set(i);
1455       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1456         Elts.push_back(Undef);
1457         UndefElts.set(i);
1458       } else {                               // Otherwise, defined.
1459         Elts.push_back(CP->getOperand(i));
1460       }
1461
1462     // If we changed the constant, return it.
1463     Constant *NewCP = ConstantVector::get(Elts);
1464     return NewCP != CP ? NewCP : 0;
1465   } else if (isa<ConstantAggregateZero>(V)) {
1466     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1467     // set to undef.
1468     
1469     // Check if this is identity. If so, return 0 since we are not simplifying
1470     // anything.
1471     if (DemandedElts == ((1ULL << VWidth) -1))
1472       return 0;
1473     
1474     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1475     Constant *Zero = Constant::getNullValue(EltTy);
1476     Constant *Undef = UndefValue::get(EltTy);
1477     std::vector<Constant*> Elts;
1478     for (unsigned i = 0; i != VWidth; ++i) {
1479       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1480       Elts.push_back(Elt);
1481     }
1482     UndefElts = DemandedElts ^ EltMask;
1483     return ConstantVector::get(Elts);
1484   }
1485   
1486   // Limit search depth.
1487   if (Depth == 10)
1488     return 0;
1489
1490   // If multiple users are using the root value, procede with
1491   // simplification conservatively assuming that all elements
1492   // are needed.
1493   if (!V->hasOneUse()) {
1494     // Quit if we find multiple users of a non-root value though.
1495     // They'll be handled when it's their turn to be visited by
1496     // the main instcombine process.
1497     if (Depth != 0)
1498       // TODO: Just compute the UndefElts information recursively.
1499       return 0;
1500
1501     // Conservatively assume that all elements are needed.
1502     DemandedElts = EltMask;
1503   }
1504   
1505   Instruction *I = dyn_cast<Instruction>(V);
1506   if (!I) return 0;        // Only analyze instructions.
1507   
1508   bool MadeChange = false;
1509   APInt UndefElts2(VWidth, 0);
1510   Value *TmpV;
1511   switch (I->getOpcode()) {
1512   default: break;
1513     
1514   case Instruction::InsertElement: {
1515     // If this is a variable index, we don't know which element it overwrites.
1516     // demand exactly the same input as we produce.
1517     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1518     if (Idx == 0) {
1519       // Note that we can't propagate undef elt info, because we don't know
1520       // which elt is getting updated.
1521       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1522                                         UndefElts2, Depth+1);
1523       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1524       break;
1525     }
1526     
1527     // If this is inserting an element that isn't demanded, remove this
1528     // insertelement.
1529     unsigned IdxNo = Idx->getZExtValue();
1530     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1531       return AddSoonDeadInstToWorklist(*I, 0);
1532     
1533     // Otherwise, the element inserted overwrites whatever was there, so the
1534     // input demanded set is simpler than the output set.
1535     APInt DemandedElts2 = DemandedElts;
1536     DemandedElts2.clear(IdxNo);
1537     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1538                                       UndefElts, Depth+1);
1539     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1540
1541     // The inserted element is defined.
1542     UndefElts.clear(IdxNo);
1543     break;
1544   }
1545   case Instruction::ShuffleVector: {
1546     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1547     uint64_t LHSVWidth =
1548       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1549     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1550     for (unsigned i = 0; i < VWidth; i++) {
1551       if (DemandedElts[i]) {
1552         unsigned MaskVal = Shuffle->getMaskValue(i);
1553         if (MaskVal != -1u) {
1554           assert(MaskVal < LHSVWidth * 2 &&
1555                  "shufflevector mask index out of range!");
1556           if (MaskVal < LHSVWidth)
1557             LeftDemanded.set(MaskVal);
1558           else
1559             RightDemanded.set(MaskVal - LHSVWidth);
1560         }
1561       }
1562     }
1563
1564     APInt UndefElts4(LHSVWidth, 0);
1565     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1566                                       UndefElts4, Depth+1);
1567     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1568
1569     APInt UndefElts3(LHSVWidth, 0);
1570     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1571                                       UndefElts3, Depth+1);
1572     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1573
1574     bool NewUndefElts = false;
1575     for (unsigned i = 0; i < VWidth; i++) {
1576       unsigned MaskVal = Shuffle->getMaskValue(i);
1577       if (MaskVal == -1u) {
1578         UndefElts.set(i);
1579       } else if (MaskVal < LHSVWidth) {
1580         if (UndefElts4[MaskVal]) {
1581           NewUndefElts = true;
1582           UndefElts.set(i);
1583         }
1584       } else {
1585         if (UndefElts3[MaskVal - LHSVWidth]) {
1586           NewUndefElts = true;
1587           UndefElts.set(i);
1588         }
1589       }
1590     }
1591
1592     if (NewUndefElts) {
1593       // Add additional discovered undefs.
1594       std::vector<Constant*> Elts;
1595       for (unsigned i = 0; i < VWidth; ++i) {
1596         if (UndefElts[i])
1597           Elts.push_back(UndefValue::get(Type::Int32Ty));
1598         else
1599           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1600                                           Shuffle->getMaskValue(i)));
1601       }
1602       I->setOperand(2, ConstantVector::get(Elts));
1603       MadeChange = true;
1604     }
1605     break;
1606   }
1607   case Instruction::BitCast: {
1608     // Vector->vector casts only.
1609     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1610     if (!VTy) break;
1611     unsigned InVWidth = VTy->getNumElements();
1612     APInt InputDemandedElts(InVWidth, 0);
1613     unsigned Ratio;
1614
1615     if (VWidth == InVWidth) {
1616       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1617       // elements as are demanded of us.
1618       Ratio = 1;
1619       InputDemandedElts = DemandedElts;
1620     } else if (VWidth > InVWidth) {
1621       // Untested so far.
1622       break;
1623       
1624       // If there are more elements in the result than there are in the source,
1625       // then an input element is live if any of the corresponding output
1626       // elements are live.
1627       Ratio = VWidth/InVWidth;
1628       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1629         if (DemandedElts[OutIdx])
1630           InputDemandedElts.set(OutIdx/Ratio);
1631       }
1632     } else {
1633       // Untested so far.
1634       break;
1635       
1636       // If there are more elements in the source than there are in the result,
1637       // then an input element is live if the corresponding output element is
1638       // live.
1639       Ratio = InVWidth/VWidth;
1640       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1641         if (DemandedElts[InIdx/Ratio])
1642           InputDemandedElts.set(InIdx);
1643     }
1644     
1645     // div/rem demand all inputs, because they don't want divide by zero.
1646     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1647                                       UndefElts2, Depth+1);
1648     if (TmpV) {
1649       I->setOperand(0, TmpV);
1650       MadeChange = true;
1651     }
1652     
1653     UndefElts = UndefElts2;
1654     if (VWidth > InVWidth) {
1655       assert(0 && "Unimp");
1656       // If there are more elements in the result than there are in the source,
1657       // then an output element is undef if the corresponding input element is
1658       // undef.
1659       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1660         if (UndefElts2[OutIdx/Ratio])
1661           UndefElts.set(OutIdx);
1662     } else if (VWidth < InVWidth) {
1663       assert(0 && "Unimp");
1664       // If there are more elements in the source than there are in the result,
1665       // then a result element is undef if all of the corresponding input
1666       // elements are undef.
1667       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1668       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1669         if (!UndefElts2[InIdx])            // Not undef?
1670           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1671     }
1672     break;
1673   }
1674   case Instruction::And:
1675   case Instruction::Or:
1676   case Instruction::Xor:
1677   case Instruction::Add:
1678   case Instruction::Sub:
1679   case Instruction::Mul:
1680     // div/rem demand all inputs, because they don't want divide by zero.
1681     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1682                                       UndefElts, Depth+1);
1683     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1684     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1685                                       UndefElts2, Depth+1);
1686     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1687       
1688     // Output elements are undefined if both are undefined.  Consider things
1689     // like undef&0.  The result is known zero, not undef.
1690     UndefElts &= UndefElts2;
1691     break;
1692     
1693   case Instruction::Call: {
1694     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1695     if (!II) break;
1696     switch (II->getIntrinsicID()) {
1697     default: break;
1698       
1699     // Binary vector operations that work column-wise.  A dest element is a
1700     // function of the corresponding input elements from the two inputs.
1701     case Intrinsic::x86_sse_sub_ss:
1702     case Intrinsic::x86_sse_mul_ss:
1703     case Intrinsic::x86_sse_min_ss:
1704     case Intrinsic::x86_sse_max_ss:
1705     case Intrinsic::x86_sse2_sub_sd:
1706     case Intrinsic::x86_sse2_mul_sd:
1707     case Intrinsic::x86_sse2_min_sd:
1708     case Intrinsic::x86_sse2_max_sd:
1709       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1710                                         UndefElts, Depth+1);
1711       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1712       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1713                                         UndefElts2, Depth+1);
1714       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1715
1716       // If only the low elt is demanded and this is a scalarizable intrinsic,
1717       // scalarize it now.
1718       if (DemandedElts == 1) {
1719         switch (II->getIntrinsicID()) {
1720         default: break;
1721         case Intrinsic::x86_sse_sub_ss:
1722         case Intrinsic::x86_sse_mul_ss:
1723         case Intrinsic::x86_sse2_sub_sd:
1724         case Intrinsic::x86_sse2_mul_sd:
1725           // TODO: Lower MIN/MAX/ABS/etc
1726           Value *LHS = II->getOperand(1);
1727           Value *RHS = II->getOperand(2);
1728           // Extract the element as scalars.
1729           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1730           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1731           
1732           switch (II->getIntrinsicID()) {
1733           default: assert(0 && "Case stmts out of sync!");
1734           case Intrinsic::x86_sse_sub_ss:
1735           case Intrinsic::x86_sse2_sub_sd:
1736             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1737                                                         II->getName()), *II);
1738             break;
1739           case Intrinsic::x86_sse_mul_ss:
1740           case Intrinsic::x86_sse2_mul_sd:
1741             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1742                                                          II->getName()), *II);
1743             break;
1744           }
1745           
1746           Instruction *New =
1747             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1748                                       II->getName());
1749           InsertNewInstBefore(New, *II);
1750           AddSoonDeadInstToWorklist(*II, 0);
1751           return New;
1752         }            
1753       }
1754         
1755       // Output elements are undefined if both are undefined.  Consider things
1756       // like undef&0.  The result is known zero, not undef.
1757       UndefElts &= UndefElts2;
1758       break;
1759     }
1760     break;
1761   }
1762   }
1763   return MadeChange ? I : 0;
1764 }
1765
1766
1767 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1768 /// function is designed to check a chain of associative operators for a
1769 /// potential to apply a certain optimization.  Since the optimization may be
1770 /// applicable if the expression was reassociated, this checks the chain, then
1771 /// reassociates the expression as necessary to expose the optimization
1772 /// opportunity.  This makes use of a special Functor, which must define
1773 /// 'shouldApply' and 'apply' methods.
1774 ///
1775 template<typename Functor>
1776 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1777   unsigned Opcode = Root.getOpcode();
1778   Value *LHS = Root.getOperand(0);
1779
1780   // Quick check, see if the immediate LHS matches...
1781   if (F.shouldApply(LHS))
1782     return F.apply(Root);
1783
1784   // Otherwise, if the LHS is not of the same opcode as the root, return.
1785   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1786   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1787     // Should we apply this transform to the RHS?
1788     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1789
1790     // If not to the RHS, check to see if we should apply to the LHS...
1791     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1792       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1793       ShouldApply = true;
1794     }
1795
1796     // If the functor wants to apply the optimization to the RHS of LHSI,
1797     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1798     if (ShouldApply) {
1799       // Now all of the instructions are in the current basic block, go ahead
1800       // and perform the reassociation.
1801       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1802
1803       // First move the selected RHS to the LHS of the root...
1804       Root.setOperand(0, LHSI->getOperand(1));
1805
1806       // Make what used to be the LHS of the root be the user of the root...
1807       Value *ExtraOperand = TmpLHSI->getOperand(1);
1808       if (&Root == TmpLHSI) {
1809         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1810         return 0;
1811       }
1812       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1813       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1814       BasicBlock::iterator ARI = &Root; ++ARI;
1815       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1816       ARI = Root;
1817
1818       // Now propagate the ExtraOperand down the chain of instructions until we
1819       // get to LHSI.
1820       while (TmpLHSI != LHSI) {
1821         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1822         // Move the instruction to immediately before the chain we are
1823         // constructing to avoid breaking dominance properties.
1824         NextLHSI->moveBefore(ARI);
1825         ARI = NextLHSI;
1826
1827         Value *NextOp = NextLHSI->getOperand(1);
1828         NextLHSI->setOperand(1, ExtraOperand);
1829         TmpLHSI = NextLHSI;
1830         ExtraOperand = NextOp;
1831       }
1832
1833       // Now that the instructions are reassociated, have the functor perform
1834       // the transformation...
1835       return F.apply(Root);
1836     }
1837
1838     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1839   }
1840   return 0;
1841 }
1842
1843 namespace {
1844
1845 // AddRHS - Implements: X + X --> X << 1
1846 struct AddRHS {
1847   Value *RHS;
1848   AddRHS(Value *rhs) : RHS(rhs) {}
1849   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1850   Instruction *apply(BinaryOperator &Add) const {
1851     return BinaryOperator::CreateShl(Add.getOperand(0),
1852                                      ConstantInt::get(Add.getType(), 1));
1853   }
1854 };
1855
1856 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1857 //                 iff C1&C2 == 0
1858 struct AddMaskingAnd {
1859   Constant *C2;
1860   AddMaskingAnd(Constant *c) : C2(c) {}
1861   bool shouldApply(Value *LHS) const {
1862     ConstantInt *C1;
1863     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1864            ConstantExpr::getAnd(C1, C2)->isNullValue();
1865   }
1866   Instruction *apply(BinaryOperator &Add) const {
1867     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1868   }
1869 };
1870
1871 }
1872
1873 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1874                                              InstCombiner *IC) {
1875   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1876     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1877   }
1878
1879   // Figure out if the constant is the left or the right argument.
1880   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1881   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1882
1883   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1884     if (ConstIsRHS)
1885       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1886     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1887   }
1888
1889   Value *Op0 = SO, *Op1 = ConstOperand;
1890   if (!ConstIsRHS)
1891     std::swap(Op0, Op1);
1892   Instruction *New;
1893   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1894     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1895   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1896     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1897                           SO->getName()+".cmp");
1898   else {
1899     assert(0 && "Unknown binary instruction type!");
1900     abort();
1901   }
1902   return IC->InsertNewInstBefore(New, I);
1903 }
1904
1905 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1906 // constant as the other operand, try to fold the binary operator into the
1907 // select arguments.  This also works for Cast instructions, which obviously do
1908 // not have a second operand.
1909 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1910                                      InstCombiner *IC) {
1911   // Don't modify shared select instructions
1912   if (!SI->hasOneUse()) return 0;
1913   Value *TV = SI->getOperand(1);
1914   Value *FV = SI->getOperand(2);
1915
1916   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1917     // Bool selects with constant operands can be folded to logical ops.
1918     if (SI->getType() == Type::Int1Ty) return 0;
1919
1920     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1921     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1922
1923     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1924                               SelectFalseVal);
1925   }
1926   return 0;
1927 }
1928
1929
1930 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1931 /// node as operand #0, see if we can fold the instruction into the PHI (which
1932 /// is only possible if all operands to the PHI are constants).
1933 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1934   PHINode *PN = cast<PHINode>(I.getOperand(0));
1935   unsigned NumPHIValues = PN->getNumIncomingValues();
1936   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1937
1938   // Check to see if all of the operands of the PHI are constants.  If there is
1939   // one non-constant value, remember the BB it is.  If there is more than one
1940   // or if *it* is a PHI, bail out.
1941   BasicBlock *NonConstBB = 0;
1942   for (unsigned i = 0; i != NumPHIValues; ++i)
1943     if (!isa<Constant>(PN->getIncomingValue(i))) {
1944       if (NonConstBB) return 0;  // More than one non-const value.
1945       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1946       NonConstBB = PN->getIncomingBlock(i);
1947       
1948       // If the incoming non-constant value is in I's block, we have an infinite
1949       // loop.
1950       if (NonConstBB == I.getParent())
1951         return 0;
1952     }
1953   
1954   // If there is exactly one non-constant value, we can insert a copy of the
1955   // operation in that block.  However, if this is a critical edge, we would be
1956   // inserting the computation one some other paths (e.g. inside a loop).  Only
1957   // do this if the pred block is unconditionally branching into the phi block.
1958   if (NonConstBB) {
1959     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1960     if (!BI || !BI->isUnconditional()) return 0;
1961   }
1962
1963   // Okay, we can do the transformation: create the new PHI node.
1964   PHINode *NewPN = PHINode::Create(I.getType(), "");
1965   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1966   InsertNewInstBefore(NewPN, *PN);
1967   NewPN->takeName(PN);
1968
1969   // Next, add all of the operands to the PHI.
1970   if (I.getNumOperands() == 2) {
1971     Constant *C = cast<Constant>(I.getOperand(1));
1972     for (unsigned i = 0; i != NumPHIValues; ++i) {
1973       Value *InV = 0;
1974       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1975         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1976           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1977         else
1978           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1979       } else {
1980         assert(PN->getIncomingBlock(i) == NonConstBB);
1981         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1982           InV = BinaryOperator::Create(BO->getOpcode(),
1983                                        PN->getIncomingValue(i), C, "phitmp",
1984                                        NonConstBB->getTerminator());
1985         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1986           InV = CmpInst::Create(CI->getOpcode(), 
1987                                 CI->getPredicate(),
1988                                 PN->getIncomingValue(i), C, "phitmp",
1989                                 NonConstBB->getTerminator());
1990         else
1991           assert(0 && "Unknown binop!");
1992         
1993         AddToWorkList(cast<Instruction>(InV));
1994       }
1995       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1996     }
1997   } else { 
1998     CastInst *CI = cast<CastInst>(&I);
1999     const Type *RetTy = CI->getType();
2000     for (unsigned i = 0; i != NumPHIValues; ++i) {
2001       Value *InV;
2002       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2003         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2004       } else {
2005         assert(PN->getIncomingBlock(i) == NonConstBB);
2006         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2007                                I.getType(), "phitmp", 
2008                                NonConstBB->getTerminator());
2009         AddToWorkList(cast<Instruction>(InV));
2010       }
2011       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2012     }
2013   }
2014   return ReplaceInstUsesWith(I, NewPN);
2015 }
2016
2017
2018 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2019 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2020 /// This basically requires proving that the add in the original type would not
2021 /// overflow to change the sign bit or have a carry out.
2022 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2023   // There are different heuristics we can use for this.  Here are some simple
2024   // ones.
2025   
2026   // Add has the property that adding any two 2's complement numbers can only 
2027   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2028   // have at least two sign bits, we know that the addition of the two values will
2029   // sign extend fine.
2030   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2031     return true;
2032   
2033   
2034   // If one of the operands only has one non-zero bit, and if the other operand
2035   // has a known-zero bit in a more significant place than it (not including the
2036   // sign bit) the ripple may go up to and fill the zero, but won't change the
2037   // sign.  For example, (X & ~4) + 1.
2038   
2039   // TODO: Implement.
2040   
2041   return false;
2042 }
2043
2044
2045 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2046   bool Changed = SimplifyCommutative(I);
2047   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2048
2049   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2050     // X + undef -> undef
2051     if (isa<UndefValue>(RHS))
2052       return ReplaceInstUsesWith(I, RHS);
2053
2054     // X + 0 --> X
2055     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2056       if (RHSC->isNullValue())
2057         return ReplaceInstUsesWith(I, LHS);
2058     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2059       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2060                               (I.getType())->getValueAPF()))
2061         return ReplaceInstUsesWith(I, LHS);
2062     }
2063
2064     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2065       // X + (signbit) --> X ^ signbit
2066       const APInt& Val = CI->getValue();
2067       uint32_t BitWidth = Val.getBitWidth();
2068       if (Val == APInt::getSignBit(BitWidth))
2069         return BinaryOperator::CreateXor(LHS, RHS);
2070       
2071       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2072       // (X & 254)+1 -> (X&254)|1
2073       if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
2074         return &I;
2075
2076       // zext(i1) - 1  ->  select i1, 0, -1
2077       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2078         if (CI->isAllOnesValue() &&
2079             ZI->getOperand(0)->getType() == Type::Int1Ty)
2080           return SelectInst::Create(ZI->getOperand(0),
2081                                     Constant::getNullValue(I.getType()),
2082                                     ConstantInt::getAllOnesValue(I.getType()));
2083     }
2084
2085     if (isa<PHINode>(LHS))
2086       if (Instruction *NV = FoldOpIntoPhi(I))
2087         return NV;
2088     
2089     ConstantInt *XorRHS = 0;
2090     Value *XorLHS = 0;
2091     if (isa<ConstantInt>(RHSC) &&
2092         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2093       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2094       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2095       
2096       uint32_t Size = TySizeBits / 2;
2097       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2098       APInt CFF80Val(-C0080Val);
2099       do {
2100         if (TySizeBits > Size) {
2101           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2102           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2103           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2104               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2105             // This is a sign extend if the top bits are known zero.
2106             if (!MaskedValueIsZero(XorLHS, 
2107                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2108               Size = 0;  // Not a sign ext, but can't be any others either.
2109             break;
2110           }
2111         }
2112         Size >>= 1;
2113         C0080Val = APIntOps::lshr(C0080Val, Size);
2114         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2115       } while (Size >= 1);
2116       
2117       // FIXME: This shouldn't be necessary. When the backends can handle types
2118       // with funny bit widths then this switch statement should be removed. It
2119       // is just here to get the size of the "middle" type back up to something
2120       // that the back ends can handle.
2121       const Type *MiddleType = 0;
2122       switch (Size) {
2123         default: break;
2124         case 32: MiddleType = Type::Int32Ty; break;
2125         case 16: MiddleType = Type::Int16Ty; break;
2126         case  8: MiddleType = Type::Int8Ty; break;
2127       }
2128       if (MiddleType) {
2129         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2130         InsertNewInstBefore(NewTrunc, I);
2131         return new SExtInst(NewTrunc, I.getType(), I.getName());
2132       }
2133     }
2134   }
2135
2136   if (I.getType() == Type::Int1Ty)
2137     return BinaryOperator::CreateXor(LHS, RHS);
2138
2139   // X + X --> X << 1
2140   if (I.getType()->isInteger()) {
2141     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2142
2143     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2144       if (RHSI->getOpcode() == Instruction::Sub)
2145         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2146           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2147     }
2148     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2149       if (LHSI->getOpcode() == Instruction::Sub)
2150         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2151           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2152     }
2153   }
2154
2155   // -A + B  -->  B - A
2156   // -A + -B  -->  -(A + B)
2157   if (Value *LHSV = dyn_castNegVal(LHS)) {
2158     if (LHS->getType()->isIntOrIntVector()) {
2159       if (Value *RHSV = dyn_castNegVal(RHS)) {
2160         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2161         InsertNewInstBefore(NewAdd, I);
2162         return BinaryOperator::CreateNeg(NewAdd);
2163       }
2164     }
2165     
2166     return BinaryOperator::CreateSub(RHS, LHSV);
2167   }
2168
2169   // A + -B  -->  A - B
2170   if (!isa<Constant>(RHS))
2171     if (Value *V = dyn_castNegVal(RHS))
2172       return BinaryOperator::CreateSub(LHS, V);
2173
2174
2175   ConstantInt *C2;
2176   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2177     if (X == RHS)   // X*C + X --> X * (C+1)
2178       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2179
2180     // X*C1 + X*C2 --> X * (C1+C2)
2181     ConstantInt *C1;
2182     if (X == dyn_castFoldableMul(RHS, C1))
2183       return BinaryOperator::CreateMul(X, Add(C1, C2));
2184   }
2185
2186   // X + X*C --> X * (C+1)
2187   if (dyn_castFoldableMul(RHS, C2) == LHS)
2188     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2189
2190   // X + ~X --> -1   since   ~X = -X-1
2191   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2192     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2193   
2194
2195   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2196   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2197     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2198       return R;
2199   
2200   // A+B --> A|B iff A and B have no bits set in common.
2201   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2202     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2203     APInt LHSKnownOne(IT->getBitWidth(), 0);
2204     APInt LHSKnownZero(IT->getBitWidth(), 0);
2205     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2206     if (LHSKnownZero != 0) {
2207       APInt RHSKnownOne(IT->getBitWidth(), 0);
2208       APInt RHSKnownZero(IT->getBitWidth(), 0);
2209       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2210       
2211       // No bits in common -> bitwise or.
2212       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2213         return BinaryOperator::CreateOr(LHS, RHS);
2214     }
2215   }
2216
2217   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2218   if (I.getType()->isIntOrIntVector()) {
2219     Value *W, *X, *Y, *Z;
2220     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2221         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2222       if (W != Y) {
2223         if (W == Z) {
2224           std::swap(Y, Z);
2225         } else if (Y == X) {
2226           std::swap(W, X);
2227         } else if (X == Z) {
2228           std::swap(Y, Z);
2229           std::swap(W, X);
2230         }
2231       }
2232
2233       if (W == Y) {
2234         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2235                                                             LHS->getName()), I);
2236         return BinaryOperator::CreateMul(W, NewAdd);
2237       }
2238     }
2239   }
2240
2241   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2242     Value *X = 0;
2243     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2244       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2245
2246     // (X & FF00) + xx00  -> (X+xx00) & FF00
2247     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2248       Constant *Anded = And(CRHS, C2);
2249       if (Anded == CRHS) {
2250         // See if all bits from the first bit set in the Add RHS up are included
2251         // in the mask.  First, get the rightmost bit.
2252         const APInt& AddRHSV = CRHS->getValue();
2253
2254         // Form a mask of all bits from the lowest bit added through the top.
2255         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2256
2257         // See if the and mask includes all of these bits.
2258         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2259
2260         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2261           // Okay, the xform is safe.  Insert the new add pronto.
2262           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2263                                                             LHS->getName()), I);
2264           return BinaryOperator::CreateAnd(NewAdd, C2);
2265         }
2266       }
2267     }
2268
2269     // Try to fold constant add into select arguments.
2270     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2271       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2272         return R;
2273   }
2274
2275   // add (cast *A to intptrtype) B -> 
2276   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2277   {
2278     CastInst *CI = dyn_cast<CastInst>(LHS);
2279     Value *Other = RHS;
2280     if (!CI) {
2281       CI = dyn_cast<CastInst>(RHS);
2282       Other = LHS;
2283     }
2284     if (CI && CI->getType()->isSized() && 
2285         (CI->getType()->getPrimitiveSizeInBits() == 
2286          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2287         && isa<PointerType>(CI->getOperand(0)->getType())) {
2288       unsigned AS =
2289         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2290       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2291                                       PointerType::get(Type::Int8Ty, AS), I);
2292       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2293       return new PtrToIntInst(I2, CI->getType());
2294     }
2295   }
2296   
2297   // add (select X 0 (sub n A)) A  -->  select X A n
2298   {
2299     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2300     Value *A = RHS;
2301     if (!SI) {
2302       SI = dyn_cast<SelectInst>(RHS);
2303       A = LHS;
2304     }
2305     if (SI && SI->hasOneUse()) {
2306       Value *TV = SI->getTrueValue();
2307       Value *FV = SI->getFalseValue();
2308       Value *N;
2309
2310       // Can we fold the add into the argument of the select?
2311       // We check both true and false select arguments for a matching subtract.
2312       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2313         // Fold the add into the true select value.
2314         return SelectInst::Create(SI->getCondition(), N, A);
2315       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2316         // Fold the add into the false select value.
2317         return SelectInst::Create(SI->getCondition(), A, N);
2318     }
2319   }
2320   
2321   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2322   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2323     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2324       return ReplaceInstUsesWith(I, LHS);
2325
2326   // Check for (add (sext x), y), see if we can merge this into an
2327   // integer add followed by a sext.
2328   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2329     // (add (sext x), cst) --> (sext (add x, cst'))
2330     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2331       Constant *CI = 
2332         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2333       if (LHSConv->hasOneUse() &&
2334           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2335           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2336         // Insert the new, smaller add.
2337         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2338                                                         CI, "addconv");
2339         InsertNewInstBefore(NewAdd, I);
2340         return new SExtInst(NewAdd, I.getType());
2341       }
2342     }
2343     
2344     // (add (sext x), (sext y)) --> (sext (add int x, y))
2345     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2346       // Only do this if x/y have the same type, if at last one of them has a
2347       // single use (so we don't increase the number of sexts), and if the
2348       // integer add will not overflow.
2349       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2350           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2351           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2352                                    RHSConv->getOperand(0))) {
2353         // Insert the new integer add.
2354         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2355                                                         RHSConv->getOperand(0),
2356                                                         "addconv");
2357         InsertNewInstBefore(NewAdd, I);
2358         return new SExtInst(NewAdd, I.getType());
2359       }
2360     }
2361   }
2362   
2363   // Check for (add double (sitofp x), y), see if we can merge this into an
2364   // integer add followed by a promotion.
2365   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2366     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2367     // ... if the constant fits in the integer value.  This is useful for things
2368     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2369     // requires a constant pool load, and generally allows the add to be better
2370     // instcombined.
2371     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2372       Constant *CI = 
2373       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2374       if (LHSConv->hasOneUse() &&
2375           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2376           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2377         // Insert the new integer add.
2378         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2379                                                         CI, "addconv");
2380         InsertNewInstBefore(NewAdd, I);
2381         return new SIToFPInst(NewAdd, I.getType());
2382       }
2383     }
2384     
2385     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2386     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2387       // Only do this if x/y have the same type, if at last one of them has a
2388       // single use (so we don't increase the number of int->fp conversions),
2389       // and if the integer add will not overflow.
2390       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2391           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2392           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2393                                    RHSConv->getOperand(0))) {
2394         // Insert the new integer add.
2395         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2396                                                         RHSConv->getOperand(0),
2397                                                         "addconv");
2398         InsertNewInstBefore(NewAdd, I);
2399         return new SIToFPInst(NewAdd, I.getType());
2400       }
2401     }
2402   }
2403   
2404   return Changed ? &I : 0;
2405 }
2406
2407 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2408   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2409
2410   if (Op0 == Op1 &&                        // sub X, X  -> 0
2411       !I.getType()->isFPOrFPVector())
2412     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2413
2414   // If this is a 'B = x-(-A)', change to B = x+A...
2415   if (Value *V = dyn_castNegVal(Op1))
2416     return BinaryOperator::CreateAdd(Op0, V);
2417
2418   if (isa<UndefValue>(Op0))
2419     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2420   if (isa<UndefValue>(Op1))
2421     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2422
2423   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2424     // Replace (-1 - A) with (~A)...
2425     if (C->isAllOnesValue())
2426       return BinaryOperator::CreateNot(Op1);
2427
2428     // C - ~X == X + (1+C)
2429     Value *X = 0;
2430     if (match(Op1, m_Not(m_Value(X))))
2431       return BinaryOperator::CreateAdd(X, AddOne(C));
2432
2433     // -(X >>u 31) -> (X >>s 31)
2434     // -(X >>s 31) -> (X >>u 31)
2435     if (C->isZero()) {
2436       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2437         if (SI->getOpcode() == Instruction::LShr) {
2438           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2439             // Check to see if we are shifting out everything but the sign bit.
2440             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2441                 SI->getType()->getPrimitiveSizeInBits()-1) {
2442               // Ok, the transformation is safe.  Insert AShr.
2443               return BinaryOperator::Create(Instruction::AShr, 
2444                                           SI->getOperand(0), CU, SI->getName());
2445             }
2446           }
2447         }
2448         else if (SI->getOpcode() == Instruction::AShr) {
2449           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2450             // Check to see if we are shifting out everything but the sign bit.
2451             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2452                 SI->getType()->getPrimitiveSizeInBits()-1) {
2453               // Ok, the transformation is safe.  Insert LShr. 
2454               return BinaryOperator::CreateLShr(
2455                                           SI->getOperand(0), CU, SI->getName());
2456             }
2457           }
2458         }
2459       }
2460     }
2461
2462     // Try to fold constant sub into select arguments.
2463     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2464       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2465         return R;
2466   }
2467
2468   if (I.getType() == Type::Int1Ty)
2469     return BinaryOperator::CreateXor(Op0, Op1);
2470
2471   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2472     if (Op1I->getOpcode() == Instruction::Add &&
2473         !Op0->getType()->isFPOrFPVector()) {
2474       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2475         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2476       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2477         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2478       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2479         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2480           // C1-(X+C2) --> (C1-C2)-X
2481           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2482                                            Op1I->getOperand(0));
2483       }
2484     }
2485
2486     if (Op1I->hasOneUse()) {
2487       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2488       // is not used by anyone else...
2489       //
2490       if (Op1I->getOpcode() == Instruction::Sub &&
2491           !Op1I->getType()->isFPOrFPVector()) {
2492         // Swap the two operands of the subexpr...
2493         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2494         Op1I->setOperand(0, IIOp1);
2495         Op1I->setOperand(1, IIOp0);
2496
2497         // Create the new top level add instruction...
2498         return BinaryOperator::CreateAdd(Op0, Op1);
2499       }
2500
2501       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2502       //
2503       if (Op1I->getOpcode() == Instruction::And &&
2504           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2505         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2506
2507         Value *NewNot =
2508           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2509         return BinaryOperator::CreateAnd(Op0, NewNot);
2510       }
2511
2512       // 0 - (X sdiv C)  -> (X sdiv -C)
2513       if (Op1I->getOpcode() == Instruction::SDiv)
2514         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2515           if (CSI->isZero())
2516             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2517               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2518                                                ConstantExpr::getNeg(DivRHS));
2519
2520       // X - X*C --> X * (1-C)
2521       ConstantInt *C2 = 0;
2522       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2523         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2524         return BinaryOperator::CreateMul(Op0, CP1);
2525       }
2526     }
2527   }
2528
2529   if (!Op0->getType()->isFPOrFPVector())
2530     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2531       if (Op0I->getOpcode() == Instruction::Add) {
2532         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2533           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2534         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2535           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2536       } else if (Op0I->getOpcode() == Instruction::Sub) {
2537         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2538           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2539       }
2540     }
2541
2542   ConstantInt *C1;
2543   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2544     if (X == Op1)  // X*C - X --> X * (C-1)
2545       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2546
2547     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2548     if (X == dyn_castFoldableMul(Op1, C2))
2549       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2550   }
2551   return 0;
2552 }
2553
2554 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2555 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2556 /// TrueIfSigned if the result of the comparison is true when the input value is
2557 /// signed.
2558 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2559                            bool &TrueIfSigned) {
2560   switch (pred) {
2561   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2562     TrueIfSigned = true;
2563     return RHS->isZero();
2564   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2565     TrueIfSigned = true;
2566     return RHS->isAllOnesValue();
2567   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2568     TrueIfSigned = false;
2569     return RHS->isAllOnesValue();
2570   case ICmpInst::ICMP_UGT:
2571     // True if LHS u> RHS and RHS == high-bit-mask - 1
2572     TrueIfSigned = true;
2573     return RHS->getValue() ==
2574       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2575   case ICmpInst::ICMP_UGE: 
2576     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2577     TrueIfSigned = true;
2578     return RHS->getValue().isSignBit();
2579   default:
2580     return false;
2581   }
2582 }
2583
2584 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2585   bool Changed = SimplifyCommutative(I);
2586   Value *Op0 = I.getOperand(0);
2587
2588   // TODO: If Op1 is undef and Op0 is finite, return zero.
2589   if (!I.getType()->isFPOrFPVector() &&
2590       isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2591     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2592
2593   // Simplify mul instructions with a constant RHS...
2594   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2595     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2596
2597       // ((X << C1)*C2) == (X * (C2 << C1))
2598       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2599         if (SI->getOpcode() == Instruction::Shl)
2600           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2601             return BinaryOperator::CreateMul(SI->getOperand(0),
2602                                              ConstantExpr::getShl(CI, ShOp));
2603
2604       if (CI->isZero())
2605         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2606       if (CI->equalsInt(1))                  // X * 1  == X
2607         return ReplaceInstUsesWith(I, Op0);
2608       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2609         return BinaryOperator::CreateNeg(Op0, I.getName());
2610
2611       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2612       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2613         return BinaryOperator::CreateShl(Op0,
2614                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2615       }
2616     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2617       // TODO: If Op1 is zero and Op0 is finite, return zero.
2618
2619       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2620       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2621       if (Op1F->isExactlyValue(1.0))
2622         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2623     } else if (isa<VectorType>(Op1->getType())) {
2624       // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
2625
2626       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2627         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2628           return BinaryOperator::CreateNeg(Op0, I.getName());
2629
2630         // As above, vector X*splat(1.0) -> X in all defined cases.
2631         if (Constant *Splat = Op1V->getSplatValue()) {
2632           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2633             if (F->isExactlyValue(1.0))
2634               return ReplaceInstUsesWith(I, Op0);
2635           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2636             if (CI->equalsInt(1))
2637               return ReplaceInstUsesWith(I, Op0);
2638         }
2639       }
2640     }
2641     
2642     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2643       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2644           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2645         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2646         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2647                                                      Op1, "tmp");
2648         InsertNewInstBefore(Add, I);
2649         Value *C1C2 = ConstantExpr::getMul(Op1, 
2650                                            cast<Constant>(Op0I->getOperand(1)));
2651         return BinaryOperator::CreateAdd(Add, C1C2);
2652         
2653       }
2654
2655     // Try to fold constant mul into select arguments.
2656     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2657       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2658         return R;
2659
2660     if (isa<PHINode>(Op0))
2661       if (Instruction *NV = FoldOpIntoPhi(I))
2662         return NV;
2663   }
2664
2665   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2666     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2667       return BinaryOperator::CreateMul(Op0v, Op1v);
2668
2669   // (X / Y) *  Y = X - (X % Y)
2670   // (X / Y) * -Y = (X % Y) - X
2671   {
2672     Value *Op1 = I.getOperand(1);
2673     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2674     if (!BO ||
2675         (BO->getOpcode() != Instruction::UDiv && 
2676          BO->getOpcode() != Instruction::SDiv)) {
2677       Op1 = Op0;
2678       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2679     }
2680     Value *Neg = dyn_castNegVal(Op1);
2681     if (BO && BO->hasOneUse() &&
2682         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2683         (BO->getOpcode() == Instruction::UDiv ||
2684          BO->getOpcode() == Instruction::SDiv)) {
2685       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2686
2687       Instruction *Rem;
2688       if (BO->getOpcode() == Instruction::UDiv)
2689         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2690       else
2691         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2692
2693       InsertNewInstBefore(Rem, I);
2694       Rem->takeName(BO);
2695
2696       if (Op1BO == Op1)
2697         return BinaryOperator::CreateSub(Op0BO, Rem);
2698       else
2699         return BinaryOperator::CreateSub(Rem, Op0BO);
2700     }
2701   }
2702
2703   if (I.getType() == Type::Int1Ty)
2704     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2705
2706   // If one of the operands of the multiply is a cast from a boolean value, then
2707   // we know the bool is either zero or one, so this is a 'masking' multiply.
2708   // See if we can simplify things based on how the boolean was originally
2709   // formed.
2710   CastInst *BoolCast = 0;
2711   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2712     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2713       BoolCast = CI;
2714   if (!BoolCast)
2715     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2716       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2717         BoolCast = CI;
2718   if (BoolCast) {
2719     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2720       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2721       const Type *SCOpTy = SCIOp0->getType();
2722       bool TIS = false;
2723       
2724       // If the icmp is true iff the sign bit of X is set, then convert this
2725       // multiply into a shift/and combination.
2726       if (isa<ConstantInt>(SCIOp1) &&
2727           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2728           TIS) {
2729         // Shift the X value right to turn it into "all signbits".
2730         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2731                                           SCOpTy->getPrimitiveSizeInBits()-1);
2732         Value *V =
2733           InsertNewInstBefore(
2734             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2735                                             BoolCast->getOperand(0)->getName()+
2736                                             ".mask"), I);
2737
2738         // If the multiply type is not the same as the source type, sign extend
2739         // or truncate to the multiply type.
2740         if (I.getType() != V->getType()) {
2741           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2742           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2743           Instruction::CastOps opcode = 
2744             (SrcBits == DstBits ? Instruction::BitCast : 
2745              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2746           V = InsertCastBefore(opcode, V, I.getType(), I);
2747         }
2748
2749         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2750         return BinaryOperator::CreateAnd(V, OtherOp);
2751       }
2752     }
2753   }
2754
2755   return Changed ? &I : 0;
2756 }
2757
2758 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2759 /// instruction.
2760 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2761   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2762   
2763   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2764   int NonNullOperand = -1;
2765   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2766     if (ST->isNullValue())
2767       NonNullOperand = 2;
2768   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2769   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2770     if (ST->isNullValue())
2771       NonNullOperand = 1;
2772   
2773   if (NonNullOperand == -1)
2774     return false;
2775   
2776   Value *SelectCond = SI->getOperand(0);
2777   
2778   // Change the div/rem to use 'Y' instead of the select.
2779   I.setOperand(1, SI->getOperand(NonNullOperand));
2780   
2781   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2782   // problem.  However, the select, or the condition of the select may have
2783   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2784   // propagate the known value for the select into other uses of it, and
2785   // propagate a known value of the condition into its other users.
2786   
2787   // If the select and condition only have a single use, don't bother with this,
2788   // early exit.
2789   if (SI->use_empty() && SelectCond->hasOneUse())
2790     return true;
2791   
2792   // Scan the current block backward, looking for other uses of SI.
2793   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2794   
2795   while (BBI != BBFront) {
2796     --BBI;
2797     // If we found a call to a function, we can't assume it will return, so
2798     // information from below it cannot be propagated above it.
2799     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2800       break;
2801     
2802     // Replace uses of the select or its condition with the known values.
2803     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2804          I != E; ++I) {
2805       if (*I == SI) {
2806         *I = SI->getOperand(NonNullOperand);
2807         AddToWorkList(BBI);
2808       } else if (*I == SelectCond) {
2809         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2810                                    ConstantInt::getFalse();
2811         AddToWorkList(BBI);
2812       }
2813     }
2814     
2815     // If we past the instruction, quit looking for it.
2816     if (&*BBI == SI)
2817       SI = 0;
2818     if (&*BBI == SelectCond)
2819       SelectCond = 0;
2820     
2821     // If we ran out of things to eliminate, break out of the loop.
2822     if (SelectCond == 0 && SI == 0)
2823       break;
2824     
2825   }
2826   return true;
2827 }
2828
2829
2830 /// This function implements the transforms on div instructions that work
2831 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2832 /// used by the visitors to those instructions.
2833 /// @brief Transforms common to all three div instructions
2834 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2835   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2836
2837   // undef / X -> 0        for integer.
2838   // undef / X -> undef    for FP (the undef could be a snan).
2839   if (isa<UndefValue>(Op0)) {
2840     if (Op0->getType()->isFPOrFPVector())
2841       return ReplaceInstUsesWith(I, Op0);
2842     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2843   }
2844
2845   // X / undef -> undef
2846   if (isa<UndefValue>(Op1))
2847     return ReplaceInstUsesWith(I, Op1);
2848
2849   return 0;
2850 }
2851
2852 /// This function implements the transforms common to both integer division
2853 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2854 /// division instructions.
2855 /// @brief Common integer divide transforms
2856 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2857   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2858
2859   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2860   if (Op0 == Op1) {
2861     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2862       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2863       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2864       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2865     }
2866
2867     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2868     return ReplaceInstUsesWith(I, CI);
2869   }
2870   
2871   if (Instruction *Common = commonDivTransforms(I))
2872     return Common;
2873   
2874   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2875   // This does not apply for fdiv.
2876   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2877     return &I;
2878
2879   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2880     // div X, 1 == X
2881     if (RHS->equalsInt(1))
2882       return ReplaceInstUsesWith(I, Op0);
2883
2884     // (X / C1) / C2  -> X / (C1*C2)
2885     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2886       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2887         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2888           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2889             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2890           else 
2891             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2892                                           Multiply(RHS, LHSRHS));
2893         }
2894
2895     if (!RHS->isZero()) { // avoid X udiv 0
2896       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2897         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2898           return R;
2899       if (isa<PHINode>(Op0))
2900         if (Instruction *NV = FoldOpIntoPhi(I))
2901           return NV;
2902     }
2903   }
2904
2905   // 0 / X == 0, we don't need to preserve faults!
2906   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2907     if (LHS->equalsInt(0))
2908       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2909
2910   // It can't be division by zero, hence it must be division by one.
2911   if (I.getType() == Type::Int1Ty)
2912     return ReplaceInstUsesWith(I, Op0);
2913
2914   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2915     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2916       // div X, 1 == X
2917       if (X->isOne())
2918         return ReplaceInstUsesWith(I, Op0);
2919   }
2920
2921   return 0;
2922 }
2923
2924 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2925   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2926
2927   // Handle the integer div common cases
2928   if (Instruction *Common = commonIDivTransforms(I))
2929     return Common;
2930
2931   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2932     // X udiv C^2 -> X >> C
2933     // Check to see if this is an unsigned division with an exact power of 2,
2934     // if so, convert to a right shift.
2935     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2936       return BinaryOperator::CreateLShr(Op0, 
2937                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2938
2939     // X udiv C, where C >= signbit
2940     if (C->getValue().isNegative()) {
2941       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2942                                       I);
2943       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2944                                 ConstantInt::get(I.getType(), 1));
2945     }
2946   }
2947
2948   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2949   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2950     if (RHSI->getOpcode() == Instruction::Shl &&
2951         isa<ConstantInt>(RHSI->getOperand(0))) {
2952       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2953       if (C1.isPowerOf2()) {
2954         Value *N = RHSI->getOperand(1);
2955         const Type *NTy = N->getType();
2956         if (uint32_t C2 = C1.logBase2()) {
2957           Constant *C2V = ConstantInt::get(NTy, C2);
2958           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2959         }
2960         return BinaryOperator::CreateLShr(Op0, N);
2961       }
2962     }
2963   }
2964   
2965   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2966   // where C1&C2 are powers of two.
2967   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2968     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2969       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2970         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2971         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2972           // Compute the shift amounts
2973           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2974           // Construct the "on true" case of the select
2975           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2976           Instruction *TSI = BinaryOperator::CreateLShr(
2977                                                  Op0, TC, SI->getName()+".t");
2978           TSI = InsertNewInstBefore(TSI, I);
2979   
2980           // Construct the "on false" case of the select
2981           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2982           Instruction *FSI = BinaryOperator::CreateLShr(
2983                                                  Op0, FC, SI->getName()+".f");
2984           FSI = InsertNewInstBefore(FSI, I);
2985
2986           // construct the select instruction and return it.
2987           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2988         }
2989       }
2990   return 0;
2991 }
2992
2993 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2994   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2995
2996   // Handle the integer div common cases
2997   if (Instruction *Common = commonIDivTransforms(I))
2998     return Common;
2999
3000   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3001     // sdiv X, -1 == -X
3002     if (RHS->isAllOnesValue())
3003       return BinaryOperator::CreateNeg(Op0);
3004   }
3005
3006   // If the sign bits of both operands are zero (i.e. we can prove they are
3007   // unsigned inputs), turn this into a udiv.
3008   if (I.getType()->isInteger()) {
3009     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3010     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3011       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3012       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3013     }
3014   }      
3015   
3016   return 0;
3017 }
3018
3019 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3020   return commonDivTransforms(I);
3021 }
3022
3023 /// This function implements the transforms on rem instructions that work
3024 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3025 /// is used by the visitors to those instructions.
3026 /// @brief Transforms common to all three rem instructions
3027 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3028   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3029
3030   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3031     if (I.getType()->isFPOrFPVector())
3032       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3033     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3034   }
3035   if (isa<UndefValue>(Op1))
3036     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3037
3038   // Handle cases involving: rem X, (select Cond, Y, Z)
3039   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3040     return &I;
3041
3042   return 0;
3043 }
3044
3045 /// This function implements the transforms common to both integer remainder
3046 /// instructions (urem and srem). It is called by the visitors to those integer
3047 /// remainder instructions.
3048 /// @brief Common integer remainder transforms
3049 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3050   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3051
3052   if (Instruction *common = commonRemTransforms(I))
3053     return common;
3054
3055   // 0 % X == 0 for integer, we don't need to preserve faults!
3056   if (Constant *LHS = dyn_cast<Constant>(Op0))
3057     if (LHS->isNullValue())
3058       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3059
3060   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3061     // X % 0 == undef, we don't need to preserve faults!
3062     if (RHS->equalsInt(0))
3063       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3064     
3065     if (RHS->equalsInt(1))  // X % 1 == 0
3066       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3067
3068     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3069       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3070         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3071           return R;
3072       } else if (isa<PHINode>(Op0I)) {
3073         if (Instruction *NV = FoldOpIntoPhi(I))
3074           return NV;
3075       }
3076
3077       // See if we can fold away this rem instruction.
3078       if (SimplifyDemandedInstructionBits(I))
3079         return &I;
3080     }
3081   }
3082
3083   return 0;
3084 }
3085
3086 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3087   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3088
3089   if (Instruction *common = commonIRemTransforms(I))
3090     return common;
3091   
3092   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3093     // X urem C^2 -> X and C
3094     // Check to see if this is an unsigned remainder with an exact power of 2,
3095     // if so, convert to a bitwise and.
3096     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3097       if (C->getValue().isPowerOf2())
3098         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3099   }
3100
3101   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3102     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3103     if (RHSI->getOpcode() == Instruction::Shl &&
3104         isa<ConstantInt>(RHSI->getOperand(0))) {
3105       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3106         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3107         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3108                                                                    "tmp"), I);
3109         return BinaryOperator::CreateAnd(Op0, Add);
3110       }
3111     }
3112   }
3113
3114   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3115   // where C1&C2 are powers of two.
3116   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3117     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3118       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3119         // STO == 0 and SFO == 0 handled above.
3120         if ((STO->getValue().isPowerOf2()) && 
3121             (SFO->getValue().isPowerOf2())) {
3122           Value *TrueAnd = InsertNewInstBefore(
3123             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3124           Value *FalseAnd = InsertNewInstBefore(
3125             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3126           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3127         }
3128       }
3129   }
3130   
3131   return 0;
3132 }
3133
3134 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3135   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3136
3137   // Handle the integer rem common cases
3138   if (Instruction *common = commonIRemTransforms(I))
3139     return common;
3140   
3141   if (Value *RHSNeg = dyn_castNegVal(Op1))
3142     if (!isa<Constant>(RHSNeg) ||
3143         (isa<ConstantInt>(RHSNeg) &&
3144          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3145       // X % -Y -> X % Y
3146       AddUsesToWorkList(I);
3147       I.setOperand(1, RHSNeg);
3148       return &I;
3149     }
3150
3151   // If the sign bits of both operands are zero (i.e. we can prove they are
3152   // unsigned inputs), turn this into a urem.
3153   if (I.getType()->isInteger()) {
3154     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3155     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3156       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3157       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3158     }
3159   }
3160
3161   // If it's a constant vector, flip any negative values positive.
3162   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3163     unsigned VWidth = RHSV->getNumOperands();
3164
3165     bool hasNegative = false;
3166     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3167       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3168         if (RHS->getValue().isNegative())
3169           hasNegative = true;
3170
3171     if (hasNegative) {
3172       std::vector<Constant *> Elts(VWidth);
3173       for (unsigned i = 0; i != VWidth; ++i) {
3174         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3175           if (RHS->getValue().isNegative())
3176             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3177           else
3178             Elts[i] = RHS;
3179         }
3180       }
3181
3182       Constant *NewRHSV = ConstantVector::get(Elts);
3183       if (NewRHSV != RHSV) {
3184         AddUsesToWorkList(I);
3185         I.setOperand(1, NewRHSV);
3186         return &I;
3187       }
3188     }
3189   }
3190
3191   return 0;
3192 }
3193
3194 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3195   return commonRemTransforms(I);
3196 }
3197
3198 // isOneBitSet - Return true if there is exactly one bit set in the specified
3199 // constant.
3200 static bool isOneBitSet(const ConstantInt *CI) {
3201   return CI->getValue().isPowerOf2();
3202 }
3203
3204 // isHighOnes - Return true if the constant is of the form 1+0+.
3205 // This is the same as lowones(~X).
3206 static bool isHighOnes(const ConstantInt *CI) {
3207   return (~CI->getValue() + 1).isPowerOf2();
3208 }
3209
3210 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3211 /// are carefully arranged to allow folding of expressions such as:
3212 ///
3213 ///      (A < B) | (A > B) --> (A != B)
3214 ///
3215 /// Note that this is only valid if the first and second predicates have the
3216 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3217 ///
3218 /// Three bits are used to represent the condition, as follows:
3219 ///   0  A > B
3220 ///   1  A == B
3221 ///   2  A < B
3222 ///
3223 /// <=>  Value  Definition
3224 /// 000     0   Always false
3225 /// 001     1   A >  B
3226 /// 010     2   A == B
3227 /// 011     3   A >= B
3228 /// 100     4   A <  B
3229 /// 101     5   A != B
3230 /// 110     6   A <= B
3231 /// 111     7   Always true
3232 ///  
3233 static unsigned getICmpCode(const ICmpInst *ICI) {
3234   switch (ICI->getPredicate()) {
3235     // False -> 0
3236   case ICmpInst::ICMP_UGT: return 1;  // 001
3237   case ICmpInst::ICMP_SGT: return 1;  // 001
3238   case ICmpInst::ICMP_EQ:  return 2;  // 010
3239   case ICmpInst::ICMP_UGE: return 3;  // 011
3240   case ICmpInst::ICMP_SGE: return 3;  // 011
3241   case ICmpInst::ICMP_ULT: return 4;  // 100
3242   case ICmpInst::ICMP_SLT: return 4;  // 100
3243   case ICmpInst::ICMP_NE:  return 5;  // 101
3244   case ICmpInst::ICMP_ULE: return 6;  // 110
3245   case ICmpInst::ICMP_SLE: return 6;  // 110
3246     // True -> 7
3247   default:
3248     assert(0 && "Invalid ICmp predicate!");
3249     return 0;
3250   }
3251 }
3252
3253 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3254 /// predicate into a three bit mask. It also returns whether it is an ordered
3255 /// predicate by reference.
3256 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3257   isOrdered = false;
3258   switch (CC) {
3259   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3260   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3261   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3262   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3263   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3264   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3265   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3266   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3267   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3268   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3269   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3270   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3271   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3272   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3273     // True -> 7
3274   default:
3275     // Not expecting FCMP_FALSE and FCMP_TRUE;
3276     assert(0 && "Unexpected FCmp predicate!");
3277     return 0;
3278   }
3279 }
3280
3281 /// getICmpValue - This is the complement of getICmpCode, which turns an
3282 /// opcode and two operands into either a constant true or false, or a brand 
3283 /// new ICmp instruction. The sign is passed in to determine which kind
3284 /// of predicate to use in the new icmp instruction.
3285 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3286   switch (code) {
3287   default: assert(0 && "Illegal ICmp code!");
3288   case  0: return ConstantInt::getFalse();
3289   case  1: 
3290     if (sign)
3291       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3292     else
3293       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3294   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3295   case  3: 
3296     if (sign)
3297       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3298     else
3299       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3300   case  4: 
3301     if (sign)
3302       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3303     else
3304       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3305   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3306   case  6: 
3307     if (sign)
3308       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3309     else
3310       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3311   case  7: return ConstantInt::getTrue();
3312   }
3313 }
3314
3315 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3316 /// opcode and two operands into either a FCmp instruction. isordered is passed
3317 /// in to determine which kind of predicate to use in the new fcmp instruction.
3318 static Value *getFCmpValue(bool isordered, unsigned code,
3319                            Value *LHS, Value *RHS) {
3320   switch (code) {
3321   default: assert(0 && "Illegal FCmp code!");
3322   case  0:
3323     if (isordered)
3324       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3325     else
3326       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3327   case  1: 
3328     if (isordered)
3329       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3330     else
3331       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3332   case  2: 
3333     if (isordered)
3334       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3335     else
3336       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3337   case  3: 
3338     if (isordered)
3339       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3340     else
3341       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3342   case  4: 
3343     if (isordered)
3344       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3345     else
3346       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3347   case  5: 
3348     if (isordered)
3349       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3350     else
3351       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3352   case  6: 
3353     if (isordered)
3354       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3355     else
3356       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3357   case  7: return ConstantInt::getTrue();
3358   }
3359 }
3360
3361 /// PredicatesFoldable - Return true if both predicates match sign or if at
3362 /// least one of them is an equality comparison (which is signless).
3363 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3364   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3365          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3366          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3367 }
3368
3369 namespace { 
3370 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3371 struct FoldICmpLogical {
3372   InstCombiner &IC;
3373   Value *LHS, *RHS;
3374   ICmpInst::Predicate pred;
3375   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3376     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3377       pred(ICI->getPredicate()) {}
3378   bool shouldApply(Value *V) const {
3379     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3380       if (PredicatesFoldable(pred, ICI->getPredicate()))
3381         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3382                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3383     return false;
3384   }
3385   Instruction *apply(Instruction &Log) const {
3386     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3387     if (ICI->getOperand(0) != LHS) {
3388       assert(ICI->getOperand(1) == LHS);
3389       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3390     }
3391
3392     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3393     unsigned LHSCode = getICmpCode(ICI);
3394     unsigned RHSCode = getICmpCode(RHSICI);
3395     unsigned Code;
3396     switch (Log.getOpcode()) {
3397     case Instruction::And: Code = LHSCode & RHSCode; break;
3398     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3399     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3400     default: assert(0 && "Illegal logical opcode!"); return 0;
3401     }
3402
3403     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3404                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3405       
3406     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3407     if (Instruction *I = dyn_cast<Instruction>(RV))
3408       return I;
3409     // Otherwise, it's a constant boolean value...
3410     return IC.ReplaceInstUsesWith(Log, RV);
3411   }
3412 };
3413 } // end anonymous namespace
3414
3415 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3416 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3417 // guaranteed to be a binary operator.
3418 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3419                                     ConstantInt *OpRHS,
3420                                     ConstantInt *AndRHS,
3421                                     BinaryOperator &TheAnd) {
3422   Value *X = Op->getOperand(0);
3423   Constant *Together = 0;
3424   if (!Op->isShift())
3425     Together = And(AndRHS, OpRHS);
3426
3427   switch (Op->getOpcode()) {
3428   case Instruction::Xor:
3429     if (Op->hasOneUse()) {
3430       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3431       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3432       InsertNewInstBefore(And, TheAnd);
3433       And->takeName(Op);
3434       return BinaryOperator::CreateXor(And, Together);
3435     }
3436     break;
3437   case Instruction::Or:
3438     if (Together == AndRHS) // (X | C) & C --> C
3439       return ReplaceInstUsesWith(TheAnd, AndRHS);
3440
3441     if (Op->hasOneUse() && Together != OpRHS) {
3442       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3443       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3444       InsertNewInstBefore(Or, TheAnd);
3445       Or->takeName(Op);
3446       return BinaryOperator::CreateAnd(Or, AndRHS);
3447     }
3448     break;
3449   case Instruction::Add:
3450     if (Op->hasOneUse()) {
3451       // Adding a one to a single bit bit-field should be turned into an XOR
3452       // of the bit.  First thing to check is to see if this AND is with a
3453       // single bit constant.
3454       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3455
3456       // If there is only one bit set...
3457       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3458         // Ok, at this point, we know that we are masking the result of the
3459         // ADD down to exactly one bit.  If the constant we are adding has
3460         // no bits set below this bit, then we can eliminate the ADD.
3461         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3462
3463         // Check to see if any bits below the one bit set in AndRHSV are set.
3464         if ((AddRHS & (AndRHSV-1)) == 0) {
3465           // If not, the only thing that can effect the output of the AND is
3466           // the bit specified by AndRHSV.  If that bit is set, the effect of
3467           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3468           // no effect.
3469           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3470             TheAnd.setOperand(0, X);
3471             return &TheAnd;
3472           } else {
3473             // Pull the XOR out of the AND.
3474             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3475             InsertNewInstBefore(NewAnd, TheAnd);
3476             NewAnd->takeName(Op);
3477             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3478           }
3479         }
3480       }
3481     }
3482     break;
3483
3484   case Instruction::Shl: {
3485     // We know that the AND will not produce any of the bits shifted in, so if
3486     // the anded constant includes them, clear them now!
3487     //
3488     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3489     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3490     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3491     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3492
3493     if (CI->getValue() == ShlMask) { 
3494     // Masking out bits that the shift already masks
3495       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3496     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3497       TheAnd.setOperand(1, CI);
3498       return &TheAnd;
3499     }
3500     break;
3501   }
3502   case Instruction::LShr:
3503   {
3504     // We know that the AND will not produce any of the bits shifted in, so if
3505     // the anded constant includes them, clear them now!  This only applies to
3506     // unsigned shifts, because a signed shr may bring in set bits!
3507     //
3508     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3509     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3510     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3511     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3512
3513     if (CI->getValue() == ShrMask) {   
3514     // Masking out bits that the shift already masks.
3515       return ReplaceInstUsesWith(TheAnd, Op);
3516     } else if (CI != AndRHS) {
3517       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3518       return &TheAnd;
3519     }
3520     break;
3521   }
3522   case Instruction::AShr:
3523     // Signed shr.
3524     // See if this is shifting in some sign extension, then masking it out
3525     // with an and.
3526     if (Op->hasOneUse()) {
3527       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3528       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3529       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3530       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3531       if (C == AndRHS) {          // Masking out bits shifted in.
3532         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3533         // Make the argument unsigned.
3534         Value *ShVal = Op->getOperand(0);
3535         ShVal = InsertNewInstBefore(
3536             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3537                                    Op->getName()), TheAnd);
3538         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3539       }
3540     }
3541     break;
3542   }
3543   return 0;
3544 }
3545
3546
3547 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3548 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3549 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3550 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3551 /// insert new instructions.
3552 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3553                                            bool isSigned, bool Inside, 
3554                                            Instruction &IB) {
3555   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3556             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3557          "Lo is not <= Hi in range emission code!");
3558     
3559   if (Inside) {
3560     if (Lo == Hi)  // Trivially false.
3561       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3562
3563     // V >= Min && V < Hi --> V < Hi
3564     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3565       ICmpInst::Predicate pred = (isSigned ? 
3566         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3567       return new ICmpInst(pred, V, Hi);
3568     }
3569
3570     // Emit V-Lo <u Hi-Lo
3571     Constant *NegLo = ConstantExpr::getNeg(Lo);
3572     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3573     InsertNewInstBefore(Add, IB);
3574     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3575     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3576   }
3577
3578   if (Lo == Hi)  // Trivially true.
3579     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3580
3581   // V < Min || V >= Hi -> V > Hi-1
3582   Hi = SubOne(cast<ConstantInt>(Hi));
3583   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3584     ICmpInst::Predicate pred = (isSigned ? 
3585         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3586     return new ICmpInst(pred, V, Hi);
3587   }
3588
3589   // Emit V-Lo >u Hi-1-Lo
3590   // Note that Hi has already had one subtracted from it, above.
3591   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3592   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3593   InsertNewInstBefore(Add, IB);
3594   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3595   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3596 }
3597
3598 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3599 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3600 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3601 // not, since all 1s are not contiguous.
3602 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3603   const APInt& V = Val->getValue();
3604   uint32_t BitWidth = Val->getType()->getBitWidth();
3605   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3606
3607   // look for the first zero bit after the run of ones
3608   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3609   // look for the first non-zero bit
3610   ME = V.getActiveBits(); 
3611   return true;
3612 }
3613
3614 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3615 /// where isSub determines whether the operator is a sub.  If we can fold one of
3616 /// the following xforms:
3617 /// 
3618 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3619 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3620 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3621 ///
3622 /// return (A +/- B).
3623 ///
3624 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3625                                         ConstantInt *Mask, bool isSub,
3626                                         Instruction &I) {
3627   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3628   if (!LHSI || LHSI->getNumOperands() != 2 ||
3629       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3630
3631   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3632
3633   switch (LHSI->getOpcode()) {
3634   default: return 0;
3635   case Instruction::And:
3636     if (And(N, Mask) == Mask) {
3637       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3638       if ((Mask->getValue().countLeadingZeros() + 
3639            Mask->getValue().countPopulation()) == 
3640           Mask->getValue().getBitWidth())
3641         break;
3642
3643       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3644       // part, we don't need any explicit masks to take them out of A.  If that
3645       // is all N is, ignore it.
3646       uint32_t MB = 0, ME = 0;
3647       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3648         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3649         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3650         if (MaskedValueIsZero(RHS, Mask))
3651           break;
3652       }
3653     }
3654     return 0;
3655   case Instruction::Or:
3656   case Instruction::Xor:
3657     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3658     if ((Mask->getValue().countLeadingZeros() + 
3659          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3660         && And(N, Mask)->isZero())
3661       break;
3662     return 0;
3663   }
3664   
3665   Instruction *New;
3666   if (isSub)
3667     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3668   else
3669     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3670   return InsertNewInstBefore(New, I);
3671 }
3672
3673 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3674 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3675                                           ICmpInst *LHS, ICmpInst *RHS) {
3676   Value *Val, *Val2;
3677   ConstantInt *LHSCst, *RHSCst;
3678   ICmpInst::Predicate LHSCC, RHSCC;
3679   
3680   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3681   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3682       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3683     return 0;
3684   
3685   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3686   // where C is a power of 2
3687   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3688       LHSCst->getValue().isPowerOf2()) {
3689     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3690     InsertNewInstBefore(NewOr, I);
3691     return new ICmpInst(LHSCC, NewOr, LHSCst);
3692   }
3693   
3694   // From here on, we only handle:
3695   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3696   if (Val != Val2) return 0;
3697   
3698   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3699   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3700       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3701       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3702       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3703     return 0;
3704   
3705   // We can't fold (ugt x, C) & (sgt x, C2).
3706   if (!PredicatesFoldable(LHSCC, RHSCC))
3707     return 0;
3708     
3709   // Ensure that the larger constant is on the RHS.
3710   bool ShouldSwap;
3711   if (ICmpInst::isSignedPredicate(LHSCC) ||
3712       (ICmpInst::isEquality(LHSCC) && 
3713        ICmpInst::isSignedPredicate(RHSCC)))
3714     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3715   else
3716     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3717     
3718   if (ShouldSwap) {
3719     std::swap(LHS, RHS);
3720     std::swap(LHSCst, RHSCst);
3721     std::swap(LHSCC, RHSCC);
3722   }
3723
3724   // At this point, we know we have have two icmp instructions
3725   // comparing a value against two constants and and'ing the result
3726   // together.  Because of the above check, we know that we only have
3727   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3728   // (from the FoldICmpLogical check above), that the two constants 
3729   // are not equal and that the larger constant is on the RHS
3730   assert(LHSCst != RHSCst && "Compares not folded above?");
3731
3732   switch (LHSCC) {
3733   default: assert(0 && "Unknown integer condition code!");
3734   case ICmpInst::ICMP_EQ:
3735     switch (RHSCC) {
3736     default: assert(0 && "Unknown integer condition code!");
3737     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3738     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3739     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3740       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3741     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3742     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3743     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3744       return ReplaceInstUsesWith(I, LHS);
3745     }
3746   case ICmpInst::ICMP_NE:
3747     switch (RHSCC) {
3748     default: assert(0 && "Unknown integer condition code!");
3749     case ICmpInst::ICMP_ULT:
3750       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3751         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3752       break;                        // (X != 13 & X u< 15) -> no change
3753     case ICmpInst::ICMP_SLT:
3754       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3755         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3756       break;                        // (X != 13 & X s< 15) -> no change
3757     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3758     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3759     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3760       return ReplaceInstUsesWith(I, RHS);
3761     case ICmpInst::ICMP_NE:
3762       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3763         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3764         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3765                                                      Val->getName()+".off");
3766         InsertNewInstBefore(Add, I);
3767         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3768                             ConstantInt::get(Add->getType(), 1));
3769       }
3770       break;                        // (X != 13 & X != 15) -> no change
3771     }
3772     break;
3773   case ICmpInst::ICMP_ULT:
3774     switch (RHSCC) {
3775     default: assert(0 && "Unknown integer condition code!");
3776     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3777     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3778       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3779     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3780       break;
3781     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3782     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3783       return ReplaceInstUsesWith(I, LHS);
3784     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3785       break;
3786     }
3787     break;
3788   case ICmpInst::ICMP_SLT:
3789     switch (RHSCC) {
3790     default: assert(0 && "Unknown integer condition code!");
3791     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3792     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3793       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3794     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3795       break;
3796     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3797     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3798       return ReplaceInstUsesWith(I, LHS);
3799     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3800       break;
3801     }
3802     break;
3803   case ICmpInst::ICMP_UGT:
3804     switch (RHSCC) {
3805     default: assert(0 && "Unknown integer condition code!");
3806     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3807     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3808       return ReplaceInstUsesWith(I, RHS);
3809     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3810       break;
3811     case ICmpInst::ICMP_NE:
3812       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3813         return new ICmpInst(LHSCC, Val, RHSCst);
3814       break;                        // (X u> 13 & X != 15) -> no change
3815     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3816       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3817     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3818       break;
3819     }
3820     break;
3821   case ICmpInst::ICMP_SGT:
3822     switch (RHSCC) {
3823     default: assert(0 && "Unknown integer condition code!");
3824     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3825     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3826       return ReplaceInstUsesWith(I, RHS);
3827     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3828       break;
3829     case ICmpInst::ICMP_NE:
3830       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3831         return new ICmpInst(LHSCC, Val, RHSCst);
3832       break;                        // (X s> 13 & X != 15) -> no change
3833     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3834       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3835     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3836       break;
3837     }
3838     break;
3839   }
3840  
3841   return 0;
3842 }
3843
3844
3845 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3846   bool Changed = SimplifyCommutative(I);
3847   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3848
3849   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3850     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3851
3852   // and X, X = X
3853   if (Op0 == Op1)
3854     return ReplaceInstUsesWith(I, Op1);
3855
3856   // See if we can simplify any instructions used by the instruction whose sole 
3857   // purpose is to compute bits we don't care about.
3858   if (!isa<VectorType>(I.getType())) {
3859     if (SimplifyDemandedInstructionBits(I))
3860       return &I;
3861   } else {
3862     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3863       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3864         return ReplaceInstUsesWith(I, I.getOperand(0));
3865     } else if (isa<ConstantAggregateZero>(Op1)) {
3866       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3867     }
3868   }
3869   
3870   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3871     const APInt& AndRHSMask = AndRHS->getValue();
3872     APInt NotAndRHS(~AndRHSMask);
3873
3874     // Optimize a variety of ((val OP C1) & C2) combinations...
3875     if (isa<BinaryOperator>(Op0)) {
3876       Instruction *Op0I = cast<Instruction>(Op0);
3877       Value *Op0LHS = Op0I->getOperand(0);
3878       Value *Op0RHS = Op0I->getOperand(1);
3879       switch (Op0I->getOpcode()) {
3880       case Instruction::Xor:
3881       case Instruction::Or:
3882         // If the mask is only needed on one incoming arm, push it up.
3883         if (Op0I->hasOneUse()) {
3884           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3885             // Not masking anything out for the LHS, move to RHS.
3886             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3887                                                    Op0RHS->getName()+".masked");
3888             InsertNewInstBefore(NewRHS, I);
3889             return BinaryOperator::Create(
3890                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3891           }
3892           if (!isa<Constant>(Op0RHS) &&
3893               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3894             // Not masking anything out for the RHS, move to LHS.
3895             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3896                                                    Op0LHS->getName()+".masked");
3897             InsertNewInstBefore(NewLHS, I);
3898             return BinaryOperator::Create(
3899                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3900           }
3901         }
3902
3903         break;
3904       case Instruction::Add:
3905         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3906         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3907         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3908         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3909           return BinaryOperator::CreateAnd(V, AndRHS);
3910         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3911           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3912         break;
3913
3914       case Instruction::Sub:
3915         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3916         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3917         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3918         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3919           return BinaryOperator::CreateAnd(V, AndRHS);
3920
3921         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3922         // has 1's for all bits that the subtraction with A might affect.
3923         if (Op0I->hasOneUse()) {
3924           uint32_t BitWidth = AndRHSMask.getBitWidth();
3925           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3926           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3927
3928           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3929           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3930               MaskedValueIsZero(Op0LHS, Mask)) {
3931             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3932             InsertNewInstBefore(NewNeg, I);
3933             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3934           }
3935         }
3936         break;
3937
3938       case Instruction::Shl:
3939       case Instruction::LShr:
3940         // (1 << x) & 1 --> zext(x == 0)
3941         // (1 >> x) & 1 --> zext(x == 0)
3942         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3943           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3944                                            Constant::getNullValue(I.getType()));
3945           InsertNewInstBefore(NewICmp, I);
3946           return new ZExtInst(NewICmp, I.getType());
3947         }
3948         break;
3949       }
3950
3951       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3952         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3953           return Res;
3954     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3955       // If this is an integer truncation or change from signed-to-unsigned, and
3956       // if the source is an and/or with immediate, transform it.  This
3957       // frequently occurs for bitfield accesses.
3958       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3959         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3960             CastOp->getNumOperands() == 2)
3961           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3962             if (CastOp->getOpcode() == Instruction::And) {
3963               // Change: and (cast (and X, C1) to T), C2
3964               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3965               // This will fold the two constants together, which may allow 
3966               // other simplifications.
3967               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3968                 CastOp->getOperand(0), I.getType(), 
3969                 CastOp->getName()+".shrunk");
3970               NewCast = InsertNewInstBefore(NewCast, I);
3971               // trunc_or_bitcast(C1)&C2
3972               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3973               C3 = ConstantExpr::getAnd(C3, AndRHS);
3974               return BinaryOperator::CreateAnd(NewCast, C3);
3975             } else if (CastOp->getOpcode() == Instruction::Or) {
3976               // Change: and (cast (or X, C1) to T), C2
3977               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3978               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3979               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3980                 return ReplaceInstUsesWith(I, AndRHS);
3981             }
3982           }
3983       }
3984     }
3985
3986     // Try to fold constant and into select arguments.
3987     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3988       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3989         return R;
3990     if (isa<PHINode>(Op0))
3991       if (Instruction *NV = FoldOpIntoPhi(I))
3992         return NV;
3993   }
3994
3995   Value *Op0NotVal = dyn_castNotVal(Op0);
3996   Value *Op1NotVal = dyn_castNotVal(Op1);
3997
3998   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3999     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4000
4001   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4002   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4003     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4004                                                I.getName()+".demorgan");
4005     InsertNewInstBefore(Or, I);
4006     return BinaryOperator::CreateNot(Or);
4007   }
4008   
4009   {
4010     Value *A = 0, *B = 0, *C = 0, *D = 0;
4011     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4012       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4013         return ReplaceInstUsesWith(I, Op1);
4014     
4015       // (A|B) & ~(A&B) -> A^B
4016       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4017         if ((A == C && B == D) || (A == D && B == C))
4018           return BinaryOperator::CreateXor(A, B);
4019       }
4020     }
4021     
4022     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4023       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4024         return ReplaceInstUsesWith(I, Op0);
4025
4026       // ~(A&B) & (A|B) -> A^B
4027       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4028         if ((A == C && B == D) || (A == D && B == C))
4029           return BinaryOperator::CreateXor(A, B);
4030       }
4031     }
4032     
4033     if (Op0->hasOneUse() &&
4034         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4035       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4036         I.swapOperands();     // Simplify below
4037         std::swap(Op0, Op1);
4038       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4039         cast<BinaryOperator>(Op0)->swapOperands();
4040         I.swapOperands();     // Simplify below
4041         std::swap(Op0, Op1);
4042       }
4043     }
4044
4045     if (Op1->hasOneUse() &&
4046         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4047       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4048         cast<BinaryOperator>(Op1)->swapOperands();
4049         std::swap(A, B);
4050       }
4051       if (A == Op0) {                                // A&(A^B) -> A & ~B
4052         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4053         InsertNewInstBefore(NotB, I);
4054         return BinaryOperator::CreateAnd(A, NotB);
4055       }
4056     }
4057
4058     // (A&((~A)|B)) -> A&B
4059     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4060         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4061       return BinaryOperator::CreateAnd(A, Op1);
4062     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4063         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4064       return BinaryOperator::CreateAnd(A, Op0);
4065   }
4066   
4067   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4068     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4069     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4070       return R;
4071
4072     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4073       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4074         return Res;
4075   }
4076
4077   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4078   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4079     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4080       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4081         const Type *SrcTy = Op0C->getOperand(0)->getType();
4082         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4083             // Only do this if the casts both really cause code to be generated.
4084             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4085                               I.getType(), TD) &&
4086             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4087                               I.getType(), TD)) {
4088           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4089                                                          Op1C->getOperand(0),
4090                                                          I.getName());
4091           InsertNewInstBefore(NewOp, I);
4092           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4093         }
4094       }
4095     
4096   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4097   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4098     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4099       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4100           SI0->getOperand(1) == SI1->getOperand(1) &&
4101           (SI0->hasOneUse() || SI1->hasOneUse())) {
4102         Instruction *NewOp =
4103           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4104                                                         SI1->getOperand(0),
4105                                                         SI0->getName()), I);
4106         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4107                                       SI1->getOperand(1));
4108       }
4109   }
4110
4111   // If and'ing two fcmp, try combine them into one.
4112   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4113     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4114       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4115           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4116         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4117         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4118           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4119             // If either of the constants are nans, then the whole thing returns
4120             // false.
4121             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4122               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4123             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4124                                 RHS->getOperand(0));
4125           }
4126       } else {
4127         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4128         FCmpInst::Predicate Op0CC, Op1CC;
4129         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4130             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4131           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4132             // Swap RHS operands to match LHS.
4133             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4134             std::swap(Op1LHS, Op1RHS);
4135           }
4136           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4137             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4138             if (Op0CC == Op1CC)
4139               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4140             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4141                      Op1CC == FCmpInst::FCMP_FALSE)
4142               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4143             else if (Op0CC == FCmpInst::FCMP_TRUE)
4144               return ReplaceInstUsesWith(I, Op1);
4145             else if (Op1CC == FCmpInst::FCMP_TRUE)
4146               return ReplaceInstUsesWith(I, Op0);
4147             bool Op0Ordered;
4148             bool Op1Ordered;
4149             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4150             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4151             if (Op1Pred == 0) {
4152               std::swap(Op0, Op1);
4153               std::swap(Op0Pred, Op1Pred);
4154               std::swap(Op0Ordered, Op1Ordered);
4155             }
4156             if (Op0Pred == 0) {
4157               // uno && ueq -> uno && (uno || eq) -> ueq
4158               // ord && olt -> ord && (ord && lt) -> olt
4159               if (Op0Ordered == Op1Ordered)
4160                 return ReplaceInstUsesWith(I, Op1);
4161               // uno && oeq -> uno && (ord && eq) -> false
4162               // uno && ord -> false
4163               if (!Op0Ordered)
4164                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4165               // ord && ueq -> ord && (uno || eq) -> oeq
4166               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4167                                                     Op0LHS, Op0RHS));
4168             }
4169           }
4170         }
4171       }
4172     }
4173   }
4174
4175   return Changed ? &I : 0;
4176 }
4177
4178 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4179 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4180 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4181 /// the expression came from the corresponding "byte swapped" byte in some other
4182 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4183 /// we know that the expression deposits the low byte of %X into the high byte
4184 /// of the bswap result and that all other bytes are zero.  This expression is
4185 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4186 /// match.
4187 ///
4188 /// This function returns true if the match was unsuccessful and false if so.
4189 /// On entry to the function the "OverallLeftShift" is a signed integer value
4190 /// indicating the number of bytes that the subexpression is later shifted.  For
4191 /// example, if the expression is later right shifted by 16 bits, the
4192 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4193 /// byte of ByteValues is actually being set.
4194 ///
4195 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4196 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4197 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4198 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4199 /// always in the local (OverallLeftShift) coordinate space.
4200 ///
4201 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4202                               SmallVector<Value*, 8> &ByteValues) {
4203   if (Instruction *I = dyn_cast<Instruction>(V)) {
4204     // If this is an or instruction, it may be an inner node of the bswap.
4205     if (I->getOpcode() == Instruction::Or) {
4206       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4207                                ByteValues) ||
4208              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4209                                ByteValues);
4210     }
4211   
4212     // If this is a logical shift by a constant multiple of 8, recurse with
4213     // OverallLeftShift and ByteMask adjusted.
4214     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4215       unsigned ShAmt = 
4216         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4217       // Ensure the shift amount is defined and of a byte value.
4218       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4219         return true;
4220
4221       unsigned ByteShift = ShAmt >> 3;
4222       if (I->getOpcode() == Instruction::Shl) {
4223         // X << 2 -> collect(X, +2)
4224         OverallLeftShift += ByteShift;
4225         ByteMask >>= ByteShift;
4226       } else {
4227         // X >>u 2 -> collect(X, -2)
4228         OverallLeftShift -= ByteShift;
4229         ByteMask <<= ByteShift;
4230         ByteMask &= (~0U >> (32-ByteValues.size()));
4231       }
4232
4233       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4234       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4235
4236       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4237                                ByteValues);
4238     }
4239
4240     // If this is a logical 'and' with a mask that clears bytes, clear the
4241     // corresponding bytes in ByteMask.
4242     if (I->getOpcode() == Instruction::And &&
4243         isa<ConstantInt>(I->getOperand(1))) {
4244       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4245       unsigned NumBytes = ByteValues.size();
4246       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4247       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4248       
4249       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4250         // If this byte is masked out by a later operation, we don't care what
4251         // the and mask is.
4252         if ((ByteMask & (1 << i)) == 0)
4253           continue;
4254         
4255         // If the AndMask is all zeros for this byte, clear the bit.
4256         APInt MaskB = AndMask & Byte;
4257         if (MaskB == 0) {
4258           ByteMask &= ~(1U << i);
4259           continue;
4260         }
4261         
4262         // If the AndMask is not all ones for this byte, it's not a bytezap.
4263         if (MaskB != Byte)
4264           return true;
4265
4266         // Otherwise, this byte is kept.
4267       }
4268
4269       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4270                                ByteValues);
4271     }
4272   }
4273   
4274   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4275   // the input value to the bswap.  Some observations: 1) if more than one byte
4276   // is demanded from this input, then it could not be successfully assembled
4277   // into a byteswap.  At least one of the two bytes would not be aligned with
4278   // their ultimate destination.
4279   if (!isPowerOf2_32(ByteMask)) return true;
4280   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4281   
4282   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4283   // is demanded, it needs to go into byte 0 of the result.  This means that the
4284   // byte needs to be shifted until it lands in the right byte bucket.  The
4285   // shift amount depends on the position: if the byte is coming from the high
4286   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4287   // low part, it must be shifted left.
4288   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4289   if (InputByteNo < ByteValues.size()/2) {
4290     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4291       return true;
4292   } else {
4293     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4294       return true;
4295   }
4296   
4297   // If the destination byte value is already defined, the values are or'd
4298   // together, which isn't a bswap (unless it's an or of the same bits).
4299   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4300     return true;
4301   ByteValues[DestByteNo] = V;
4302   return false;
4303 }
4304
4305 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4306 /// If so, insert the new bswap intrinsic and return it.
4307 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4308   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4309   if (!ITy || ITy->getBitWidth() % 16 || 
4310       // ByteMask only allows up to 32-byte values.
4311       ITy->getBitWidth() > 32*8) 
4312     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4313   
4314   /// ByteValues - For each byte of the result, we keep track of which value
4315   /// defines each byte.
4316   SmallVector<Value*, 8> ByteValues;
4317   ByteValues.resize(ITy->getBitWidth()/8);
4318     
4319   // Try to find all the pieces corresponding to the bswap.
4320   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4321   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4322     return 0;
4323   
4324   // Check to see if all of the bytes come from the same value.
4325   Value *V = ByteValues[0];
4326   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4327   
4328   // Check to make sure that all of the bytes come from the same value.
4329   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4330     if (ByteValues[i] != V)
4331       return 0;
4332   const Type *Tys[] = { ITy };
4333   Module *M = I.getParent()->getParent()->getParent();
4334   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4335   return CallInst::Create(F, V);
4336 }
4337
4338 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4339 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4340 /// we can simplify this expression to "cond ? C : D or B".
4341 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4342                                          Value *C, Value *D) {
4343   // If A is not a select of -1/0, this cannot match.
4344   Value *Cond = 0;
4345   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4346     return 0;
4347
4348   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4349   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4350     return SelectInst::Create(Cond, C, B);
4351   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4352     return SelectInst::Create(Cond, C, B);
4353   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4354   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4355     return SelectInst::Create(Cond, C, D);
4356   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4357     return SelectInst::Create(Cond, C, D);
4358   return 0;
4359 }
4360
4361 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4362 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4363                                          ICmpInst *LHS, ICmpInst *RHS) {
4364   Value *Val, *Val2;
4365   ConstantInt *LHSCst, *RHSCst;
4366   ICmpInst::Predicate LHSCC, RHSCC;
4367   
4368   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4369   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4370       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4371     return 0;
4372   
4373   // From here on, we only handle:
4374   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4375   if (Val != Val2) return 0;
4376   
4377   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4378   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4379       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4380       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4381       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4382     return 0;
4383   
4384   // We can't fold (ugt x, C) | (sgt x, C2).
4385   if (!PredicatesFoldable(LHSCC, RHSCC))
4386     return 0;
4387   
4388   // Ensure that the larger constant is on the RHS.
4389   bool ShouldSwap;
4390   if (ICmpInst::isSignedPredicate(LHSCC) ||
4391       (ICmpInst::isEquality(LHSCC) && 
4392        ICmpInst::isSignedPredicate(RHSCC)))
4393     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4394   else
4395     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4396   
4397   if (ShouldSwap) {
4398     std::swap(LHS, RHS);
4399     std::swap(LHSCst, RHSCst);
4400     std::swap(LHSCC, RHSCC);
4401   }
4402   
4403   // At this point, we know we have have two icmp instructions
4404   // comparing a value against two constants and or'ing the result
4405   // together.  Because of the above check, we know that we only have
4406   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4407   // FoldICmpLogical check above), that the two constants are not
4408   // equal.
4409   assert(LHSCst != RHSCst && "Compares not folded above?");
4410
4411   switch (LHSCC) {
4412   default: assert(0 && "Unknown integer condition code!");
4413   case ICmpInst::ICMP_EQ:
4414     switch (RHSCC) {
4415     default: assert(0 && "Unknown integer condition code!");
4416     case ICmpInst::ICMP_EQ:
4417       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4418         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4419         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4420                                                      Val->getName()+".off");
4421         InsertNewInstBefore(Add, I);
4422         AddCST = Subtract(AddOne(RHSCst), LHSCst);
4423         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4424       }
4425       break;                         // (X == 13 | X == 15) -> no change
4426     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4427     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4428       break;
4429     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4430     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4431     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4432       return ReplaceInstUsesWith(I, RHS);
4433     }
4434     break;
4435   case ICmpInst::ICMP_NE:
4436     switch (RHSCC) {
4437     default: assert(0 && "Unknown integer condition code!");
4438     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4439     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4440     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4441       return ReplaceInstUsesWith(I, LHS);
4442     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4443     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4444     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4445       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4446     }
4447     break;
4448   case ICmpInst::ICMP_ULT:
4449     switch (RHSCC) {
4450     default: assert(0 && "Unknown integer condition code!");
4451     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4452       break;
4453     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4454       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4455       // this can cause overflow.
4456       if (RHSCst->isMaxValue(false))
4457         return ReplaceInstUsesWith(I, LHS);
4458       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4459     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4460       break;
4461     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4462     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4463       return ReplaceInstUsesWith(I, RHS);
4464     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4465       break;
4466     }
4467     break;
4468   case ICmpInst::ICMP_SLT:
4469     switch (RHSCC) {
4470     default: assert(0 && "Unknown integer condition code!");
4471     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4472       break;
4473     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4474       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4475       // this can cause overflow.
4476       if (RHSCst->isMaxValue(true))
4477         return ReplaceInstUsesWith(I, LHS);
4478       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4479     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4480       break;
4481     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4482     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4483       return ReplaceInstUsesWith(I, RHS);
4484     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4485       break;
4486     }
4487     break;
4488   case ICmpInst::ICMP_UGT:
4489     switch (RHSCC) {
4490     default: assert(0 && "Unknown integer condition code!");
4491     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4492     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4493       return ReplaceInstUsesWith(I, LHS);
4494     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4495       break;
4496     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4497     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4498       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4499     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4500       break;
4501     }
4502     break;
4503   case ICmpInst::ICMP_SGT:
4504     switch (RHSCC) {
4505     default: assert(0 && "Unknown integer condition code!");
4506     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4507     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4508       return ReplaceInstUsesWith(I, LHS);
4509     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4510       break;
4511     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4512     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4513       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4514     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4515       break;
4516     }
4517     break;
4518   }
4519   return 0;
4520 }
4521
4522 /// FoldOrWithConstants - This helper function folds:
4523 ///
4524 ///     ((A | B) & C1) | (B & C2)
4525 ///
4526 /// into:
4527 /// 
4528 ///     (A & C1) | B
4529 ///
4530 /// when the XOR of the two constants is "all ones" (-1).
4531 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4532                                                Value *A, Value *B, Value *C) {
4533   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4534   if (!CI1) return 0;
4535
4536   Value *V1 = 0;
4537   ConstantInt *CI2 = 0;
4538   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4539
4540   APInt Xor = CI1->getValue() ^ CI2->getValue();
4541   if (!Xor.isAllOnesValue()) return 0;
4542
4543   if (V1 == A || V1 == B) {
4544     Instruction *NewOp =
4545       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4546     return BinaryOperator::CreateOr(NewOp, V1);
4547   }
4548
4549   return 0;
4550 }
4551
4552 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4553   bool Changed = SimplifyCommutative(I);
4554   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4555
4556   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4557     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4558
4559   // or X, X = X
4560   if (Op0 == Op1)
4561     return ReplaceInstUsesWith(I, Op0);
4562
4563   // See if we can simplify any instructions used by the instruction whose sole 
4564   // purpose is to compute bits we don't care about.
4565   if (!isa<VectorType>(I.getType())) {
4566     if (SimplifyDemandedInstructionBits(I))
4567       return &I;
4568   } else if (isa<ConstantAggregateZero>(Op1)) {
4569     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4570   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4571     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4572       return ReplaceInstUsesWith(I, I.getOperand(1));
4573   }
4574     
4575
4576   
4577   // or X, -1 == -1
4578   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4579     ConstantInt *C1 = 0; Value *X = 0;
4580     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4581     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4582       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4583       InsertNewInstBefore(Or, I);
4584       Or->takeName(Op0);
4585       return BinaryOperator::CreateAnd(Or, 
4586                ConstantInt::get(RHS->getValue() | C1->getValue()));
4587     }
4588
4589     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4590     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4591       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4592       InsertNewInstBefore(Or, I);
4593       Or->takeName(Op0);
4594       return BinaryOperator::CreateXor(Or,
4595                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4596     }
4597
4598     // Try to fold constant and into select arguments.
4599     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4600       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4601         return R;
4602     if (isa<PHINode>(Op0))
4603       if (Instruction *NV = FoldOpIntoPhi(I))
4604         return NV;
4605   }
4606
4607   Value *A = 0, *B = 0;
4608   ConstantInt *C1 = 0, *C2 = 0;
4609
4610   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4611     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4612       return ReplaceInstUsesWith(I, Op1);
4613   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4614     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4615       return ReplaceInstUsesWith(I, Op0);
4616
4617   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4618   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4619   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4620       match(Op1, m_Or(m_Value(), m_Value())) ||
4621       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4622        match(Op1, m_Shift(m_Value(), m_Value())))) {
4623     if (Instruction *BSwap = MatchBSwap(I))
4624       return BSwap;
4625   }
4626   
4627   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4628   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4629       MaskedValueIsZero(Op1, C1->getValue())) {
4630     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4631     InsertNewInstBefore(NOr, I);
4632     NOr->takeName(Op0);
4633     return BinaryOperator::CreateXor(NOr, C1);
4634   }
4635
4636   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4637   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4638       MaskedValueIsZero(Op0, C1->getValue())) {
4639     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4640     InsertNewInstBefore(NOr, I);
4641     NOr->takeName(Op0);
4642     return BinaryOperator::CreateXor(NOr, C1);
4643   }
4644
4645   // (A & C)|(B & D)
4646   Value *C = 0, *D = 0;
4647   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4648       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4649     Value *V1 = 0, *V2 = 0, *V3 = 0;
4650     C1 = dyn_cast<ConstantInt>(C);
4651     C2 = dyn_cast<ConstantInt>(D);
4652     if (C1 && C2) {  // (A & C1)|(B & C2)
4653       // If we have: ((V + N) & C1) | (V & C2)
4654       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4655       // replace with V+N.
4656       if (C1->getValue() == ~C2->getValue()) {
4657         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4658             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4659           // Add commutes, try both ways.
4660           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4661             return ReplaceInstUsesWith(I, A);
4662           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4663             return ReplaceInstUsesWith(I, A);
4664         }
4665         // Or commutes, try both ways.
4666         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4667             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4668           // Add commutes, try both ways.
4669           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4670             return ReplaceInstUsesWith(I, B);
4671           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4672             return ReplaceInstUsesWith(I, B);
4673         }
4674       }
4675       V1 = 0; V2 = 0; V3 = 0;
4676     }
4677     
4678     // Check to see if we have any common things being and'ed.  If so, find the
4679     // terms for V1 & (V2|V3).
4680     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4681       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4682         V1 = A, V2 = C, V3 = D;
4683       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4684         V1 = A, V2 = B, V3 = C;
4685       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4686         V1 = C, V2 = A, V3 = D;
4687       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4688         V1 = C, V2 = A, V3 = B;
4689       
4690       if (V1) {
4691         Value *Or =
4692           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4693         return BinaryOperator::CreateAnd(V1, Or);
4694       }
4695     }
4696
4697     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4698     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4699       return Match;
4700     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4701       return Match;
4702     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4703       return Match;
4704     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4705       return Match;
4706
4707     // ((A&~B)|(~A&B)) -> A^B
4708     if ((match(C, m_Not(m_Specific(D))) &&
4709          match(B, m_Not(m_Specific(A)))))
4710       return BinaryOperator::CreateXor(A, D);
4711     // ((~B&A)|(~A&B)) -> A^B
4712     if ((match(A, m_Not(m_Specific(D))) &&
4713          match(B, m_Not(m_Specific(C)))))
4714       return BinaryOperator::CreateXor(C, D);
4715     // ((A&~B)|(B&~A)) -> A^B
4716     if ((match(C, m_Not(m_Specific(B))) &&
4717          match(D, m_Not(m_Specific(A)))))
4718       return BinaryOperator::CreateXor(A, B);
4719     // ((~B&A)|(B&~A)) -> A^B
4720     if ((match(A, m_Not(m_Specific(B))) &&
4721          match(D, m_Not(m_Specific(C)))))
4722       return BinaryOperator::CreateXor(C, B);
4723   }
4724   
4725   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4726   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4727     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4728       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4729           SI0->getOperand(1) == SI1->getOperand(1) &&
4730           (SI0->hasOneUse() || SI1->hasOneUse())) {
4731         Instruction *NewOp =
4732         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4733                                                      SI1->getOperand(0),
4734                                                      SI0->getName()), I);
4735         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4736                                       SI1->getOperand(1));
4737       }
4738   }
4739
4740   // ((A|B)&1)|(B&-2) -> (A&1) | B
4741   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4742       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4743     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4744     if (Ret) return Ret;
4745   }
4746   // (B&-2)|((A|B)&1) -> (A&1) | B
4747   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4748       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4749     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4750     if (Ret) return Ret;
4751   }
4752
4753   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4754     if (A == Op1)   // ~A | A == -1
4755       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4756   } else {
4757     A = 0;
4758   }
4759   // Note, A is still live here!
4760   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4761     if (Op0 == B)
4762       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4763
4764     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4765     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4766       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4767                                               I.getName()+".demorgan"), I);
4768       return BinaryOperator::CreateNot(And);
4769     }
4770   }
4771
4772   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4773   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4774     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4775       return R;
4776
4777     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4778       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4779         return Res;
4780   }
4781     
4782   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4783   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4784     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4785       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4786         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4787             !isa<ICmpInst>(Op1C->getOperand(0))) {
4788           const Type *SrcTy = Op0C->getOperand(0)->getType();
4789           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4790               // Only do this if the casts both really cause code to be
4791               // generated.
4792               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4793                                 I.getType(), TD) &&
4794               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4795                                 I.getType(), TD)) {
4796             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4797                                                           Op1C->getOperand(0),
4798                                                           I.getName());
4799             InsertNewInstBefore(NewOp, I);
4800             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4801           }
4802         }
4803       }
4804   }
4805   
4806     
4807   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4808   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4809     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4810       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4811           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4812           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4813         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4814           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4815             // If either of the constants are nans, then the whole thing returns
4816             // true.
4817             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4818               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4819             
4820             // Otherwise, no need to compare the two constants, compare the
4821             // rest.
4822             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4823                                 RHS->getOperand(0));
4824           }
4825       } else {
4826         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4827         FCmpInst::Predicate Op0CC, Op1CC;
4828         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4829             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4830           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4831             // Swap RHS operands to match LHS.
4832             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4833             std::swap(Op1LHS, Op1RHS);
4834           }
4835           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4836             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4837             if (Op0CC == Op1CC)
4838               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4839             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4840                      Op1CC == FCmpInst::FCMP_TRUE)
4841               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4842             else if (Op0CC == FCmpInst::FCMP_FALSE)
4843               return ReplaceInstUsesWith(I, Op1);
4844             else if (Op1CC == FCmpInst::FCMP_FALSE)
4845               return ReplaceInstUsesWith(I, Op0);
4846             bool Op0Ordered;
4847             bool Op1Ordered;
4848             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4849             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4850             if (Op0Ordered == Op1Ordered) {
4851               // If both are ordered or unordered, return a new fcmp with
4852               // or'ed predicates.
4853               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4854                                        Op0LHS, Op0RHS);
4855               if (Instruction *I = dyn_cast<Instruction>(RV))
4856                 return I;
4857               // Otherwise, it's a constant boolean value...
4858               return ReplaceInstUsesWith(I, RV);
4859             }
4860           }
4861         }
4862       }
4863     }
4864   }
4865
4866   return Changed ? &I : 0;
4867 }
4868
4869 namespace {
4870
4871 // XorSelf - Implements: X ^ X --> 0
4872 struct XorSelf {
4873   Value *RHS;
4874   XorSelf(Value *rhs) : RHS(rhs) {}
4875   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4876   Instruction *apply(BinaryOperator &Xor) const {
4877     return &Xor;
4878   }
4879 };
4880
4881 }
4882
4883 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4884   bool Changed = SimplifyCommutative(I);
4885   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4886
4887   if (isa<UndefValue>(Op1)) {
4888     if (isa<UndefValue>(Op0))
4889       // Handle undef ^ undef -> 0 special case. This is a common
4890       // idiom (misuse).
4891       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4892     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4893   }
4894
4895   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4896   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4897     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4898     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4899   }
4900   
4901   // See if we can simplify any instructions used by the instruction whose sole 
4902   // purpose is to compute bits we don't care about.
4903   if (!isa<VectorType>(I.getType())) {
4904     if (SimplifyDemandedInstructionBits(I))
4905       return &I;
4906   } else if (isa<ConstantAggregateZero>(Op1)) {
4907     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4908   }
4909
4910   // Is this a ~ operation?
4911   if (Value *NotOp = dyn_castNotVal(&I)) {
4912     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4913     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4914     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4915       if (Op0I->getOpcode() == Instruction::And || 
4916           Op0I->getOpcode() == Instruction::Or) {
4917         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4918         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4919           Instruction *NotY =
4920             BinaryOperator::CreateNot(Op0I->getOperand(1),
4921                                       Op0I->getOperand(1)->getName()+".not");
4922           InsertNewInstBefore(NotY, I);
4923           if (Op0I->getOpcode() == Instruction::And)
4924             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4925           else
4926             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4927         }
4928       }
4929     }
4930   }
4931   
4932   
4933   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4934     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4935       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4936       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4937         return new ICmpInst(ICI->getInversePredicate(),
4938                             ICI->getOperand(0), ICI->getOperand(1));
4939
4940       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4941         return new FCmpInst(FCI->getInversePredicate(),
4942                             FCI->getOperand(0), FCI->getOperand(1));
4943     }
4944
4945     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4946     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4947       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4948         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4949           Instruction::CastOps Opcode = Op0C->getOpcode();
4950           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4951             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4952                                              Op0C->getDestTy())) {
4953               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4954                                      CI->getOpcode(), CI->getInversePredicate(),
4955                                      CI->getOperand(0), CI->getOperand(1)), I);
4956               NewCI->takeName(CI);
4957               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4958             }
4959           }
4960         }
4961       }
4962     }
4963
4964     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4965       // ~(c-X) == X-c-1 == X+(-c-1)
4966       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4967         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4968           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4969           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4970                                               ConstantInt::get(I.getType(), 1));
4971           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4972         }
4973           
4974       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4975         if (Op0I->getOpcode() == Instruction::Add) {
4976           // ~(X-c) --> (-c-1)-X
4977           if (RHS->isAllOnesValue()) {
4978             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4979             return BinaryOperator::CreateSub(
4980                            ConstantExpr::getSub(NegOp0CI,
4981                                              ConstantInt::get(I.getType(), 1)),
4982                                           Op0I->getOperand(0));
4983           } else if (RHS->getValue().isSignBit()) {
4984             // (X + C) ^ signbit -> (X + C + signbit)
4985             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4986             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4987
4988           }
4989         } else if (Op0I->getOpcode() == Instruction::Or) {
4990           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4991           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4992             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4993             // Anything in both C1 and C2 is known to be zero, remove it from
4994             // NewRHS.
4995             Constant *CommonBits = And(Op0CI, RHS);
4996             NewRHS = ConstantExpr::getAnd(NewRHS, 
4997                                           ConstantExpr::getNot(CommonBits));
4998             AddToWorkList(Op0I);
4999             I.setOperand(0, Op0I->getOperand(0));
5000             I.setOperand(1, NewRHS);
5001             return &I;
5002           }
5003         }
5004       }
5005     }
5006
5007     // Try to fold constant and into select arguments.
5008     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5009       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5010         return R;
5011     if (isa<PHINode>(Op0))
5012       if (Instruction *NV = FoldOpIntoPhi(I))
5013         return NV;
5014   }
5015
5016   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5017     if (X == Op1)
5018       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5019
5020   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5021     if (X == Op0)
5022       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5023
5024   
5025   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5026   if (Op1I) {
5027     Value *A, *B;
5028     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5029       if (A == Op0) {              // B^(B|A) == (A|B)^B
5030         Op1I->swapOperands();
5031         I.swapOperands();
5032         std::swap(Op0, Op1);
5033       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5034         I.swapOperands();     // Simplified below.
5035         std::swap(Op0, Op1);
5036       }
5037     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5038       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5039     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5040       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5041     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5042       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5043         Op1I->swapOperands();
5044         std::swap(A, B);
5045       }
5046       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5047         I.swapOperands();     // Simplified below.
5048         std::swap(Op0, Op1);
5049       }
5050     }
5051   }
5052   
5053   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5054   if (Op0I) {
5055     Value *A, *B;
5056     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5057       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5058         std::swap(A, B);
5059       if (B == Op1) {                                // (A|B)^B == A & ~B
5060         Instruction *NotB =
5061           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5062         return BinaryOperator::CreateAnd(A, NotB);
5063       }
5064     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5065       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5066     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5067       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5068     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5069       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5070         std::swap(A, B);
5071       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5072           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5073         Instruction *N =
5074           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5075         return BinaryOperator::CreateAnd(N, Op1);
5076       }
5077     }
5078   }
5079   
5080   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5081   if (Op0I && Op1I && Op0I->isShift() && 
5082       Op0I->getOpcode() == Op1I->getOpcode() && 
5083       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5084       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5085     Instruction *NewOp =
5086       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5087                                                     Op1I->getOperand(0),
5088                                                     Op0I->getName()), I);
5089     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5090                                   Op1I->getOperand(1));
5091   }
5092     
5093   if (Op0I && Op1I) {
5094     Value *A, *B, *C, *D;
5095     // (A & B)^(A | B) -> A ^ B
5096     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5097         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5098       if ((A == C && B == D) || (A == D && B == C)) 
5099         return BinaryOperator::CreateXor(A, B);
5100     }
5101     // (A | B)^(A & B) -> A ^ B
5102     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5103         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5104       if ((A == C && B == D) || (A == D && B == C)) 
5105         return BinaryOperator::CreateXor(A, B);
5106     }
5107     
5108     // (A & B)^(C & D)
5109     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5110         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5111         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5112       // (X & Y)^(X & Y) -> (Y^Z) & X
5113       Value *X = 0, *Y = 0, *Z = 0;
5114       if (A == C)
5115         X = A, Y = B, Z = D;
5116       else if (A == D)
5117         X = A, Y = B, Z = C;
5118       else if (B == C)
5119         X = B, Y = A, Z = D;
5120       else if (B == D)
5121         X = B, Y = A, Z = C;
5122       
5123       if (X) {
5124         Instruction *NewOp =
5125         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5126         return BinaryOperator::CreateAnd(NewOp, X);
5127       }
5128     }
5129   }
5130     
5131   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5132   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5133     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5134       return R;
5135
5136   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5137   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5138     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5139       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5140         const Type *SrcTy = Op0C->getOperand(0)->getType();
5141         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5142             // Only do this if the casts both really cause code to be generated.
5143             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5144                               I.getType(), TD) &&
5145             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5146                               I.getType(), TD)) {
5147           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5148                                                          Op1C->getOperand(0),
5149                                                          I.getName());
5150           InsertNewInstBefore(NewOp, I);
5151           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5152         }
5153       }
5154   }
5155
5156   return Changed ? &I : 0;
5157 }
5158
5159 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5160 /// overflowed for this type.
5161 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5162                             ConstantInt *In2, bool IsSigned = false) {
5163   Result = cast<ConstantInt>(Add(In1, In2));
5164
5165   if (IsSigned)
5166     if (In2->getValue().isNegative())
5167       return Result->getValue().sgt(In1->getValue());
5168     else
5169       return Result->getValue().slt(In1->getValue());
5170   else
5171     return Result->getValue().ult(In1->getValue());
5172 }
5173
5174 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5175 /// overflowed for this type.
5176 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5177                             ConstantInt *In2, bool IsSigned = false) {
5178   Result = cast<ConstantInt>(Subtract(In1, In2));
5179
5180   if (IsSigned)
5181     if (In2->getValue().isNegative())
5182       return Result->getValue().slt(In1->getValue());
5183     else
5184       return Result->getValue().sgt(In1->getValue());
5185   else
5186     return Result->getValue().ugt(In1->getValue());
5187 }
5188
5189 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5190 /// code necessary to compute the offset from the base pointer (without adding
5191 /// in the base pointer).  Return the result as a signed integer of intptr size.
5192 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5193   TargetData &TD = IC.getTargetData();
5194   gep_type_iterator GTI = gep_type_begin(GEP);
5195   const Type *IntPtrTy = TD.getIntPtrType();
5196   Value *Result = Constant::getNullValue(IntPtrTy);
5197
5198   // Build a mask for high order bits.
5199   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5200   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5201
5202   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5203        ++i, ++GTI) {
5204     Value *Op = *i;
5205     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5206     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5207       if (OpC->isZero()) continue;
5208       
5209       // Handle a struct index, which adds its field offset to the pointer.
5210       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5211         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5212         
5213         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5214           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5215         else
5216           Result = IC.InsertNewInstBefore(
5217                    BinaryOperator::CreateAdd(Result,
5218                                              ConstantInt::get(IntPtrTy, Size),
5219                                              GEP->getName()+".offs"), I);
5220         continue;
5221       }
5222       
5223       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5224       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5225       Scale = ConstantExpr::getMul(OC, Scale);
5226       if (Constant *RC = dyn_cast<Constant>(Result))
5227         Result = ConstantExpr::getAdd(RC, Scale);
5228       else {
5229         // Emit an add instruction.
5230         Result = IC.InsertNewInstBefore(
5231            BinaryOperator::CreateAdd(Result, Scale,
5232                                      GEP->getName()+".offs"), I);
5233       }
5234       continue;
5235     }
5236     // Convert to correct type.
5237     if (Op->getType() != IntPtrTy) {
5238       if (Constant *OpC = dyn_cast<Constant>(Op))
5239         Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
5240       else
5241         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5242                                                                 true,
5243                                                       Op->getName()+".c"), I);
5244     }
5245     if (Size != 1) {
5246       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5247       if (Constant *OpC = dyn_cast<Constant>(Op))
5248         Op = ConstantExpr::getMul(OpC, Scale);
5249       else    // We'll let instcombine(mul) convert this to a shl if possible.
5250         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5251                                                   GEP->getName()+".idx"), I);
5252     }
5253
5254     // Emit an add instruction.
5255     if (isa<Constant>(Op) && isa<Constant>(Result))
5256       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5257                                     cast<Constant>(Result));
5258     else
5259       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5260                                                   GEP->getName()+".offs"), I);
5261   }
5262   return Result;
5263 }
5264
5265
5266 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5267 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5268 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5269 /// complex, and scales are involved.  The above expression would also be legal
5270 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5271 /// later form is less amenable to optimization though, and we are allowed to
5272 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5273 ///
5274 /// If we can't emit an optimized form for this expression, this returns null.
5275 /// 
5276 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5277                                           InstCombiner &IC) {
5278   TargetData &TD = IC.getTargetData();
5279   gep_type_iterator GTI = gep_type_begin(GEP);
5280
5281   // Check to see if this gep only has a single variable index.  If so, and if
5282   // any constant indices are a multiple of its scale, then we can compute this
5283   // in terms of the scale of the variable index.  For example, if the GEP
5284   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5285   // because the expression will cross zero at the same point.
5286   unsigned i, e = GEP->getNumOperands();
5287   int64_t Offset = 0;
5288   for (i = 1; i != e; ++i, ++GTI) {
5289     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5290       // Compute the aggregate offset of constant indices.
5291       if (CI->isZero()) continue;
5292
5293       // Handle a struct index, which adds its field offset to the pointer.
5294       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5295         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5296       } else {
5297         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5298         Offset += Size*CI->getSExtValue();
5299       }
5300     } else {
5301       // Found our variable index.
5302       break;
5303     }
5304   }
5305   
5306   // If there are no variable indices, we must have a constant offset, just
5307   // evaluate it the general way.
5308   if (i == e) return 0;
5309   
5310   Value *VariableIdx = GEP->getOperand(i);
5311   // Determine the scale factor of the variable element.  For example, this is
5312   // 4 if the variable index is into an array of i32.
5313   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5314   
5315   // Verify that there are no other variable indices.  If so, emit the hard way.
5316   for (++i, ++GTI; i != e; ++i, ++GTI) {
5317     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5318     if (!CI) return 0;
5319    
5320     // Compute the aggregate offset of constant indices.
5321     if (CI->isZero()) continue;
5322     
5323     // Handle a struct index, which adds its field offset to the pointer.
5324     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5325       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5326     } else {
5327       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5328       Offset += Size*CI->getSExtValue();
5329     }
5330   }
5331   
5332   // Okay, we know we have a single variable index, which must be a
5333   // pointer/array/vector index.  If there is no offset, life is simple, return
5334   // the index.
5335   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5336   if (Offset == 0) {
5337     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5338     // we don't need to bother extending: the extension won't affect where the
5339     // computation crosses zero.
5340     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5341       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5342                                   VariableIdx->getNameStart(), &I);
5343     return VariableIdx;
5344   }
5345   
5346   // Otherwise, there is an index.  The computation we will do will be modulo
5347   // the pointer size, so get it.
5348   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5349   
5350   Offset &= PtrSizeMask;
5351   VariableScale &= PtrSizeMask;
5352
5353   // To do this transformation, any constant index must be a multiple of the
5354   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5355   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5356   // multiple of the variable scale.
5357   int64_t NewOffs = Offset / (int64_t)VariableScale;
5358   if (Offset != NewOffs*(int64_t)VariableScale)
5359     return 0;
5360
5361   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5362   const Type *IntPtrTy = TD.getIntPtrType();
5363   if (VariableIdx->getType() != IntPtrTy)
5364     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5365                                               true /*SExt*/, 
5366                                               VariableIdx->getNameStart(), &I);
5367   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5368   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5369 }
5370
5371
5372 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5373 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5374 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5375                                        ICmpInst::Predicate Cond,
5376                                        Instruction &I) {
5377   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5378
5379   // Look through bitcasts.
5380   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5381     RHS = BCI->getOperand(0);
5382
5383   Value *PtrBase = GEPLHS->getOperand(0);
5384   if (PtrBase == RHS) {
5385     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5386     // This transformation (ignoring the base and scales) is valid because we
5387     // know pointers can't overflow.  See if we can output an optimized form.
5388     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5389     
5390     // If not, synthesize the offset the hard way.
5391     if (Offset == 0)
5392       Offset = EmitGEPOffset(GEPLHS, I, *this);
5393     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5394                         Constant::getNullValue(Offset->getType()));
5395   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5396     // If the base pointers are different, but the indices are the same, just
5397     // compare the base pointer.
5398     if (PtrBase != GEPRHS->getOperand(0)) {
5399       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5400       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5401                         GEPRHS->getOperand(0)->getType();
5402       if (IndicesTheSame)
5403         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5404           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5405             IndicesTheSame = false;
5406             break;
5407           }
5408
5409       // If all indices are the same, just compare the base pointers.
5410       if (IndicesTheSame)
5411         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5412                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5413
5414       // Otherwise, the base pointers are different and the indices are
5415       // different, bail out.
5416       return 0;
5417     }
5418
5419     // If one of the GEPs has all zero indices, recurse.
5420     bool AllZeros = true;
5421     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5422       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5423           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5424         AllZeros = false;
5425         break;
5426       }
5427     if (AllZeros)
5428       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5429                           ICmpInst::getSwappedPredicate(Cond), I);
5430
5431     // If the other GEP has all zero indices, recurse.
5432     AllZeros = true;
5433     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5434       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5435           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5436         AllZeros = false;
5437         break;
5438       }
5439     if (AllZeros)
5440       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5441
5442     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5443       // If the GEPs only differ by one index, compare it.
5444       unsigned NumDifferences = 0;  // Keep track of # differences.
5445       unsigned DiffOperand = 0;     // The operand that differs.
5446       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5447         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5448           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5449                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5450             // Irreconcilable differences.
5451             NumDifferences = 2;
5452             break;
5453           } else {
5454             if (NumDifferences++) break;
5455             DiffOperand = i;
5456           }
5457         }
5458
5459       if (NumDifferences == 0)   // SAME GEP?
5460         return ReplaceInstUsesWith(I, // No comparison is needed here.
5461                                    ConstantInt::get(Type::Int1Ty,
5462                                              ICmpInst::isTrueWhenEqual(Cond)));
5463
5464       else if (NumDifferences == 1) {
5465         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5466         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5467         // Make sure we do a signed comparison here.
5468         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5469       }
5470     }
5471
5472     // Only lower this if the icmp is the only user of the GEP or if we expect
5473     // the result to fold to a constant!
5474     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5475         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5476       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5477       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5478       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5479       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5480     }
5481   }
5482   return 0;
5483 }
5484
5485 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5486 ///
5487 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5488                                                 Instruction *LHSI,
5489                                                 Constant *RHSC) {
5490   if (!isa<ConstantFP>(RHSC)) return 0;
5491   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5492   
5493   // Get the width of the mantissa.  We don't want to hack on conversions that
5494   // might lose information from the integer, e.g. "i64 -> float"
5495   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5496   if (MantissaWidth == -1) return 0;  // Unknown.
5497   
5498   // Check to see that the input is converted from an integer type that is small
5499   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5500   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5501   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5502   
5503   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5504   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5505   if (LHSUnsigned)
5506     ++InputSize;
5507   
5508   // If the conversion would lose info, don't hack on this.
5509   if ((int)InputSize > MantissaWidth)
5510     return 0;
5511   
5512   // Otherwise, we can potentially simplify the comparison.  We know that it
5513   // will always come through as an integer value and we know the constant is
5514   // not a NAN (it would have been previously simplified).
5515   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5516   
5517   ICmpInst::Predicate Pred;
5518   switch (I.getPredicate()) {
5519   default: assert(0 && "Unexpected predicate!");
5520   case FCmpInst::FCMP_UEQ:
5521   case FCmpInst::FCMP_OEQ:
5522     Pred = ICmpInst::ICMP_EQ;
5523     break;
5524   case FCmpInst::FCMP_UGT:
5525   case FCmpInst::FCMP_OGT:
5526     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5527     break;
5528   case FCmpInst::FCMP_UGE:
5529   case FCmpInst::FCMP_OGE:
5530     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5531     break;
5532   case FCmpInst::FCMP_ULT:
5533   case FCmpInst::FCMP_OLT:
5534     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5535     break;
5536   case FCmpInst::FCMP_ULE:
5537   case FCmpInst::FCMP_OLE:
5538     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5539     break;
5540   case FCmpInst::FCMP_UNE:
5541   case FCmpInst::FCMP_ONE:
5542     Pred = ICmpInst::ICMP_NE;
5543     break;
5544   case FCmpInst::FCMP_ORD:
5545     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5546   case FCmpInst::FCMP_UNO:
5547     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5548   }
5549   
5550   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5551   
5552   // Now we know that the APFloat is a normal number, zero or inf.
5553   
5554   // See if the FP constant is too large for the integer.  For example,
5555   // comparing an i8 to 300.0.
5556   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5557   
5558   if (!LHSUnsigned) {
5559     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5560     // and large values.
5561     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5562     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5563                           APFloat::rmNearestTiesToEven);
5564     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5565       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5566           Pred == ICmpInst::ICMP_SLE)
5567         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5568       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5569     }
5570   } else {
5571     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5572     // +INF and large values.
5573     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5574     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5575                           APFloat::rmNearestTiesToEven);
5576     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5577       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5578           Pred == ICmpInst::ICMP_ULE)
5579         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5580       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5581     }
5582   }
5583   
5584   if (!LHSUnsigned) {
5585     // See if the RHS value is < SignedMin.
5586     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5587     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5588                           APFloat::rmNearestTiesToEven);
5589     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5590       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5591           Pred == ICmpInst::ICMP_SGE)
5592         return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5593       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5594     }
5595   }
5596
5597   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5598   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5599   // casting the FP value to the integer value and back, checking for equality.
5600   // Don't do this for zero, because -0.0 is not fractional.
5601   Constant *RHSInt = LHSUnsigned
5602     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5603     : ConstantExpr::getFPToSI(RHSC, IntTy);
5604   if (!RHS.isZero()) {
5605     bool Equal = LHSUnsigned
5606       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5607       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5608     if (!Equal) {
5609       // If we had a comparison against a fractional value, we have to adjust
5610       // the compare predicate and sometimes the value.  RHSC is rounded towards
5611       // zero at this point.
5612       switch (Pred) {
5613       default: assert(0 && "Unexpected integer comparison!");
5614       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5615         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5616       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5617         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5618       case ICmpInst::ICMP_ULE:
5619         // (float)int <= 4.4   --> int <= 4
5620         // (float)int <= -4.4  --> false
5621         if (RHS.isNegative())
5622           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5623         break;
5624       case ICmpInst::ICMP_SLE:
5625         // (float)int <= 4.4   --> int <= 4
5626         // (float)int <= -4.4  --> int < -4
5627         if (RHS.isNegative())
5628           Pred = ICmpInst::ICMP_SLT;
5629         break;
5630       case ICmpInst::ICMP_ULT:
5631         // (float)int < -4.4   --> false
5632         // (float)int < 4.4    --> int <= 4
5633         if (RHS.isNegative())
5634           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5635         Pred = ICmpInst::ICMP_ULE;
5636         break;
5637       case ICmpInst::ICMP_SLT:
5638         // (float)int < -4.4   --> int < -4
5639         // (float)int < 4.4    --> int <= 4
5640         if (!RHS.isNegative())
5641           Pred = ICmpInst::ICMP_SLE;
5642         break;
5643       case ICmpInst::ICMP_UGT:
5644         // (float)int > 4.4    --> int > 4
5645         // (float)int > -4.4   --> true
5646         if (RHS.isNegative())
5647           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5648         break;
5649       case ICmpInst::ICMP_SGT:
5650         // (float)int > 4.4    --> int > 4
5651         // (float)int > -4.4   --> int >= -4
5652         if (RHS.isNegative())
5653           Pred = ICmpInst::ICMP_SGE;
5654         break;
5655       case ICmpInst::ICMP_UGE:
5656         // (float)int >= -4.4   --> true
5657         // (float)int >= 4.4    --> int > 4
5658         if (!RHS.isNegative())
5659           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5660         Pred = ICmpInst::ICMP_UGT;
5661         break;
5662       case ICmpInst::ICMP_SGE:
5663         // (float)int >= -4.4   --> int >= -4
5664         // (float)int >= 4.4    --> int > 4
5665         if (!RHS.isNegative())
5666           Pred = ICmpInst::ICMP_SGT;
5667         break;
5668       }
5669     }
5670   }
5671
5672   // Lower this FP comparison into an appropriate integer version of the
5673   // comparison.
5674   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5675 }
5676
5677 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5678   bool Changed = SimplifyCompare(I);
5679   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5680
5681   // Fold trivial predicates.
5682   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5683     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5684   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5685     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5686   
5687   // Simplify 'fcmp pred X, X'
5688   if (Op0 == Op1) {
5689     switch (I.getPredicate()) {
5690     default: assert(0 && "Unknown predicate!");
5691     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5692     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5693     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5694       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5695     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5696     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5697     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5698       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5699       
5700     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5701     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5702     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5703     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5704       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5705       I.setPredicate(FCmpInst::FCMP_UNO);
5706       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5707       return &I;
5708       
5709     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5710     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5711     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5712     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5713       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5714       I.setPredicate(FCmpInst::FCMP_ORD);
5715       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5716       return &I;
5717     }
5718   }
5719     
5720   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5721     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5722
5723   // Handle fcmp with constant RHS
5724   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5725     // If the constant is a nan, see if we can fold the comparison based on it.
5726     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5727       if (CFP->getValueAPF().isNaN()) {
5728         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5729           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5730         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5731                "Comparison must be either ordered or unordered!");
5732         // True if unordered.
5733         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5734       }
5735     }
5736     
5737     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5738       switch (LHSI->getOpcode()) {
5739       case Instruction::PHI:
5740         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5741         // block.  If in the same block, we're encouraging jump threading.  If
5742         // not, we are just pessimizing the code by making an i1 phi.
5743         if (LHSI->getParent() == I.getParent())
5744           if (Instruction *NV = FoldOpIntoPhi(I))
5745             return NV;
5746         break;
5747       case Instruction::SIToFP:
5748       case Instruction::UIToFP:
5749         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5750           return NV;
5751         break;
5752       case Instruction::Select:
5753         // If either operand of the select is a constant, we can fold the
5754         // comparison into the select arms, which will cause one to be
5755         // constant folded and the select turned into a bitwise or.
5756         Value *Op1 = 0, *Op2 = 0;
5757         if (LHSI->hasOneUse()) {
5758           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5759             // Fold the known value into the constant operand.
5760             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5761             // Insert a new FCmp of the other select operand.
5762             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5763                                                       LHSI->getOperand(2), RHSC,
5764                                                       I.getName()), I);
5765           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5766             // Fold the known value into the constant operand.
5767             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5768             // Insert a new FCmp of the other select operand.
5769             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5770                                                       LHSI->getOperand(1), RHSC,
5771                                                       I.getName()), I);
5772           }
5773         }
5774
5775         if (Op1)
5776           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5777         break;
5778       }
5779   }
5780
5781   return Changed ? &I : 0;
5782 }
5783
5784 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5785   bool Changed = SimplifyCompare(I);
5786   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5787   const Type *Ty = Op0->getType();
5788
5789   // icmp X, X
5790   if (Op0 == Op1)
5791     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5792                                                    I.isTrueWhenEqual()));
5793
5794   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5795     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5796   
5797   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5798   // addresses never equal each other!  We already know that Op0 != Op1.
5799   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5800        isa<ConstantPointerNull>(Op0)) &&
5801       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5802        isa<ConstantPointerNull>(Op1)))
5803     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5804                                                    !I.isTrueWhenEqual()));
5805
5806   // icmp's with boolean values can always be turned into bitwise operations
5807   if (Ty == Type::Int1Ty) {
5808     switch (I.getPredicate()) {
5809     default: assert(0 && "Invalid icmp instruction!");
5810     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5811       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5812       InsertNewInstBefore(Xor, I);
5813       return BinaryOperator::CreateNot(Xor);
5814     }
5815     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5816       return BinaryOperator::CreateXor(Op0, Op1);
5817
5818     case ICmpInst::ICMP_UGT:
5819       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5820       // FALL THROUGH
5821     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5822       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5823       InsertNewInstBefore(Not, I);
5824       return BinaryOperator::CreateAnd(Not, Op1);
5825     }
5826     case ICmpInst::ICMP_SGT:
5827       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5828       // FALL THROUGH
5829     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5830       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5831       InsertNewInstBefore(Not, I);
5832       return BinaryOperator::CreateAnd(Not, Op0);
5833     }
5834     case ICmpInst::ICMP_UGE:
5835       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5836       // FALL THROUGH
5837     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5838       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5839       InsertNewInstBefore(Not, I);
5840       return BinaryOperator::CreateOr(Not, Op1);
5841     }
5842     case ICmpInst::ICMP_SGE:
5843       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5844       // FALL THROUGH
5845     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5846       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5847       InsertNewInstBefore(Not, I);
5848       return BinaryOperator::CreateOr(Not, Op0);
5849     }
5850     }
5851   }
5852
5853   unsigned BitWidth = 0;
5854   if (TD)
5855     BitWidth = TD->getTypeSizeInBits(Ty);
5856   else if (isa<IntegerType>(Ty))
5857     BitWidth = Ty->getPrimitiveSizeInBits();
5858
5859   bool isSignBit = false;
5860
5861   // See if we are doing a comparison with a constant.
5862   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5863     Value *A = 0, *B = 0;
5864     
5865     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5866     if (I.isEquality() && CI->isNullValue() &&
5867         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5868       // (icmp cond A B) if cond is equality
5869       return new ICmpInst(I.getPredicate(), A, B);
5870     }
5871     
5872     // If we have an icmp le or icmp ge instruction, turn it into the
5873     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5874     // them being folded in the code below.
5875     switch (I.getPredicate()) {
5876     default: break;
5877     case ICmpInst::ICMP_ULE:
5878       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5879         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5880       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5881     case ICmpInst::ICMP_SLE:
5882       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5883         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5884       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5885     case ICmpInst::ICMP_UGE:
5886       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5887         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5888       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5889     case ICmpInst::ICMP_SGE:
5890       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5891         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5892       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5893     }
5894     
5895     // If this comparison is a normal comparison, it demands all
5896     // bits, if it is a sign bit comparison, it only demands the sign bit.
5897     bool UnusedBit;
5898     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5899   }
5900
5901   // See if we can fold the comparison based on range information we can get
5902   // by checking whether bits are known to be zero or one in the input.
5903   if (BitWidth != 0) {
5904     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
5905     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
5906
5907     if (SimplifyDemandedBits(I.getOperandUse(0),
5908                              isSignBit ? APInt::getSignBit(BitWidth)
5909                                        : APInt::getAllOnesValue(BitWidth),
5910                              Op0KnownZero, Op0KnownOne, 0))
5911       return &I;
5912     if (SimplifyDemandedBits(I.getOperandUse(1),
5913                              APInt::getAllOnesValue(BitWidth),
5914                              Op1KnownZero, Op1KnownOne, 0))
5915       return &I;
5916
5917     // Given the known and unknown bits, compute a range that the LHS could be
5918     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5919     // EQ and NE we use unsigned values.
5920     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
5921     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
5922     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5923       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
5924                                              Op0Min, Op0Max);
5925       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
5926                                              Op1Min, Op1Max);
5927     } else {
5928       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
5929                                                Op0Min, Op0Max);
5930       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
5931                                                Op1Min, Op1Max);
5932     }
5933
5934     // If Min and Max are known to be the same, then SimplifyDemandedBits
5935     // figured out that the LHS is a constant.  Just constant fold this now so
5936     // that code below can assume that Min != Max.
5937     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
5938       return new ICmpInst(I.getPredicate(), ConstantInt::get(Op0Min), Op1);
5939     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
5940       return new ICmpInst(I.getPredicate(), Op0, ConstantInt::get(Op1Min));
5941
5942     // Based on the range information we know about the LHS, see if we can
5943     // simplify this comparison.  For example, (x&4) < 8  is always true.
5944     switch (I.getPredicate()) {
5945     default: assert(0 && "Unknown icmp opcode!");
5946     case ICmpInst::ICMP_EQ:
5947       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
5948         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5949       break;
5950     case ICmpInst::ICMP_NE:
5951       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
5952         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5953       break;
5954     case ICmpInst::ICMP_ULT:
5955       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
5956         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5957       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
5958         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5959       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
5960         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5961       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5962         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
5963           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5964
5965         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5966         if (CI->isMinValue(true))
5967           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5968                             ConstantInt::getAllOnesValue(Op0->getType()));
5969       }
5970       break;
5971     case ICmpInst::ICMP_UGT:
5972       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
5973         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5974       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
5975         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5976
5977       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
5978         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5979       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5980         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
5981           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5982
5983         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5984         if (CI->isMaxValue(true))
5985           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5986                               ConstantInt::getNullValue(Op0->getType()));
5987       }
5988       break;
5989     case ICmpInst::ICMP_SLT:
5990       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
5991         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5992       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
5993         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5994       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
5995         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5996       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5997         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
5998           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5999       }
6000       break;
6001     case ICmpInst::ICMP_SGT:
6002       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6003         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6004       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6005         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6006
6007       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6008         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6009       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6010         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6011           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6012       }
6013       break;
6014     case ICmpInst::ICMP_SGE:
6015       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6016       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6017         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6018       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6019         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6020       break;
6021     case ICmpInst::ICMP_SLE:
6022       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6023       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6024         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6025       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6026         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6027       break;
6028     case ICmpInst::ICMP_UGE:
6029       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6030       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6031         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6032       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6033         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6034       break;
6035     case ICmpInst::ICMP_ULE:
6036       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6037       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6038         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6039       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6040         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6041       break;
6042     }
6043
6044     // Turn a signed comparison into an unsigned one if both operands
6045     // are known to have the same sign.
6046     if (I.isSignedPredicate() &&
6047         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6048          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6049       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6050   }
6051
6052   // Test if the ICmpInst instruction is used exclusively by a select as
6053   // part of a minimum or maximum operation. If so, refrain from doing
6054   // any other folding. This helps out other analyses which understand
6055   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6056   // and CodeGen. And in this case, at least one of the comparison
6057   // operands has at least one user besides the compare (the select),
6058   // which would often largely negate the benefit of folding anyway.
6059   if (I.hasOneUse())
6060     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6061       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6062           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6063         return 0;
6064
6065   // See if we are doing a comparison between a constant and an instruction that
6066   // can be folded into the comparison.
6067   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6068     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6069     // instruction, see if that instruction also has constants so that the 
6070     // instruction can be folded into the icmp 
6071     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6072       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6073         return Res;
6074   }
6075
6076   // Handle icmp with constant (but not simple integer constant) RHS
6077   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6078     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6079       switch (LHSI->getOpcode()) {
6080       case Instruction::GetElementPtr:
6081         if (RHSC->isNullValue()) {
6082           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6083           bool isAllZeros = true;
6084           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6085             if (!isa<Constant>(LHSI->getOperand(i)) ||
6086                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6087               isAllZeros = false;
6088               break;
6089             }
6090           if (isAllZeros)
6091             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6092                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6093         }
6094         break;
6095
6096       case Instruction::PHI:
6097         // Only fold icmp into the PHI if the phi and fcmp are in the same
6098         // block.  If in the same block, we're encouraging jump threading.  If
6099         // not, we are just pessimizing the code by making an i1 phi.
6100         if (LHSI->getParent() == I.getParent())
6101           if (Instruction *NV = FoldOpIntoPhi(I))
6102             return NV;
6103         break;
6104       case Instruction::Select: {
6105         // If either operand of the select is a constant, we can fold the
6106         // comparison into the select arms, which will cause one to be
6107         // constant folded and the select turned into a bitwise or.
6108         Value *Op1 = 0, *Op2 = 0;
6109         if (LHSI->hasOneUse()) {
6110           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6111             // Fold the known value into the constant operand.
6112             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6113             // Insert a new ICmp of the other select operand.
6114             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6115                                                    LHSI->getOperand(2), RHSC,
6116                                                    I.getName()), I);
6117           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6118             // Fold the known value into the constant operand.
6119             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6120             // Insert a new ICmp of the other select operand.
6121             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6122                                                    LHSI->getOperand(1), RHSC,
6123                                                    I.getName()), I);
6124           }
6125         }
6126
6127         if (Op1)
6128           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6129         break;
6130       }
6131       case Instruction::Malloc:
6132         // If we have (malloc != null), and if the malloc has a single use, we
6133         // can assume it is successful and remove the malloc.
6134         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6135           AddToWorkList(LHSI);
6136           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6137                                                          !I.isTrueWhenEqual()));
6138         }
6139         break;
6140       }
6141   }
6142
6143   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6144   if (User *GEP = dyn_castGetElementPtr(Op0))
6145     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6146       return NI;
6147   if (User *GEP = dyn_castGetElementPtr(Op1))
6148     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6149                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6150       return NI;
6151
6152   // Test to see if the operands of the icmp are casted versions of other
6153   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6154   // now.
6155   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6156     if (isa<PointerType>(Op0->getType()) && 
6157         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6158       // We keep moving the cast from the left operand over to the right
6159       // operand, where it can often be eliminated completely.
6160       Op0 = CI->getOperand(0);
6161
6162       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6163       // so eliminate it as well.
6164       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6165         Op1 = CI2->getOperand(0);
6166
6167       // If Op1 is a constant, we can fold the cast into the constant.
6168       if (Op0->getType() != Op1->getType()) {
6169         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6170           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6171         } else {
6172           // Otherwise, cast the RHS right before the icmp
6173           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6174         }
6175       }
6176       return new ICmpInst(I.getPredicate(), Op0, Op1);
6177     }
6178   }
6179   
6180   if (isa<CastInst>(Op0)) {
6181     // Handle the special case of: icmp (cast bool to X), <cst>
6182     // This comes up when you have code like
6183     //   int X = A < B;
6184     //   if (X) ...
6185     // For generality, we handle any zero-extension of any operand comparison
6186     // with a constant or another cast from the same type.
6187     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6188       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6189         return R;
6190   }
6191   
6192   // See if it's the same type of instruction on the left and right.
6193   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6194     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6195       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6196           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6197         switch (Op0I->getOpcode()) {
6198         default: break;
6199         case Instruction::Add:
6200         case Instruction::Sub:
6201         case Instruction::Xor:
6202           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6203             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6204                                 Op1I->getOperand(0));
6205           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6206           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6207             if (CI->getValue().isSignBit()) {
6208               ICmpInst::Predicate Pred = I.isSignedPredicate()
6209                                              ? I.getUnsignedPredicate()
6210                                              : I.getSignedPredicate();
6211               return new ICmpInst(Pred, Op0I->getOperand(0),
6212                                   Op1I->getOperand(0));
6213             }
6214             
6215             if (CI->getValue().isMaxSignedValue()) {
6216               ICmpInst::Predicate Pred = I.isSignedPredicate()
6217                                              ? I.getUnsignedPredicate()
6218                                              : I.getSignedPredicate();
6219               Pred = I.getSwappedPredicate(Pred);
6220               return new ICmpInst(Pred, Op0I->getOperand(0),
6221                                   Op1I->getOperand(0));
6222             }
6223           }
6224           break;
6225         case Instruction::Mul:
6226           if (!I.isEquality())
6227             break;
6228
6229           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6230             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6231             // Mask = -1 >> count-trailing-zeros(Cst).
6232             if (!CI->isZero() && !CI->isOne()) {
6233               const APInt &AP = CI->getValue();
6234               ConstantInt *Mask = ConstantInt::get(
6235                                       APInt::getLowBitsSet(AP.getBitWidth(),
6236                                                            AP.getBitWidth() -
6237                                                       AP.countTrailingZeros()));
6238               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6239                                                             Mask);
6240               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6241                                                             Mask);
6242               InsertNewInstBefore(And1, I);
6243               InsertNewInstBefore(And2, I);
6244               return new ICmpInst(I.getPredicate(), And1, And2);
6245             }
6246           }
6247           break;
6248         }
6249       }
6250     }
6251   }
6252   
6253   // ~x < ~y --> y < x
6254   { Value *A, *B;
6255     if (match(Op0, m_Not(m_Value(A))) &&
6256         match(Op1, m_Not(m_Value(B))))
6257       return new ICmpInst(I.getPredicate(), B, A);
6258   }
6259   
6260   if (I.isEquality()) {
6261     Value *A, *B, *C, *D;
6262     
6263     // -x == -y --> x == y
6264     if (match(Op0, m_Neg(m_Value(A))) &&
6265         match(Op1, m_Neg(m_Value(B))))
6266       return new ICmpInst(I.getPredicate(), A, B);
6267     
6268     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6269       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6270         Value *OtherVal = A == Op1 ? B : A;
6271         return new ICmpInst(I.getPredicate(), OtherVal,
6272                             Constant::getNullValue(A->getType()));
6273       }
6274
6275       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6276         // A^c1 == C^c2 --> A == C^(c1^c2)
6277         ConstantInt *C1, *C2;
6278         if (match(B, m_ConstantInt(C1)) &&
6279             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6280           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6281           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6282           return new ICmpInst(I.getPredicate(), A,
6283                               InsertNewInstBefore(Xor, I));
6284         }
6285         
6286         // A^B == A^D -> B == D
6287         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6288         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6289         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6290         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6291       }
6292     }
6293     
6294     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6295         (A == Op0 || B == Op0)) {
6296       // A == (A^B)  ->  B == 0
6297       Value *OtherVal = A == Op0 ? B : A;
6298       return new ICmpInst(I.getPredicate(), OtherVal,
6299                           Constant::getNullValue(A->getType()));
6300     }
6301
6302     // (A-B) == A  ->  B == 0
6303     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6304       return new ICmpInst(I.getPredicate(), B, 
6305                           Constant::getNullValue(B->getType()));
6306
6307     // A == (A-B)  ->  B == 0
6308     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6309       return new ICmpInst(I.getPredicate(), B,
6310                           Constant::getNullValue(B->getType()));
6311     
6312     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6313     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6314         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6315         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6316       Value *X = 0, *Y = 0, *Z = 0;
6317       
6318       if (A == C) {
6319         X = B; Y = D; Z = A;
6320       } else if (A == D) {
6321         X = B; Y = C; Z = A;
6322       } else if (B == C) {
6323         X = A; Y = D; Z = B;
6324       } else if (B == D) {
6325         X = A; Y = C; Z = B;
6326       }
6327       
6328       if (X) {   // Build (X^Y) & Z
6329         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6330         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6331         I.setOperand(0, Op1);
6332         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6333         return &I;
6334       }
6335     }
6336   }
6337   return Changed ? &I : 0;
6338 }
6339
6340
6341 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6342 /// and CmpRHS are both known to be integer constants.
6343 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6344                                           ConstantInt *DivRHS) {
6345   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6346   const APInt &CmpRHSV = CmpRHS->getValue();
6347   
6348   // FIXME: If the operand types don't match the type of the divide 
6349   // then don't attempt this transform. The code below doesn't have the
6350   // logic to deal with a signed divide and an unsigned compare (and
6351   // vice versa). This is because (x /s C1) <s C2  produces different 
6352   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6353   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6354   // work. :(  The if statement below tests that condition and bails 
6355   // if it finds it. 
6356   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6357   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6358     return 0;
6359   if (DivRHS->isZero())
6360     return 0; // The ProdOV computation fails on divide by zero.
6361   if (DivIsSigned && DivRHS->isAllOnesValue())
6362     return 0; // The overflow computation also screws up here
6363   if (DivRHS->isOne())
6364     return 0; // Not worth bothering, and eliminates some funny cases
6365               // with INT_MIN.
6366
6367   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6368   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6369   // C2 (CI). By solving for X we can turn this into a range check 
6370   // instead of computing a divide. 
6371   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6372
6373   // Determine if the product overflows by seeing if the product is
6374   // not equal to the divide. Make sure we do the same kind of divide
6375   // as in the LHS instruction that we're folding. 
6376   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6377                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6378
6379   // Get the ICmp opcode
6380   ICmpInst::Predicate Pred = ICI.getPredicate();
6381
6382   // Figure out the interval that is being checked.  For example, a comparison
6383   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6384   // Compute this interval based on the constants involved and the signedness of
6385   // the compare/divide.  This computes a half-open interval, keeping track of
6386   // whether either value in the interval overflows.  After analysis each
6387   // overflow variable is set to 0 if it's corresponding bound variable is valid
6388   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6389   int LoOverflow = 0, HiOverflow = 0;
6390   ConstantInt *LoBound = 0, *HiBound = 0;
6391   
6392   if (!DivIsSigned) {  // udiv
6393     // e.g. X/5 op 3  --> [15, 20)
6394     LoBound = Prod;
6395     HiOverflow = LoOverflow = ProdOV;
6396     if (!HiOverflow)
6397       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6398   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6399     if (CmpRHSV == 0) {       // (X / pos) op 0
6400       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6401       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6402       HiBound = DivRHS;
6403     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6404       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6405       HiOverflow = LoOverflow = ProdOV;
6406       if (!HiOverflow)
6407         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6408     } else {                       // (X / pos) op neg
6409       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6410       HiBound = AddOne(Prod);
6411       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6412       if (!LoOverflow) {
6413         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6414         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6415                                      true) ? -1 : 0;
6416        }
6417     }
6418   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6419     if (CmpRHSV == 0) {       // (X / neg) op 0
6420       // e.g. X/-5 op 0  --> [-4, 5)
6421       LoBound = AddOne(DivRHS);
6422       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6423       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6424         HiOverflow = 1;            // [INTMIN+1, overflow)
6425         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6426       }
6427     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6428       // e.g. X/-5 op 3  --> [-19, -14)
6429       HiBound = AddOne(Prod);
6430       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6431       if (!LoOverflow)
6432         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6433     } else {                       // (X / neg) op neg
6434       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6435       LoOverflow = HiOverflow = ProdOV;
6436       if (!HiOverflow)
6437         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6438     }
6439     
6440     // Dividing by a negative swaps the condition.  LT <-> GT
6441     Pred = ICmpInst::getSwappedPredicate(Pred);
6442   }
6443
6444   Value *X = DivI->getOperand(0);
6445   switch (Pred) {
6446   default: assert(0 && "Unhandled icmp opcode!");
6447   case ICmpInst::ICMP_EQ:
6448     if (LoOverflow && HiOverflow)
6449       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6450     else if (HiOverflow)
6451       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6452                           ICmpInst::ICMP_UGE, X, LoBound);
6453     else if (LoOverflow)
6454       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6455                           ICmpInst::ICMP_ULT, X, HiBound);
6456     else
6457       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6458   case ICmpInst::ICMP_NE:
6459     if (LoOverflow && HiOverflow)
6460       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6461     else if (HiOverflow)
6462       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6463                           ICmpInst::ICMP_ULT, X, LoBound);
6464     else if (LoOverflow)
6465       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6466                           ICmpInst::ICMP_UGE, X, HiBound);
6467     else
6468       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6469   case ICmpInst::ICMP_ULT:
6470   case ICmpInst::ICMP_SLT:
6471     if (LoOverflow == +1)   // Low bound is greater than input range.
6472       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6473     if (LoOverflow == -1)   // Low bound is less than input range.
6474       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6475     return new ICmpInst(Pred, X, LoBound);
6476   case ICmpInst::ICMP_UGT:
6477   case ICmpInst::ICMP_SGT:
6478     if (HiOverflow == +1)       // High bound greater than input range.
6479       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6480     else if (HiOverflow == -1)  // High bound less than input range.
6481       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6482     if (Pred == ICmpInst::ICMP_UGT)
6483       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6484     else
6485       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6486   }
6487 }
6488
6489
6490 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6491 ///
6492 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6493                                                           Instruction *LHSI,
6494                                                           ConstantInt *RHS) {
6495   const APInt &RHSV = RHS->getValue();
6496   
6497   switch (LHSI->getOpcode()) {
6498   case Instruction::Trunc:
6499     if (ICI.isEquality() && LHSI->hasOneUse()) {
6500       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6501       // of the high bits truncated out of x are known.
6502       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6503              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6504       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6505       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6506       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6507       
6508       // If all the high bits are known, we can do this xform.
6509       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6510         // Pull in the high bits from known-ones set.
6511         APInt NewRHS(RHS->getValue());
6512         NewRHS.zext(SrcBits);
6513         NewRHS |= KnownOne;
6514         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6515                             ConstantInt::get(NewRHS));
6516       }
6517     }
6518     break;
6519       
6520   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6521     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6522       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6523       // fold the xor.
6524       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6525           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6526         Value *CompareVal = LHSI->getOperand(0);
6527         
6528         // If the sign bit of the XorCST is not set, there is no change to
6529         // the operation, just stop using the Xor.
6530         if (!XorCST->getValue().isNegative()) {
6531           ICI.setOperand(0, CompareVal);
6532           AddToWorkList(LHSI);
6533           return &ICI;
6534         }
6535         
6536         // Was the old condition true if the operand is positive?
6537         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6538         
6539         // If so, the new one isn't.
6540         isTrueIfPositive ^= true;
6541         
6542         if (isTrueIfPositive)
6543           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6544         else
6545           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6546       }
6547
6548       if (LHSI->hasOneUse()) {
6549         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6550         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6551           const APInt &SignBit = XorCST->getValue();
6552           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6553                                          ? ICI.getUnsignedPredicate()
6554                                          : ICI.getSignedPredicate();
6555           return new ICmpInst(Pred, LHSI->getOperand(0),
6556                               ConstantInt::get(RHSV ^ SignBit));
6557         }
6558
6559         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6560         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6561           const APInt &NotSignBit = XorCST->getValue();
6562           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6563                                          ? ICI.getUnsignedPredicate()
6564                                          : ICI.getSignedPredicate();
6565           Pred = ICI.getSwappedPredicate(Pred);
6566           return new ICmpInst(Pred, LHSI->getOperand(0),
6567                               ConstantInt::get(RHSV ^ NotSignBit));
6568         }
6569       }
6570     }
6571     break;
6572   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6573     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6574         LHSI->getOperand(0)->hasOneUse()) {
6575       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6576       
6577       // If the LHS is an AND of a truncating cast, we can widen the
6578       // and/compare to be the input width without changing the value
6579       // produced, eliminating a cast.
6580       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6581         // We can do this transformation if either the AND constant does not
6582         // have its sign bit set or if it is an equality comparison. 
6583         // Extending a relational comparison when we're checking the sign
6584         // bit would not work.
6585         if (Cast->hasOneUse() &&
6586             (ICI.isEquality() ||
6587              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6588           uint32_t BitWidth = 
6589             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6590           APInt NewCST = AndCST->getValue();
6591           NewCST.zext(BitWidth);
6592           APInt NewCI = RHSV;
6593           NewCI.zext(BitWidth);
6594           Instruction *NewAnd = 
6595             BinaryOperator::CreateAnd(Cast->getOperand(0),
6596                                       ConstantInt::get(NewCST),LHSI->getName());
6597           InsertNewInstBefore(NewAnd, ICI);
6598           return new ICmpInst(ICI.getPredicate(), NewAnd,
6599                               ConstantInt::get(NewCI));
6600         }
6601       }
6602       
6603       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6604       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6605       // happens a LOT in code produced by the C front-end, for bitfield
6606       // access.
6607       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6608       if (Shift && !Shift->isShift())
6609         Shift = 0;
6610       
6611       ConstantInt *ShAmt;
6612       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6613       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6614       const Type *AndTy = AndCST->getType();          // Type of the and.
6615       
6616       // We can fold this as long as we can't shift unknown bits
6617       // into the mask.  This can only happen with signed shift
6618       // rights, as they sign-extend.
6619       if (ShAmt) {
6620         bool CanFold = Shift->isLogicalShift();
6621         if (!CanFold) {
6622           // To test for the bad case of the signed shr, see if any
6623           // of the bits shifted in could be tested after the mask.
6624           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6625           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6626           
6627           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6628           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6629                AndCST->getValue()) == 0)
6630             CanFold = true;
6631         }
6632         
6633         if (CanFold) {
6634           Constant *NewCst;
6635           if (Shift->getOpcode() == Instruction::Shl)
6636             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6637           else
6638             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6639           
6640           // Check to see if we are shifting out any of the bits being
6641           // compared.
6642           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6643             // If we shifted bits out, the fold is not going to work out.
6644             // As a special case, check to see if this means that the
6645             // result is always true or false now.
6646             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6647               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6648             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6649               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6650           } else {
6651             ICI.setOperand(1, NewCst);
6652             Constant *NewAndCST;
6653             if (Shift->getOpcode() == Instruction::Shl)
6654               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6655             else
6656               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6657             LHSI->setOperand(1, NewAndCST);
6658             LHSI->setOperand(0, Shift->getOperand(0));
6659             AddToWorkList(Shift); // Shift is dead.
6660             AddUsesToWorkList(ICI);
6661             return &ICI;
6662           }
6663         }
6664       }
6665       
6666       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6667       // preferable because it allows the C<<Y expression to be hoisted out
6668       // of a loop if Y is invariant and X is not.
6669       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6670           ICI.isEquality() && !Shift->isArithmeticShift() &&
6671           !isa<Constant>(Shift->getOperand(0))) {
6672         // Compute C << Y.
6673         Value *NS;
6674         if (Shift->getOpcode() == Instruction::LShr) {
6675           NS = BinaryOperator::CreateShl(AndCST, 
6676                                          Shift->getOperand(1), "tmp");
6677         } else {
6678           // Insert a logical shift.
6679           NS = BinaryOperator::CreateLShr(AndCST,
6680                                           Shift->getOperand(1), "tmp");
6681         }
6682         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6683         
6684         // Compute X & (C << Y).
6685         Instruction *NewAnd = 
6686           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6687         InsertNewInstBefore(NewAnd, ICI);
6688         
6689         ICI.setOperand(0, NewAnd);
6690         return &ICI;
6691       }
6692     }
6693     break;
6694     
6695   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6696     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6697     if (!ShAmt) break;
6698     
6699     uint32_t TypeBits = RHSV.getBitWidth();
6700     
6701     // Check that the shift amount is in range.  If not, don't perform
6702     // undefined shifts.  When the shift is visited it will be
6703     // simplified.
6704     if (ShAmt->uge(TypeBits))
6705       break;
6706     
6707     if (ICI.isEquality()) {
6708       // If we are comparing against bits always shifted out, the
6709       // comparison cannot succeed.
6710       Constant *Comp =
6711         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6712       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6713         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6714         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6715         return ReplaceInstUsesWith(ICI, Cst);
6716       }
6717       
6718       if (LHSI->hasOneUse()) {
6719         // Otherwise strength reduce the shift into an and.
6720         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6721         Constant *Mask =
6722           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6723         
6724         Instruction *AndI =
6725           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6726                                     Mask, LHSI->getName()+".mask");
6727         Value *And = InsertNewInstBefore(AndI, ICI);
6728         return new ICmpInst(ICI.getPredicate(), And,
6729                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6730       }
6731     }
6732     
6733     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6734     bool TrueIfSigned = false;
6735     if (LHSI->hasOneUse() &&
6736         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6737       // (X << 31) <s 0  --> (X&1) != 0
6738       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6739                                            (TypeBits-ShAmt->getZExtValue()-1));
6740       Instruction *AndI =
6741         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6742                                   Mask, LHSI->getName()+".mask");
6743       Value *And = InsertNewInstBefore(AndI, ICI);
6744       
6745       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6746                           And, Constant::getNullValue(And->getType()));
6747     }
6748     break;
6749   }
6750     
6751   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6752   case Instruction::AShr: {
6753     // Only handle equality comparisons of shift-by-constant.
6754     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6755     if (!ShAmt || !ICI.isEquality()) break;
6756
6757     // Check that the shift amount is in range.  If not, don't perform
6758     // undefined shifts.  When the shift is visited it will be
6759     // simplified.
6760     uint32_t TypeBits = RHSV.getBitWidth();
6761     if (ShAmt->uge(TypeBits))
6762       break;
6763     
6764     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6765       
6766     // If we are comparing against bits always shifted out, the
6767     // comparison cannot succeed.
6768     APInt Comp = RHSV << ShAmtVal;
6769     if (LHSI->getOpcode() == Instruction::LShr)
6770       Comp = Comp.lshr(ShAmtVal);
6771     else
6772       Comp = Comp.ashr(ShAmtVal);
6773     
6774     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6775       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6776       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6777       return ReplaceInstUsesWith(ICI, Cst);
6778     }
6779     
6780     // Otherwise, check to see if the bits shifted out are known to be zero.
6781     // If so, we can compare against the unshifted value:
6782     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6783     if (LHSI->hasOneUse() &&
6784         MaskedValueIsZero(LHSI->getOperand(0), 
6785                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6786       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6787                           ConstantExpr::getShl(RHS, ShAmt));
6788     }
6789       
6790     if (LHSI->hasOneUse()) {
6791       // Otherwise strength reduce the shift into an and.
6792       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6793       Constant *Mask = ConstantInt::get(Val);
6794       
6795       Instruction *AndI =
6796         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6797                                   Mask, LHSI->getName()+".mask");
6798       Value *And = InsertNewInstBefore(AndI, ICI);
6799       return new ICmpInst(ICI.getPredicate(), And,
6800                           ConstantExpr::getShl(RHS, ShAmt));
6801     }
6802     break;
6803   }
6804     
6805   case Instruction::SDiv:
6806   case Instruction::UDiv:
6807     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6808     // Fold this div into the comparison, producing a range check. 
6809     // Determine, based on the divide type, what the range is being 
6810     // checked.  If there is an overflow on the low or high side, remember 
6811     // it, otherwise compute the range [low, hi) bounding the new value.
6812     // See: InsertRangeTest above for the kinds of replacements possible.
6813     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6814       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6815                                           DivRHS))
6816         return R;
6817     break;
6818
6819   case Instruction::Add:
6820     // Fold: icmp pred (add, X, C1), C2
6821
6822     if (!ICI.isEquality()) {
6823       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6824       if (!LHSC) break;
6825       const APInt &LHSV = LHSC->getValue();
6826
6827       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6828                             .subtract(LHSV);
6829
6830       if (ICI.isSignedPredicate()) {
6831         if (CR.getLower().isSignBit()) {
6832           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6833                               ConstantInt::get(CR.getUpper()));
6834         } else if (CR.getUpper().isSignBit()) {
6835           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6836                               ConstantInt::get(CR.getLower()));
6837         }
6838       } else {
6839         if (CR.getLower().isMinValue()) {
6840           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6841                               ConstantInt::get(CR.getUpper()));
6842         } else if (CR.getUpper().isMinValue()) {
6843           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6844                               ConstantInt::get(CR.getLower()));
6845         }
6846       }
6847     }
6848     break;
6849   }
6850   
6851   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6852   if (ICI.isEquality()) {
6853     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6854     
6855     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6856     // the second operand is a constant, simplify a bit.
6857     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6858       switch (BO->getOpcode()) {
6859       case Instruction::SRem:
6860         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6861         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6862           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6863           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6864             Instruction *NewRem =
6865               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6866                                          BO->getName());
6867             InsertNewInstBefore(NewRem, ICI);
6868             return new ICmpInst(ICI.getPredicate(), NewRem, 
6869                                 Constant::getNullValue(BO->getType()));
6870           }
6871         }
6872         break;
6873       case Instruction::Add:
6874         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6875         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6876           if (BO->hasOneUse())
6877             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6878                                 Subtract(RHS, BOp1C));
6879         } else if (RHSV == 0) {
6880           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6881           // efficiently invertible, or if the add has just this one use.
6882           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6883           
6884           if (Value *NegVal = dyn_castNegVal(BOp1))
6885             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6886           else if (Value *NegVal = dyn_castNegVal(BOp0))
6887             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6888           else if (BO->hasOneUse()) {
6889             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6890             InsertNewInstBefore(Neg, ICI);
6891             Neg->takeName(BO);
6892             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6893           }
6894         }
6895         break;
6896       case Instruction::Xor:
6897         // For the xor case, we can xor two constants together, eliminating
6898         // the explicit xor.
6899         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6900           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6901                               ConstantExpr::getXor(RHS, BOC));
6902         
6903         // FALLTHROUGH
6904       case Instruction::Sub:
6905         // Replace (([sub|xor] A, B) != 0) with (A != B)
6906         if (RHSV == 0)
6907           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6908                               BO->getOperand(1));
6909         break;
6910         
6911       case Instruction::Or:
6912         // If bits are being or'd in that are not present in the constant we
6913         // are comparing against, then the comparison could never succeed!
6914         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6915           Constant *NotCI = ConstantExpr::getNot(RHS);
6916           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6917             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6918                                                              isICMP_NE));
6919         }
6920         break;
6921         
6922       case Instruction::And:
6923         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6924           // If bits are being compared against that are and'd out, then the
6925           // comparison can never succeed!
6926           if ((RHSV & ~BOC->getValue()) != 0)
6927             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6928                                                              isICMP_NE));
6929           
6930           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6931           if (RHS == BOC && RHSV.isPowerOf2())
6932             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6933                                 ICmpInst::ICMP_NE, LHSI,
6934                                 Constant::getNullValue(RHS->getType()));
6935           
6936           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6937           if (BOC->getValue().isSignBit()) {
6938             Value *X = BO->getOperand(0);
6939             Constant *Zero = Constant::getNullValue(X->getType());
6940             ICmpInst::Predicate pred = isICMP_NE ? 
6941               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6942             return new ICmpInst(pred, X, Zero);
6943           }
6944           
6945           // ((X & ~7) == 0) --> X < 8
6946           if (RHSV == 0 && isHighOnes(BOC)) {
6947             Value *X = BO->getOperand(0);
6948             Constant *NegX = ConstantExpr::getNeg(BOC);
6949             ICmpInst::Predicate pred = isICMP_NE ? 
6950               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6951             return new ICmpInst(pred, X, NegX);
6952           }
6953         }
6954       default: break;
6955       }
6956     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6957       // Handle icmp {eq|ne} <intrinsic>, intcst.
6958       if (II->getIntrinsicID() == Intrinsic::bswap) {
6959         AddToWorkList(II);
6960         ICI.setOperand(0, II->getOperand(1));
6961         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6962         return &ICI;
6963       }
6964     }
6965   }
6966   return 0;
6967 }
6968
6969 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6970 /// We only handle extending casts so far.
6971 ///
6972 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6973   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6974   Value *LHSCIOp        = LHSCI->getOperand(0);
6975   const Type *SrcTy     = LHSCIOp->getType();
6976   const Type *DestTy    = LHSCI->getType();
6977   Value *RHSCIOp;
6978
6979   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6980   // integer type is the same size as the pointer type.
6981   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6982       getTargetData().getPointerSizeInBits() == 
6983          cast<IntegerType>(DestTy)->getBitWidth()) {
6984     Value *RHSOp = 0;
6985     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6986       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6987     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6988       RHSOp = RHSC->getOperand(0);
6989       // If the pointer types don't match, insert a bitcast.
6990       if (LHSCIOp->getType() != RHSOp->getType())
6991         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6992     }
6993
6994     if (RHSOp)
6995       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6996   }
6997   
6998   // The code below only handles extension cast instructions, so far.
6999   // Enforce this.
7000   if (LHSCI->getOpcode() != Instruction::ZExt &&
7001       LHSCI->getOpcode() != Instruction::SExt)
7002     return 0;
7003
7004   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7005   bool isSignedCmp = ICI.isSignedPredicate();
7006
7007   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7008     // Not an extension from the same type?
7009     RHSCIOp = CI->getOperand(0);
7010     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7011       return 0;
7012     
7013     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7014     // and the other is a zext), then we can't handle this.
7015     if (CI->getOpcode() != LHSCI->getOpcode())
7016       return 0;
7017
7018     // Deal with equality cases early.
7019     if (ICI.isEquality())
7020       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7021
7022     // A signed comparison of sign extended values simplifies into a
7023     // signed comparison.
7024     if (isSignedCmp && isSignedExt)
7025       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7026
7027     // The other three cases all fold into an unsigned comparison.
7028     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7029   }
7030
7031   // If we aren't dealing with a constant on the RHS, exit early
7032   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7033   if (!CI)
7034     return 0;
7035
7036   // Compute the constant that would happen if we truncated to SrcTy then
7037   // reextended to DestTy.
7038   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7039   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
7040
7041   // If the re-extended constant didn't change...
7042   if (Res2 == CI) {
7043     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7044     // For example, we might have:
7045     //    %A = sext short %X to uint
7046     //    %B = icmp ugt uint %A, 1330
7047     // It is incorrect to transform this into 
7048     //    %B = icmp ugt short %X, 1330 
7049     // because %A may have negative value. 
7050     //
7051     // However, we allow this when the compare is EQ/NE, because they are
7052     // signless.
7053     if (isSignedExt == isSignedCmp || ICI.isEquality())
7054       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7055     return 0;
7056   }
7057
7058   // The re-extended constant changed so the constant cannot be represented 
7059   // in the shorter type. Consequently, we cannot emit a simple comparison.
7060
7061   // First, handle some easy cases. We know the result cannot be equal at this
7062   // point so handle the ICI.isEquality() cases
7063   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7064     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
7065   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7066     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
7067
7068   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7069   // should have been folded away previously and not enter in here.
7070   Value *Result;
7071   if (isSignedCmp) {
7072     // We're performing a signed comparison.
7073     if (cast<ConstantInt>(CI)->getValue().isNegative())
7074       Result = ConstantInt::getFalse();          // X < (small) --> false
7075     else
7076       Result = ConstantInt::getTrue();           // X < (large) --> true
7077   } else {
7078     // We're performing an unsigned comparison.
7079     if (isSignedExt) {
7080       // We're performing an unsigned comp with a sign extended value.
7081       // This is true if the input is >= 0. [aka >s -1]
7082       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
7083       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
7084                                    NegOne, ICI.getName()), ICI);
7085     } else {
7086       // Unsigned extend & unsigned compare -> always true.
7087       Result = ConstantInt::getTrue();
7088     }
7089   }
7090
7091   // Finally, return the value computed.
7092   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7093       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7094     return ReplaceInstUsesWith(ICI, Result);
7095
7096   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7097           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7098          "ICmp should be folded!");
7099   if (Constant *CI = dyn_cast<Constant>(Result))
7100     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7101   return BinaryOperator::CreateNot(Result);
7102 }
7103
7104 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7105   return commonShiftTransforms(I);
7106 }
7107
7108 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7109   return commonShiftTransforms(I);
7110 }
7111
7112 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7113   if (Instruction *R = commonShiftTransforms(I))
7114     return R;
7115   
7116   Value *Op0 = I.getOperand(0);
7117   
7118   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7119   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7120     if (CSI->isAllOnesValue())
7121       return ReplaceInstUsesWith(I, CSI);
7122   
7123   // See if we can turn a signed shr into an unsigned shr.
7124   if (!isa<VectorType>(I.getType())) {
7125     if (MaskedValueIsZero(Op0,
7126                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
7127       return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7128
7129     // Arithmetic shifting an all-sign-bit value is a no-op.
7130     unsigned NumSignBits = ComputeNumSignBits(Op0);
7131     if (NumSignBits == Op0->getType()->getPrimitiveSizeInBits())
7132       return ReplaceInstUsesWith(I, Op0);
7133   }
7134
7135   return 0;
7136 }
7137
7138 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7139   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7140   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7141
7142   // shl X, 0 == X and shr X, 0 == X
7143   // shl 0, X == 0 and shr 0, X == 0
7144   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7145       Op0 == Constant::getNullValue(Op0->getType()))
7146     return ReplaceInstUsesWith(I, Op0);
7147   
7148   if (isa<UndefValue>(Op0)) {            
7149     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7150       return ReplaceInstUsesWith(I, Op0);
7151     else                                    // undef << X -> 0, undef >>u X -> 0
7152       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7153   }
7154   if (isa<UndefValue>(Op1)) {
7155     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7156       return ReplaceInstUsesWith(I, Op0);          
7157     else                                     // X << undef, X >>u undef -> 0
7158       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7159   }
7160
7161   // See if we can fold away this shift.
7162   if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
7163     return &I;
7164
7165   // Try to fold constant and into select arguments.
7166   if (isa<Constant>(Op0))
7167     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7168       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7169         return R;
7170
7171   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7172     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7173       return Res;
7174   return 0;
7175 }
7176
7177 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7178                                                BinaryOperator &I) {
7179   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7180
7181   // See if we can simplify any instructions used by the instruction whose sole 
7182   // purpose is to compute bits we don't care about.
7183   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
7184   
7185   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7186   // of a signed value.
7187   //
7188   if (Op1->uge(TypeBits)) {
7189     if (I.getOpcode() != Instruction::AShr)
7190       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7191     else {
7192       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7193       return &I;
7194     }
7195   }
7196   
7197   // ((X*C1) << C2) == (X * (C1 << C2))
7198   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7199     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7200       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7201         return BinaryOperator::CreateMul(BO->getOperand(0),
7202                                          ConstantExpr::getShl(BOOp, Op1));
7203   
7204   // Try to fold constant and into select arguments.
7205   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7206     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7207       return R;
7208   if (isa<PHINode>(Op0))
7209     if (Instruction *NV = FoldOpIntoPhi(I))
7210       return NV;
7211   
7212   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7213   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7214     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7215     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7216     // place.  Don't try to do this transformation in this case.  Also, we
7217     // require that the input operand is a shift-by-constant so that we have
7218     // confidence that the shifts will get folded together.  We could do this
7219     // xform in more cases, but it is unlikely to be profitable.
7220     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7221         isa<ConstantInt>(TrOp->getOperand(1))) {
7222       // Okay, we'll do this xform.  Make the shift of shift.
7223       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7224       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7225                                                 I.getName());
7226       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7227
7228       // For logical shifts, the truncation has the effect of making the high
7229       // part of the register be zeros.  Emulate this by inserting an AND to
7230       // clear the top bits as needed.  This 'and' will usually be zapped by
7231       // other xforms later if dead.
7232       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7233       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7234       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7235       
7236       // The mask we constructed says what the trunc would do if occurring
7237       // between the shifts.  We want to know the effect *after* the second
7238       // shift.  We know that it is a logical shift by a constant, so adjust the
7239       // mask as appropriate.
7240       if (I.getOpcode() == Instruction::Shl)
7241         MaskV <<= Op1->getZExtValue();
7242       else {
7243         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7244         MaskV = MaskV.lshr(Op1->getZExtValue());
7245       }
7246
7247       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7248                                                    TI->getName());
7249       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7250
7251       // Return the value truncated to the interesting size.
7252       return new TruncInst(And, I.getType());
7253     }
7254   }
7255   
7256   if (Op0->hasOneUse()) {
7257     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7258       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7259       Value *V1, *V2;
7260       ConstantInt *CC;
7261       switch (Op0BO->getOpcode()) {
7262         default: break;
7263         case Instruction::Add:
7264         case Instruction::And:
7265         case Instruction::Or:
7266         case Instruction::Xor: {
7267           // These operators commute.
7268           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7269           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7270               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7271             Instruction *YS = BinaryOperator::CreateShl(
7272                                             Op0BO->getOperand(0), Op1,
7273                                             Op0BO->getName());
7274             InsertNewInstBefore(YS, I); // (Y << C)
7275             Instruction *X = 
7276               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7277                                      Op0BO->getOperand(1)->getName());
7278             InsertNewInstBefore(X, I);  // (X + (Y << C))
7279             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7280             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7281                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7282           }
7283           
7284           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7285           Value *Op0BOOp1 = Op0BO->getOperand(1);
7286           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7287               match(Op0BOOp1, 
7288                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7289                           m_ConstantInt(CC))) &&
7290               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7291             Instruction *YS = BinaryOperator::CreateShl(
7292                                                      Op0BO->getOperand(0), Op1,
7293                                                      Op0BO->getName());
7294             InsertNewInstBefore(YS, I); // (Y << C)
7295             Instruction *XM =
7296               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7297                                         V1->getName()+".mask");
7298             InsertNewInstBefore(XM, I); // X & (CC << C)
7299             
7300             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7301           }
7302         }
7303           
7304         // FALL THROUGH.
7305         case Instruction::Sub: {
7306           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7307           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7308               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7309             Instruction *YS = BinaryOperator::CreateShl(
7310                                                      Op0BO->getOperand(1), Op1,
7311                                                      Op0BO->getName());
7312             InsertNewInstBefore(YS, I); // (Y << C)
7313             Instruction *X =
7314               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7315                                      Op0BO->getOperand(0)->getName());
7316             InsertNewInstBefore(X, I);  // (X + (Y << C))
7317             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7318             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7319                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7320           }
7321           
7322           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7323           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7324               match(Op0BO->getOperand(0),
7325                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7326                           m_ConstantInt(CC))) && V2 == Op1 &&
7327               cast<BinaryOperator>(Op0BO->getOperand(0))
7328                   ->getOperand(0)->hasOneUse()) {
7329             Instruction *YS = BinaryOperator::CreateShl(
7330                                                      Op0BO->getOperand(1), Op1,
7331                                                      Op0BO->getName());
7332             InsertNewInstBefore(YS, I); // (Y << C)
7333             Instruction *XM =
7334               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7335                                         V1->getName()+".mask");
7336             InsertNewInstBefore(XM, I); // X & (CC << C)
7337             
7338             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7339           }
7340           
7341           break;
7342         }
7343       }
7344       
7345       
7346       // If the operand is an bitwise operator with a constant RHS, and the
7347       // shift is the only use, we can pull it out of the shift.
7348       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7349         bool isValid = true;     // Valid only for And, Or, Xor
7350         bool highBitSet = false; // Transform if high bit of constant set?
7351         
7352         switch (Op0BO->getOpcode()) {
7353           default: isValid = false; break;   // Do not perform transform!
7354           case Instruction::Add:
7355             isValid = isLeftShift;
7356             break;
7357           case Instruction::Or:
7358           case Instruction::Xor:
7359             highBitSet = false;
7360             break;
7361           case Instruction::And:
7362             highBitSet = true;
7363             break;
7364         }
7365         
7366         // If this is a signed shift right, and the high bit is modified
7367         // by the logical operation, do not perform the transformation.
7368         // The highBitSet boolean indicates the value of the high bit of
7369         // the constant which would cause it to be modified for this
7370         // operation.
7371         //
7372         if (isValid && I.getOpcode() == Instruction::AShr)
7373           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7374         
7375         if (isValid) {
7376           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7377           
7378           Instruction *NewShift =
7379             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7380           InsertNewInstBefore(NewShift, I);
7381           NewShift->takeName(Op0BO);
7382           
7383           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7384                                         NewRHS);
7385         }
7386       }
7387     }
7388   }
7389   
7390   // Find out if this is a shift of a shift by a constant.
7391   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7392   if (ShiftOp && !ShiftOp->isShift())
7393     ShiftOp = 0;
7394   
7395   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7396     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7397     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7398     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7399     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7400     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7401     Value *X = ShiftOp->getOperand(0);
7402     
7403     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7404     
7405     const IntegerType *Ty = cast<IntegerType>(I.getType());
7406     
7407     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7408     if (I.getOpcode() == ShiftOp->getOpcode()) {
7409       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7410       // saturates.
7411       if (AmtSum >= TypeBits) {
7412         if (I.getOpcode() != Instruction::AShr)
7413           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7414         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7415       }
7416       
7417       return BinaryOperator::Create(I.getOpcode(), X,
7418                                     ConstantInt::get(Ty, AmtSum));
7419     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7420                I.getOpcode() == Instruction::AShr) {
7421       if (AmtSum >= TypeBits)
7422         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7423       
7424       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7425       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7426     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7427                I.getOpcode() == Instruction::LShr) {
7428       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7429       if (AmtSum >= TypeBits)
7430         AmtSum = TypeBits-1;
7431       
7432       Instruction *Shift =
7433         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7434       InsertNewInstBefore(Shift, I);
7435
7436       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7437       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7438     }
7439     
7440     // Okay, if we get here, one shift must be left, and the other shift must be
7441     // right.  See if the amounts are equal.
7442     if (ShiftAmt1 == ShiftAmt2) {
7443       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7444       if (I.getOpcode() == Instruction::Shl) {
7445         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7446         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7447       }
7448       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7449       if (I.getOpcode() == Instruction::LShr) {
7450         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7451         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7452       }
7453       // We can simplify ((X << C) >>s C) into a trunc + sext.
7454       // NOTE: we could do this for any C, but that would make 'unusual' integer
7455       // types.  For now, just stick to ones well-supported by the code
7456       // generators.
7457       const Type *SExtType = 0;
7458       switch (Ty->getBitWidth() - ShiftAmt1) {
7459       case 1  :
7460       case 8  :
7461       case 16 :
7462       case 32 :
7463       case 64 :
7464       case 128:
7465         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7466         break;
7467       default: break;
7468       }
7469       if (SExtType) {
7470         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7471         InsertNewInstBefore(NewTrunc, I);
7472         return new SExtInst(NewTrunc, Ty);
7473       }
7474       // Otherwise, we can't handle it yet.
7475     } else if (ShiftAmt1 < ShiftAmt2) {
7476       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7477       
7478       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7479       if (I.getOpcode() == Instruction::Shl) {
7480         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7481                ShiftOp->getOpcode() == Instruction::AShr);
7482         Instruction *Shift =
7483           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7484         InsertNewInstBefore(Shift, I);
7485         
7486         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7487         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7488       }
7489       
7490       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7491       if (I.getOpcode() == Instruction::LShr) {
7492         assert(ShiftOp->getOpcode() == Instruction::Shl);
7493         Instruction *Shift =
7494           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7495         InsertNewInstBefore(Shift, I);
7496         
7497         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7498         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7499       }
7500       
7501       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7502     } else {
7503       assert(ShiftAmt2 < ShiftAmt1);
7504       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7505
7506       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7507       if (I.getOpcode() == Instruction::Shl) {
7508         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7509                ShiftOp->getOpcode() == Instruction::AShr);
7510         Instruction *Shift =
7511           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7512                                  ConstantInt::get(Ty, ShiftDiff));
7513         InsertNewInstBefore(Shift, I);
7514         
7515         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7516         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7517       }
7518       
7519       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7520       if (I.getOpcode() == Instruction::LShr) {
7521         assert(ShiftOp->getOpcode() == Instruction::Shl);
7522         Instruction *Shift =
7523           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7524         InsertNewInstBefore(Shift, I);
7525         
7526         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7527         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7528       }
7529       
7530       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7531     }
7532   }
7533   return 0;
7534 }
7535
7536
7537 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7538 /// expression.  If so, decompose it, returning some value X, such that Val is
7539 /// X*Scale+Offset.
7540 ///
7541 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7542                                         int &Offset) {
7543   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7544   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7545     Offset = CI->getZExtValue();
7546     Scale  = 0;
7547     return ConstantInt::get(Type::Int32Ty, 0);
7548   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7549     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7550       if (I->getOpcode() == Instruction::Shl) {
7551         // This is a value scaled by '1 << the shift amt'.
7552         Scale = 1U << RHS->getZExtValue();
7553         Offset = 0;
7554         return I->getOperand(0);
7555       } else if (I->getOpcode() == Instruction::Mul) {
7556         // This value is scaled by 'RHS'.
7557         Scale = RHS->getZExtValue();
7558         Offset = 0;
7559         return I->getOperand(0);
7560       } else if (I->getOpcode() == Instruction::Add) {
7561         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7562         // where C1 is divisible by C2.
7563         unsigned SubScale;
7564         Value *SubVal = 
7565           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7566         Offset += RHS->getZExtValue();
7567         Scale = SubScale;
7568         return SubVal;
7569       }
7570     }
7571   }
7572
7573   // Otherwise, we can't look past this.
7574   Scale = 1;
7575   Offset = 0;
7576   return Val;
7577 }
7578
7579
7580 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7581 /// try to eliminate the cast by moving the type information into the alloc.
7582 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7583                                                    AllocationInst &AI) {
7584   const PointerType *PTy = cast<PointerType>(CI.getType());
7585   
7586   // Remove any uses of AI that are dead.
7587   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7588   
7589   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7590     Instruction *User = cast<Instruction>(*UI++);
7591     if (isInstructionTriviallyDead(User)) {
7592       while (UI != E && *UI == User)
7593         ++UI; // If this instruction uses AI more than once, don't break UI.
7594       
7595       ++NumDeadInst;
7596       DOUT << "IC: DCE: " << *User;
7597       EraseInstFromFunction(*User);
7598     }
7599   }
7600   
7601   // Get the type really allocated and the type casted to.
7602   const Type *AllocElTy = AI.getAllocatedType();
7603   const Type *CastElTy = PTy->getElementType();
7604   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7605
7606   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7607   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7608   if (CastElTyAlign < AllocElTyAlign) return 0;
7609
7610   // If the allocation has multiple uses, only promote it if we are strictly
7611   // increasing the alignment of the resultant allocation.  If we keep it the
7612   // same, we open the door to infinite loops of various kinds.  (A reference
7613   // from a dbg.declare doesn't count as a use for this purpose.)
7614   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7615       CastElTyAlign == AllocElTyAlign) return 0;
7616
7617   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7618   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7619   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7620
7621   // See if we can satisfy the modulus by pulling a scale out of the array
7622   // size argument.
7623   unsigned ArraySizeScale;
7624   int ArrayOffset;
7625   Value *NumElements = // See if the array size is a decomposable linear expr.
7626     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7627  
7628   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7629   // do the xform.
7630   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7631       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7632
7633   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7634   Value *Amt = 0;
7635   if (Scale == 1) {
7636     Amt = NumElements;
7637   } else {
7638     // If the allocation size is constant, form a constant mul expression
7639     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7640     if (isa<ConstantInt>(NumElements))
7641       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7642     // otherwise multiply the amount and the number of elements
7643     else {
7644       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7645       Amt = InsertNewInstBefore(Tmp, AI);
7646     }
7647   }
7648   
7649   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7650     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7651     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7652     Amt = InsertNewInstBefore(Tmp, AI);
7653   }
7654   
7655   AllocationInst *New;
7656   if (isa<MallocInst>(AI))
7657     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7658   else
7659     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7660   InsertNewInstBefore(New, AI);
7661   New->takeName(&AI);
7662   
7663   // If the allocation has one real use plus a dbg.declare, just remove the
7664   // declare.
7665   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7666     EraseInstFromFunction(*DI);
7667   }
7668   // If the allocation has multiple real uses, insert a cast and change all
7669   // things that used it to use the new cast.  This will also hack on CI, but it
7670   // will die soon.
7671   else if (!AI.hasOneUse()) {
7672     AddUsesToWorkList(AI);
7673     // New is the allocation instruction, pointer typed. AI is the original
7674     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7675     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7676     InsertNewInstBefore(NewCast, AI);
7677     AI.replaceAllUsesWith(NewCast);
7678   }
7679   return ReplaceInstUsesWith(CI, New);
7680 }
7681
7682 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7683 /// and return it as type Ty without inserting any new casts and without
7684 /// changing the computed value.  This is used by code that tries to decide
7685 /// whether promoting or shrinking integer operations to wider or smaller types
7686 /// will allow us to eliminate a truncate or extend.
7687 ///
7688 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7689 /// extension operation if Ty is larger.
7690 ///
7691 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7692 /// should return true if trunc(V) can be computed by computing V in the smaller
7693 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7694 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7695 /// efficiently truncated.
7696 ///
7697 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7698 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7699 /// the final result.
7700 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7701                                               unsigned CastOpc,
7702                                               int &NumCastsRemoved){
7703   // We can always evaluate constants in another type.
7704   if (isa<ConstantInt>(V))
7705     return true;
7706   
7707   Instruction *I = dyn_cast<Instruction>(V);
7708   if (!I) return false;
7709   
7710   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7711   
7712   // If this is an extension or truncate, we can often eliminate it.
7713   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7714     // If this is a cast from the destination type, we can trivially eliminate
7715     // it, and this will remove a cast overall.
7716     if (I->getOperand(0)->getType() == Ty) {
7717       // If the first operand is itself a cast, and is eliminable, do not count
7718       // this as an eliminable cast.  We would prefer to eliminate those two
7719       // casts first.
7720       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7721         ++NumCastsRemoved;
7722       return true;
7723     }
7724   }
7725
7726   // We can't extend or shrink something that has multiple uses: doing so would
7727   // require duplicating the instruction in general, which isn't profitable.
7728   if (!I->hasOneUse()) return false;
7729
7730   unsigned Opc = I->getOpcode();
7731   switch (Opc) {
7732   case Instruction::Add:
7733   case Instruction::Sub:
7734   case Instruction::Mul:
7735   case Instruction::And:
7736   case Instruction::Or:
7737   case Instruction::Xor:
7738     // These operators can all arbitrarily be extended or truncated.
7739     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7740                                       NumCastsRemoved) &&
7741            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7742                                       NumCastsRemoved);
7743
7744   case Instruction::Shl:
7745     // If we are truncating the result of this SHL, and if it's a shift of a
7746     // constant amount, we can always perform a SHL in a smaller type.
7747     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7748       uint32_t BitWidth = Ty->getBitWidth();
7749       if (BitWidth < OrigTy->getBitWidth() && 
7750           CI->getLimitedValue(BitWidth) < BitWidth)
7751         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7752                                           NumCastsRemoved);
7753     }
7754     break;
7755   case Instruction::LShr:
7756     // If this is a truncate of a logical shr, we can truncate it to a smaller
7757     // lshr iff we know that the bits we would otherwise be shifting in are
7758     // already zeros.
7759     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7760       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7761       uint32_t BitWidth = Ty->getBitWidth();
7762       if (BitWidth < OrigBitWidth &&
7763           MaskedValueIsZero(I->getOperand(0),
7764             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7765           CI->getLimitedValue(BitWidth) < BitWidth) {
7766         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7767                                           NumCastsRemoved);
7768       }
7769     }
7770     break;
7771   case Instruction::ZExt:
7772   case Instruction::SExt:
7773   case Instruction::Trunc:
7774     // If this is the same kind of case as our original (e.g. zext+zext), we
7775     // can safely replace it.  Note that replacing it does not reduce the number
7776     // of casts in the input.
7777     if (Opc == CastOpc)
7778       return true;
7779
7780     // sext (zext ty1), ty2 -> zext ty2
7781     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7782       return true;
7783     break;
7784   case Instruction::Select: {
7785     SelectInst *SI = cast<SelectInst>(I);
7786     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7787                                       NumCastsRemoved) &&
7788            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7789                                       NumCastsRemoved);
7790   }
7791   case Instruction::PHI: {
7792     // We can change a phi if we can change all operands.
7793     PHINode *PN = cast<PHINode>(I);
7794     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7795       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7796                                       NumCastsRemoved))
7797         return false;
7798     return true;
7799   }
7800   default:
7801     // TODO: Can handle more cases here.
7802     break;
7803   }
7804   
7805   return false;
7806 }
7807
7808 /// EvaluateInDifferentType - Given an expression that 
7809 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7810 /// evaluate the expression.
7811 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7812                                              bool isSigned) {
7813   if (Constant *C = dyn_cast<Constant>(V))
7814     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7815
7816   // Otherwise, it must be an instruction.
7817   Instruction *I = cast<Instruction>(V);
7818   Instruction *Res = 0;
7819   unsigned Opc = I->getOpcode();
7820   switch (Opc) {
7821   case Instruction::Add:
7822   case Instruction::Sub:
7823   case Instruction::Mul:
7824   case Instruction::And:
7825   case Instruction::Or:
7826   case Instruction::Xor:
7827   case Instruction::AShr:
7828   case Instruction::LShr:
7829   case Instruction::Shl: {
7830     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7831     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7832     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7833     break;
7834   }    
7835   case Instruction::Trunc:
7836   case Instruction::ZExt:
7837   case Instruction::SExt:
7838     // If the source type of the cast is the type we're trying for then we can
7839     // just return the source.  There's no need to insert it because it is not
7840     // new.
7841     if (I->getOperand(0)->getType() == Ty)
7842       return I->getOperand(0);
7843     
7844     // Otherwise, must be the same type of cast, so just reinsert a new one.
7845     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7846                            Ty);
7847     break;
7848   case Instruction::Select: {
7849     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7850     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7851     Res = SelectInst::Create(I->getOperand(0), True, False);
7852     break;
7853   }
7854   case Instruction::PHI: {
7855     PHINode *OPN = cast<PHINode>(I);
7856     PHINode *NPN = PHINode::Create(Ty);
7857     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7858       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7859       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7860     }
7861     Res = NPN;
7862     break;
7863   }
7864   default: 
7865     // TODO: Can handle more cases here.
7866     assert(0 && "Unreachable!");
7867     break;
7868   }
7869   
7870   Res->takeName(I);
7871   return InsertNewInstBefore(Res, *I);
7872 }
7873
7874 /// @brief Implement the transforms common to all CastInst visitors.
7875 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7876   Value *Src = CI.getOperand(0);
7877
7878   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7879   // eliminate it now.
7880   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7881     if (Instruction::CastOps opc = 
7882         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7883       // The first cast (CSrc) is eliminable so we need to fix up or replace
7884       // the second cast (CI). CSrc will then have a good chance of being dead.
7885       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7886     }
7887   }
7888
7889   // If we are casting a select then fold the cast into the select
7890   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7891     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7892       return NV;
7893
7894   // If we are casting a PHI then fold the cast into the PHI
7895   if (isa<PHINode>(Src))
7896     if (Instruction *NV = FoldOpIntoPhi(CI))
7897       return NV;
7898   
7899   return 0;
7900 }
7901
7902 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7903 /// or not there is a sequence of GEP indices into the type that will land us at
7904 /// the specified offset.  If so, fill them into NewIndices and return the
7905 /// resultant element type, otherwise return null.
7906 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
7907                                        SmallVectorImpl<Value*> &NewIndices,
7908                                        const TargetData *TD) {
7909   if (!Ty->isSized()) return 0;
7910   
7911   // Start with the index over the outer type.  Note that the type size
7912   // might be zero (even if the offset isn't zero) if the indexed type
7913   // is something like [0 x {int, int}]
7914   const Type *IntPtrTy = TD->getIntPtrType();
7915   int64_t FirstIdx = 0;
7916   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
7917     FirstIdx = Offset/TySize;
7918     Offset -= FirstIdx*TySize;
7919     
7920     // Handle hosts where % returns negative instead of values [0..TySize).
7921     if (Offset < 0) {
7922       --FirstIdx;
7923       Offset += TySize;
7924       assert(Offset >= 0);
7925     }
7926     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7927   }
7928   
7929   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7930     
7931   // Index into the types.  If we fail, set OrigBase to null.
7932   while (Offset) {
7933     // Indexing into tail padding between struct/array elements.
7934     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
7935       return 0;
7936     
7937     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7938       const StructLayout *SL = TD->getStructLayout(STy);
7939       assert(Offset < (int64_t)SL->getSizeInBytes() &&
7940              "Offset must stay within the indexed type");
7941       
7942       unsigned Elt = SL->getElementContainingOffset(Offset);
7943       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7944       
7945       Offset -= SL->getElementOffset(Elt);
7946       Ty = STy->getElementType(Elt);
7947     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
7948       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
7949       assert(EltSize && "Cannot index into a zero-sized array");
7950       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7951       Offset %= EltSize;
7952       Ty = AT->getElementType();
7953     } else {
7954       // Otherwise, we can't index into the middle of this atomic type, bail.
7955       return 0;
7956     }
7957   }
7958   
7959   return Ty;
7960 }
7961
7962 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7963 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7964   Value *Src = CI.getOperand(0);
7965   
7966   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7967     // If casting the result of a getelementptr instruction with no offset, turn
7968     // this into a cast of the original pointer!
7969     if (GEP->hasAllZeroIndices()) {
7970       // Changing the cast operand is usually not a good idea but it is safe
7971       // here because the pointer operand is being replaced with another 
7972       // pointer operand so the opcode doesn't need to change.
7973       AddToWorkList(GEP);
7974       CI.setOperand(0, GEP->getOperand(0));
7975       return &CI;
7976     }
7977     
7978     // If the GEP has a single use, and the base pointer is a bitcast, and the
7979     // GEP computes a constant offset, see if we can convert these three
7980     // instructions into fewer.  This typically happens with unions and other
7981     // non-type-safe code.
7982     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7983       if (GEP->hasAllConstantIndices()) {
7984         // We are guaranteed to get a constant from EmitGEPOffset.
7985         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7986         int64_t Offset = OffsetV->getSExtValue();
7987         
7988         // Get the base pointer input of the bitcast, and the type it points to.
7989         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7990         const Type *GEPIdxTy =
7991           cast<PointerType>(OrigBase->getType())->getElementType();
7992         SmallVector<Value*, 8> NewIndices;
7993         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7994           // If we were able to index down into an element, create the GEP
7995           // and bitcast the result.  This eliminates one bitcast, potentially
7996           // two.
7997           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7998                                                         NewIndices.begin(),
7999                                                         NewIndices.end(), "");
8000           InsertNewInstBefore(NGEP, CI);
8001           NGEP->takeName(GEP);
8002           
8003           if (isa<BitCastInst>(CI))
8004             return new BitCastInst(NGEP, CI.getType());
8005           assert(isa<PtrToIntInst>(CI));
8006           return new PtrToIntInst(NGEP, CI.getType());
8007         }
8008       }      
8009     }
8010   }
8011     
8012   return commonCastTransforms(CI);
8013 }
8014
8015 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8016 /// type like i42.  We don't want to introduce operations on random non-legal
8017 /// integer types where they don't already exist in the code.  In the future,
8018 /// we should consider making this based off target-data, so that 32-bit targets
8019 /// won't get i64 operations etc.
8020 static bool isSafeIntegerType(const Type *Ty) {
8021   switch (Ty->getPrimitiveSizeInBits()) {
8022   case 8:
8023   case 16:
8024   case 32:
8025   case 64:
8026     return true;
8027   default: 
8028     return false;
8029   }
8030 }
8031
8032 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8033 /// integer types. This function implements the common transforms for all those
8034 /// cases.
8035 /// @brief Implement the transforms common to CastInst with integer operands
8036 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8037   if (Instruction *Result = commonCastTransforms(CI))
8038     return Result;
8039
8040   Value *Src = CI.getOperand(0);
8041   const Type *SrcTy = Src->getType();
8042   const Type *DestTy = CI.getType();
8043   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
8044   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
8045
8046   // See if we can simplify any instructions used by the LHS whose sole 
8047   // purpose is to compute bits we don't care about.
8048   if (SimplifyDemandedInstructionBits(CI))
8049     return &CI;
8050
8051   // If the source isn't an instruction or has more than one use then we
8052   // can't do anything more. 
8053   Instruction *SrcI = dyn_cast<Instruction>(Src);
8054   if (!SrcI || !Src->hasOneUse())
8055     return 0;
8056
8057   // Attempt to propagate the cast into the instruction for int->int casts.
8058   int NumCastsRemoved = 0;
8059   if (!isa<BitCastInst>(CI) &&
8060       // Only do this if the dest type is a simple type, don't convert the
8061       // expression tree to something weird like i93 unless the source is also
8062       // strange.
8063       (isSafeIntegerType(DestTy) || !isSafeIntegerType(SrcI->getType())) &&
8064       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
8065                                  CI.getOpcode(), NumCastsRemoved)) {
8066     // If this cast is a truncate, evaluting in a different type always
8067     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8068     // we need to do an AND to maintain the clear top-part of the computation,
8069     // so we require that the input have eliminated at least one cast.  If this
8070     // is a sign extension, we insert two new casts (to do the extension) so we
8071     // require that two casts have been eliminated.
8072     bool DoXForm = false;
8073     bool JustReplace = false;
8074     switch (CI.getOpcode()) {
8075     default:
8076       // All the others use floating point so we shouldn't actually 
8077       // get here because of the check above.
8078       assert(0 && "Unknown cast type");
8079     case Instruction::Trunc:
8080       DoXForm = true;
8081       break;
8082     case Instruction::ZExt: {
8083       DoXForm = NumCastsRemoved >= 1;
8084       if (!DoXForm && 0) {
8085         // If it's unnecessary to issue an AND to clear the high bits, it's
8086         // always profitable to do this xform.
8087         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8088         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8089         if (MaskedValueIsZero(TryRes, Mask))
8090           return ReplaceInstUsesWith(CI, TryRes);
8091         
8092         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8093           if (TryI->use_empty())
8094             EraseInstFromFunction(*TryI);
8095       }
8096       break;
8097     }
8098     case Instruction::SExt: {
8099       DoXForm = NumCastsRemoved >= 2;
8100       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8101         // If we do not have to emit the truncate + sext pair, then it's always
8102         // profitable to do this xform.
8103         //
8104         // It's not safe to eliminate the trunc + sext pair if one of the
8105         // eliminated cast is a truncate. e.g.
8106         // t2 = trunc i32 t1 to i16
8107         // t3 = sext i16 t2 to i32
8108         // !=
8109         // i32 t1
8110         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8111         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8112         if (NumSignBits > (DestBitSize - SrcBitSize))
8113           return ReplaceInstUsesWith(CI, TryRes);
8114         
8115         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8116           if (TryI->use_empty())
8117             EraseInstFromFunction(*TryI);
8118       }
8119       break;
8120     }
8121     }
8122     
8123     if (DoXForm) {
8124       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8125            << " cast: " << CI;
8126       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8127                                            CI.getOpcode() == Instruction::SExt);
8128       if (JustReplace)
8129         // Just replace this cast with the result.
8130         return ReplaceInstUsesWith(CI, Res);
8131
8132       assert(Res->getType() == DestTy);
8133       switch (CI.getOpcode()) {
8134       default: assert(0 && "Unknown cast type!");
8135       case Instruction::Trunc:
8136       case Instruction::BitCast:
8137         // Just replace this cast with the result.
8138         return ReplaceInstUsesWith(CI, Res);
8139       case Instruction::ZExt: {
8140         assert(SrcBitSize < DestBitSize && "Not a zext?");
8141
8142         // If the high bits are already zero, just replace this cast with the
8143         // result.
8144         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8145         if (MaskedValueIsZero(Res, Mask))
8146           return ReplaceInstUsesWith(CI, Res);
8147
8148         // We need to emit an AND to clear the high bits.
8149         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8150                                                             SrcBitSize));
8151         return BinaryOperator::CreateAnd(Res, C);
8152       }
8153       case Instruction::SExt: {
8154         // If the high bits are already filled with sign bit, just replace this
8155         // cast with the result.
8156         unsigned NumSignBits = ComputeNumSignBits(Res);
8157         if (NumSignBits > (DestBitSize - SrcBitSize))
8158           return ReplaceInstUsesWith(CI, Res);
8159
8160         // We need to emit a cast to truncate, then a cast to sext.
8161         return CastInst::Create(Instruction::SExt,
8162             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8163                              CI), DestTy);
8164       }
8165       }
8166     }
8167   }
8168   
8169   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8170   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8171
8172   switch (SrcI->getOpcode()) {
8173   case Instruction::Add:
8174   case Instruction::Mul:
8175   case Instruction::And:
8176   case Instruction::Or:
8177   case Instruction::Xor:
8178     // If we are discarding information, rewrite.
8179     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8180       // Don't insert two casts if they cannot be eliminated.  We allow 
8181       // two casts to be inserted if the sizes are the same.  This could 
8182       // only be converting signedness, which is a noop.
8183       if (DestBitSize == SrcBitSize || 
8184           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8185           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8186         Instruction::CastOps opcode = CI.getOpcode();
8187         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8188         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8189         return BinaryOperator::Create(
8190             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8191       }
8192     }
8193
8194     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8195     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8196         SrcI->getOpcode() == Instruction::Xor &&
8197         Op1 == ConstantInt::getTrue() &&
8198         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8199       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8200       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
8201     }
8202     break;
8203   case Instruction::SDiv:
8204   case Instruction::UDiv:
8205   case Instruction::SRem:
8206   case Instruction::URem:
8207     // If we are just changing the sign, rewrite.
8208     if (DestBitSize == SrcBitSize) {
8209       // Don't insert two casts if they cannot be eliminated.  We allow 
8210       // two casts to be inserted if the sizes are the same.  This could 
8211       // only be converting signedness, which is a noop.
8212       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
8213           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8214         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
8215                                        Op0, DestTy, *SrcI);
8216         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
8217                                        Op1, DestTy, *SrcI);
8218         return BinaryOperator::Create(
8219           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8220       }
8221     }
8222     break;
8223
8224   case Instruction::Shl:
8225     // Allow changing the sign of the source operand.  Do not allow 
8226     // changing the size of the shift, UNLESS the shift amount is a 
8227     // constant.  We must not change variable sized shifts to a smaller 
8228     // size, because it is undefined to shift more bits out than exist 
8229     // in the value.
8230     if (DestBitSize == SrcBitSize ||
8231         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8232       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8233           Instruction::BitCast : Instruction::Trunc);
8234       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8235       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8236       return BinaryOperator::CreateShl(Op0c, Op1c);
8237     }
8238     break;
8239   case Instruction::AShr:
8240     // If this is a signed shr, and if all bits shifted in are about to be
8241     // truncated off, turn it into an unsigned shr to allow greater
8242     // simplifications.
8243     if (DestBitSize < SrcBitSize &&
8244         isa<ConstantInt>(Op1)) {
8245       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8246       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8247         // Insert the new logical shift right.
8248         return BinaryOperator::CreateLShr(Op0, Op1);
8249       }
8250     }
8251     break;
8252   }
8253   return 0;
8254 }
8255
8256 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8257   if (Instruction *Result = commonIntCastTransforms(CI))
8258     return Result;
8259   
8260   Value *Src = CI.getOperand(0);
8261   const Type *Ty = CI.getType();
8262   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8263   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
8264
8265   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8266   if (DestBitWidth == 1) {
8267     Constant *One = ConstantInt::get(Src->getType(), 1);
8268     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8269     Value *Zero = Constant::getNullValue(Src->getType());
8270     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8271   }
8272   
8273   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8274   ConstantInt *ShAmtV = 0;
8275   Value *ShiftOp = 0;
8276   if (Src->hasOneUse() &&
8277       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8278     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8279     
8280     // Get a mask for the bits shifting in.
8281     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8282     if (MaskedValueIsZero(ShiftOp, Mask)) {
8283       if (ShAmt >= DestBitWidth)        // All zeros.
8284         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8285       
8286       // Okay, we can shrink this.  Truncate the input, then return a new
8287       // shift.
8288       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8289       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8290       return BinaryOperator::CreateLShr(V1, V2);
8291     }
8292   }
8293   
8294   return 0;
8295 }
8296
8297 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8298 /// in order to eliminate the icmp.
8299 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8300                                              bool DoXform) {
8301   // If we are just checking for a icmp eq of a single bit and zext'ing it
8302   // to an integer, then shift the bit to the appropriate place and then
8303   // cast to integer to avoid the comparison.
8304   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8305     const APInt &Op1CV = Op1C->getValue();
8306       
8307     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8308     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8309     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8310         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8311       if (!DoXform) return ICI;
8312
8313       Value *In = ICI->getOperand(0);
8314       Value *Sh = ConstantInt::get(In->getType(),
8315                                    In->getType()->getPrimitiveSizeInBits()-1);
8316       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8317                                                         In->getName()+".lobit"),
8318                                CI);
8319       if (In->getType() != CI.getType())
8320         In = CastInst::CreateIntegerCast(In, CI.getType(),
8321                                          false/*ZExt*/, "tmp", &CI);
8322
8323       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8324         Constant *One = ConstantInt::get(In->getType(), 1);
8325         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8326                                                          In->getName()+".not"),
8327                                  CI);
8328       }
8329
8330       return ReplaceInstUsesWith(CI, In);
8331     }
8332       
8333       
8334       
8335     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8336     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8337     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8338     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8339     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8340     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8341     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8342     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8343     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8344         // This only works for EQ and NE
8345         ICI->isEquality()) {
8346       // If Op1C some other power of two, convert:
8347       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8348       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8349       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8350       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8351         
8352       APInt KnownZeroMask(~KnownZero);
8353       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8354         if (!DoXform) return ICI;
8355
8356         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8357         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8358           // (X&4) == 2 --> false
8359           // (X&4) != 2 --> true
8360           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8361           Res = ConstantExpr::getZExt(Res, CI.getType());
8362           return ReplaceInstUsesWith(CI, Res);
8363         }
8364           
8365         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8366         Value *In = ICI->getOperand(0);
8367         if (ShiftAmt) {
8368           // Perform a logical shr by shiftamt.
8369           // Insert the shift to put the result in the low bit.
8370           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8371                                   ConstantInt::get(In->getType(), ShiftAmt),
8372                                                    In->getName()+".lobit"), CI);
8373         }
8374           
8375         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8376           Constant *One = ConstantInt::get(In->getType(), 1);
8377           In = BinaryOperator::CreateXor(In, One, "tmp");
8378           InsertNewInstBefore(cast<Instruction>(In), CI);
8379         }
8380           
8381         if (CI.getType() == In->getType())
8382           return ReplaceInstUsesWith(CI, In);
8383         else
8384           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8385       }
8386     }
8387   }
8388
8389   return 0;
8390 }
8391
8392 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8393   // If one of the common conversion will work ..
8394   if (Instruction *Result = commonIntCastTransforms(CI))
8395     return Result;
8396
8397   Value *Src = CI.getOperand(0);
8398
8399   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8400   // types and if the sizes are just right we can convert this into a logical
8401   // 'and' which will be much cheaper than the pair of casts.
8402   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8403     // Get the sizes of the types involved.  We know that the intermediate type
8404     // will be smaller than A or C, but don't know the relation between A and C.
8405     Value *A = CSrc->getOperand(0);
8406     unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
8407     unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8408     unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8409     // If we're actually extending zero bits, then if
8410     // SrcSize <  DstSize: zext(a & mask)
8411     // SrcSize == DstSize: a & mask
8412     // SrcSize  > DstSize: trunc(a) & mask
8413     if (SrcSize < DstSize) {
8414       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8415       Constant *AndConst = ConstantInt::get(AndValue);
8416       Instruction *And =
8417         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8418       InsertNewInstBefore(And, CI);
8419       return new ZExtInst(And, CI.getType());
8420     } else if (SrcSize == DstSize) {
8421       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8422       return BinaryOperator::CreateAnd(A, ConstantInt::get(AndValue));
8423     } else if (SrcSize > DstSize) {
8424       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8425       InsertNewInstBefore(Trunc, CI);
8426       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8427       return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(AndValue));
8428     }
8429   }
8430
8431   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8432     return transformZExtICmp(ICI, CI);
8433
8434   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8435   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8436     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8437     // of the (zext icmp) will be transformed.
8438     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8439     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8440     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8441         (transformZExtICmp(LHS, CI, false) ||
8442          transformZExtICmp(RHS, CI, false))) {
8443       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8444       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8445       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8446     }
8447   }
8448
8449   return 0;
8450 }
8451
8452 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8453   if (Instruction *I = commonIntCastTransforms(CI))
8454     return I;
8455   
8456   Value *Src = CI.getOperand(0);
8457   
8458   // Canonicalize sign-extend from i1 to a select.
8459   if (Src->getType() == Type::Int1Ty)
8460     return SelectInst::Create(Src,
8461                               ConstantInt::getAllOnesValue(CI.getType()),
8462                               Constant::getNullValue(CI.getType()));
8463
8464   // See if the value being truncated is already sign extended.  If so, just
8465   // eliminate the trunc/sext pair.
8466   if (getOpcode(Src) == Instruction::Trunc) {
8467     Value *Op = cast<User>(Src)->getOperand(0);
8468     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8469     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8470     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8471     unsigned NumSignBits = ComputeNumSignBits(Op);
8472
8473     if (OpBits == DestBits) {
8474       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8475       // bits, it is already ready.
8476       if (NumSignBits > DestBits-MidBits)
8477         return ReplaceInstUsesWith(CI, Op);
8478     } else if (OpBits < DestBits) {
8479       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8480       // bits, just sext from i32.
8481       if (NumSignBits > OpBits-MidBits)
8482         return new SExtInst(Op, CI.getType(), "tmp");
8483     } else {
8484       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8485       // bits, just truncate to i32.
8486       if (NumSignBits > OpBits-MidBits)
8487         return new TruncInst(Op, CI.getType(), "tmp");
8488     }
8489   }
8490
8491   // If the input is a shl/ashr pair of a same constant, then this is a sign
8492   // extension from a smaller value.  If we could trust arbitrary bitwidth
8493   // integers, we could turn this into a truncate to the smaller bit and then
8494   // use a sext for the whole extension.  Since we don't, look deeper and check
8495   // for a truncate.  If the source and dest are the same type, eliminate the
8496   // trunc and extend and just do shifts.  For example, turn:
8497   //   %a = trunc i32 %i to i8
8498   //   %b = shl i8 %a, 6
8499   //   %c = ashr i8 %b, 6
8500   //   %d = sext i8 %c to i32
8501   // into:
8502   //   %a = shl i32 %i, 30
8503   //   %d = ashr i32 %a, 30
8504   Value *A = 0;
8505   ConstantInt *BA = 0, *CA = 0;
8506   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8507                         m_ConstantInt(CA))) &&
8508       BA == CA && isa<TruncInst>(A)) {
8509     Value *I = cast<TruncInst>(A)->getOperand(0);
8510     if (I->getType() == CI.getType()) {
8511       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8512       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8513       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8514       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8515       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8516                                                         CI.getName()), CI);
8517       return BinaryOperator::CreateAShr(I, ShAmtV);
8518     }
8519   }
8520   
8521   return 0;
8522 }
8523
8524 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8525 /// in the specified FP type without changing its value.
8526 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8527   bool losesInfo;
8528   APFloat F = CFP->getValueAPF();
8529   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8530   if (!losesInfo)
8531     return ConstantFP::get(F);
8532   return 0;
8533 }
8534
8535 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8536 /// through it until we get the source value.
8537 static Value *LookThroughFPExtensions(Value *V) {
8538   if (Instruction *I = dyn_cast<Instruction>(V))
8539     if (I->getOpcode() == Instruction::FPExt)
8540       return LookThroughFPExtensions(I->getOperand(0));
8541   
8542   // If this value is a constant, return the constant in the smallest FP type
8543   // that can accurately represent it.  This allows us to turn
8544   // (float)((double)X+2.0) into x+2.0f.
8545   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8546     if (CFP->getType() == Type::PPC_FP128Ty)
8547       return V;  // No constant folding of this.
8548     // See if the value can be truncated to float and then reextended.
8549     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8550       return V;
8551     if (CFP->getType() == Type::DoubleTy)
8552       return V;  // Won't shrink.
8553     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8554       return V;
8555     // Don't try to shrink to various long double types.
8556   }
8557   
8558   return V;
8559 }
8560
8561 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8562   if (Instruction *I = commonCastTransforms(CI))
8563     return I;
8564   
8565   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8566   // smaller than the destination type, we can eliminate the truncate by doing
8567   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8568   // many builtins (sqrt, etc).
8569   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8570   if (OpI && OpI->hasOneUse()) {
8571     switch (OpI->getOpcode()) {
8572     default: break;
8573     case Instruction::Add:
8574     case Instruction::Sub:
8575     case Instruction::Mul:
8576     case Instruction::FDiv:
8577     case Instruction::FRem:
8578       const Type *SrcTy = OpI->getType();
8579       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8580       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8581       if (LHSTrunc->getType() != SrcTy && 
8582           RHSTrunc->getType() != SrcTy) {
8583         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8584         // If the source types were both smaller than the destination type of
8585         // the cast, do this xform.
8586         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8587             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8588           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8589                                       CI.getType(), CI);
8590           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8591                                       CI.getType(), CI);
8592           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8593         }
8594       }
8595       break;  
8596     }
8597   }
8598   return 0;
8599 }
8600
8601 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8602   return commonCastTransforms(CI);
8603 }
8604
8605 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8606   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8607   if (OpI == 0)
8608     return commonCastTransforms(FI);
8609
8610   // fptoui(uitofp(X)) --> X
8611   // fptoui(sitofp(X)) --> X
8612   // This is safe if the intermediate type has enough bits in its mantissa to
8613   // accurately represent all values of X.  For example, do not do this with
8614   // i64->float->i64.  This is also safe for sitofp case, because any negative
8615   // 'X' value would cause an undefined result for the fptoui. 
8616   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8617       OpI->getOperand(0)->getType() == FI.getType() &&
8618       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8619                     OpI->getType()->getFPMantissaWidth())
8620     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8621
8622   return commonCastTransforms(FI);
8623 }
8624
8625 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8626   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8627   if (OpI == 0)
8628     return commonCastTransforms(FI);
8629   
8630   // fptosi(sitofp(X)) --> X
8631   // fptosi(uitofp(X)) --> X
8632   // This is safe if the intermediate type has enough bits in its mantissa to
8633   // accurately represent all values of X.  For example, do not do this with
8634   // i64->float->i64.  This is also safe for sitofp case, because any negative
8635   // 'X' value would cause an undefined result for the fptoui. 
8636   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8637       OpI->getOperand(0)->getType() == FI.getType() &&
8638       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8639                     OpI->getType()->getFPMantissaWidth())
8640     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8641   
8642   return commonCastTransforms(FI);
8643 }
8644
8645 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8646   return commonCastTransforms(CI);
8647 }
8648
8649 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8650   return commonCastTransforms(CI);
8651 }
8652
8653 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8654   // If the destination integer type is smaller than the intptr_t type for
8655   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8656   // trunc to be exposed to other transforms.  Don't do this for extending
8657   // ptrtoint's, because we don't know if the target sign or zero extends its
8658   // pointers.
8659   if (CI.getType()->getPrimitiveSizeInBits() < TD->getPointerSizeInBits()) {
8660     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8661                                                     TD->getIntPtrType(),
8662                                                     "tmp"), CI);
8663     return new TruncInst(P, CI.getType());
8664   }
8665   
8666   return commonPointerCastTransforms(CI);
8667 }
8668
8669 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8670   // If the source integer type is larger than the intptr_t type for
8671   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8672   // allows the trunc to be exposed to other transforms.  Don't do this for
8673   // extending inttoptr's, because we don't know if the target sign or zero
8674   // extends to pointers.
8675   if (CI.getOperand(0)->getType()->getPrimitiveSizeInBits() >
8676       TD->getPointerSizeInBits()) {
8677     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8678                                                  TD->getIntPtrType(),
8679                                                  "tmp"), CI);
8680     return new IntToPtrInst(P, CI.getType());
8681   }
8682   
8683   if (Instruction *I = commonCastTransforms(CI))
8684     return I;
8685   
8686   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8687   if (!DestPointee->isSized()) return 0;
8688
8689   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8690   ConstantInt *Cst;
8691   Value *X;
8692   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8693                                     m_ConstantInt(Cst)))) {
8694     // If the source and destination operands have the same type, see if this
8695     // is a single-index GEP.
8696     if (X->getType() == CI.getType()) {
8697       // Get the size of the pointee type.
8698       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8699
8700       // Convert the constant to intptr type.
8701       APInt Offset = Cst->getValue();
8702       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8703
8704       // If Offset is evenly divisible by Size, we can do this xform.
8705       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8706         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8707         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8708       }
8709     }
8710     // TODO: Could handle other cases, e.g. where add is indexing into field of
8711     // struct etc.
8712   } else if (CI.getOperand(0)->hasOneUse() &&
8713              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8714     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8715     // "inttoptr+GEP" instead of "add+intptr".
8716     
8717     // Get the size of the pointee type.
8718     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8719     
8720     // Convert the constant to intptr type.
8721     APInt Offset = Cst->getValue();
8722     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8723     
8724     // If Offset is evenly divisible by Size, we can do this xform.
8725     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8726       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8727       
8728       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8729                                                             "tmp"), CI);
8730       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8731     }
8732   }
8733   return 0;
8734 }
8735
8736 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8737   // If the operands are integer typed then apply the integer transforms,
8738   // otherwise just apply the common ones.
8739   Value *Src = CI.getOperand(0);
8740   const Type *SrcTy = Src->getType();
8741   const Type *DestTy = CI.getType();
8742
8743   if (SrcTy->isInteger() && DestTy->isInteger()) {
8744     if (Instruction *Result = commonIntCastTransforms(CI))
8745       return Result;
8746   } else if (isa<PointerType>(SrcTy)) {
8747     if (Instruction *I = commonPointerCastTransforms(CI))
8748       return I;
8749   } else {
8750     if (Instruction *Result = commonCastTransforms(CI))
8751       return Result;
8752   }
8753
8754
8755   // Get rid of casts from one type to the same type. These are useless and can
8756   // be replaced by the operand.
8757   if (DestTy == Src->getType())
8758     return ReplaceInstUsesWith(CI, Src);
8759
8760   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8761     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8762     const Type *DstElTy = DstPTy->getElementType();
8763     const Type *SrcElTy = SrcPTy->getElementType();
8764     
8765     // If the address spaces don't match, don't eliminate the bitcast, which is
8766     // required for changing types.
8767     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8768       return 0;
8769     
8770     // If we are casting a malloc or alloca to a pointer to a type of the same
8771     // size, rewrite the allocation instruction to allocate the "right" type.
8772     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8773       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8774         return V;
8775     
8776     // If the source and destination are pointers, and this cast is equivalent
8777     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8778     // This can enhance SROA and other transforms that want type-safe pointers.
8779     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8780     unsigned NumZeros = 0;
8781     while (SrcElTy != DstElTy && 
8782            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8783            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8784       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8785       ++NumZeros;
8786     }
8787
8788     // If we found a path from the src to dest, create the getelementptr now.
8789     if (SrcElTy == DstElTy) {
8790       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8791       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8792                                        ((Instruction*) NULL));
8793     }
8794   }
8795
8796   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8797     if (SVI->hasOneUse()) {
8798       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8799       // a bitconvert to a vector with the same # elts.
8800       if (isa<VectorType>(DestTy) && 
8801           cast<VectorType>(DestTy)->getNumElements() ==
8802                 SVI->getType()->getNumElements() &&
8803           SVI->getType()->getNumElements() ==
8804             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8805         CastInst *Tmp;
8806         // If either of the operands is a cast from CI.getType(), then
8807         // evaluating the shuffle in the casted destination's type will allow
8808         // us to eliminate at least one cast.
8809         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8810              Tmp->getOperand(0)->getType() == DestTy) ||
8811             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8812              Tmp->getOperand(0)->getType() == DestTy)) {
8813           Value *LHS = InsertCastBefore(Instruction::BitCast,
8814                                         SVI->getOperand(0), DestTy, CI);
8815           Value *RHS = InsertCastBefore(Instruction::BitCast,
8816                                         SVI->getOperand(1), DestTy, CI);
8817           // Return a new shuffle vector.  Use the same element ID's, as we
8818           // know the vector types match #elts.
8819           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8820         }
8821       }
8822     }
8823   }
8824   return 0;
8825 }
8826
8827 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8828 ///   %C = or %A, %B
8829 ///   %D = select %cond, %C, %A
8830 /// into:
8831 ///   %C = select %cond, %B, 0
8832 ///   %D = or %A, %C
8833 ///
8834 /// Assuming that the specified instruction is an operand to the select, return
8835 /// a bitmask indicating which operands of this instruction are foldable if they
8836 /// equal the other incoming value of the select.
8837 ///
8838 static unsigned GetSelectFoldableOperands(Instruction *I) {
8839   switch (I->getOpcode()) {
8840   case Instruction::Add:
8841   case Instruction::Mul:
8842   case Instruction::And:
8843   case Instruction::Or:
8844   case Instruction::Xor:
8845     return 3;              // Can fold through either operand.
8846   case Instruction::Sub:   // Can only fold on the amount subtracted.
8847   case Instruction::Shl:   // Can only fold on the shift amount.
8848   case Instruction::LShr:
8849   case Instruction::AShr:
8850     return 1;
8851   default:
8852     return 0;              // Cannot fold
8853   }
8854 }
8855
8856 /// GetSelectFoldableConstant - For the same transformation as the previous
8857 /// function, return the identity constant that goes into the select.
8858 static Constant *GetSelectFoldableConstant(Instruction *I) {
8859   switch (I->getOpcode()) {
8860   default: assert(0 && "This cannot happen!"); abort();
8861   case Instruction::Add:
8862   case Instruction::Sub:
8863   case Instruction::Or:
8864   case Instruction::Xor:
8865   case Instruction::Shl:
8866   case Instruction::LShr:
8867   case Instruction::AShr:
8868     return Constant::getNullValue(I->getType());
8869   case Instruction::And:
8870     return Constant::getAllOnesValue(I->getType());
8871   case Instruction::Mul:
8872     return ConstantInt::get(I->getType(), 1);
8873   }
8874 }
8875
8876 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8877 /// have the same opcode and only one use each.  Try to simplify this.
8878 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8879                                           Instruction *FI) {
8880   if (TI->getNumOperands() == 1) {
8881     // If this is a non-volatile load or a cast from the same type,
8882     // merge.
8883     if (TI->isCast()) {
8884       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8885         return 0;
8886     } else {
8887       return 0;  // unknown unary op.
8888     }
8889
8890     // Fold this by inserting a select from the input values.
8891     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8892                                            FI->getOperand(0), SI.getName()+".v");
8893     InsertNewInstBefore(NewSI, SI);
8894     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8895                             TI->getType());
8896   }
8897
8898   // Only handle binary operators here.
8899   if (!isa<BinaryOperator>(TI))
8900     return 0;
8901
8902   // Figure out if the operations have any operands in common.
8903   Value *MatchOp, *OtherOpT, *OtherOpF;
8904   bool MatchIsOpZero;
8905   if (TI->getOperand(0) == FI->getOperand(0)) {
8906     MatchOp  = TI->getOperand(0);
8907     OtherOpT = TI->getOperand(1);
8908     OtherOpF = FI->getOperand(1);
8909     MatchIsOpZero = true;
8910   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8911     MatchOp  = TI->getOperand(1);
8912     OtherOpT = TI->getOperand(0);
8913     OtherOpF = FI->getOperand(0);
8914     MatchIsOpZero = false;
8915   } else if (!TI->isCommutative()) {
8916     return 0;
8917   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8918     MatchOp  = TI->getOperand(0);
8919     OtherOpT = TI->getOperand(1);
8920     OtherOpF = FI->getOperand(0);
8921     MatchIsOpZero = true;
8922   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8923     MatchOp  = TI->getOperand(1);
8924     OtherOpT = TI->getOperand(0);
8925     OtherOpF = FI->getOperand(1);
8926     MatchIsOpZero = true;
8927   } else {
8928     return 0;
8929   }
8930
8931   // If we reach here, they do have operations in common.
8932   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8933                                          OtherOpF, SI.getName()+".v");
8934   InsertNewInstBefore(NewSI, SI);
8935
8936   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8937     if (MatchIsOpZero)
8938       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8939     else
8940       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8941   }
8942   assert(0 && "Shouldn't get here");
8943   return 0;
8944 }
8945
8946 static bool isSelect01(Constant *C1, Constant *C2) {
8947   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
8948   if (!C1I)
8949     return false;
8950   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
8951   if (!C2I)
8952     return false;
8953   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
8954 }
8955
8956 /// FoldSelectIntoOp - Try fold the select into one of the operands to
8957 /// facilitate further optimization.
8958 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
8959                                             Value *FalseVal) {
8960   // See the comment above GetSelectFoldableOperands for a description of the
8961   // transformation we are doing here.
8962   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
8963     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8964         !isa<Constant>(FalseVal)) {
8965       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8966         unsigned OpToFold = 0;
8967         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8968           OpToFold = 1;
8969         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8970           OpToFold = 2;
8971         }
8972
8973         if (OpToFold) {
8974           Constant *C = GetSelectFoldableConstant(TVI);
8975           Value *OOp = TVI->getOperand(2-OpToFold);
8976           // Avoid creating select between 2 constants unless it's selecting
8977           // between 0 and 1.
8978           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
8979             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
8980             InsertNewInstBefore(NewSel, SI);
8981             NewSel->takeName(TVI);
8982             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8983               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8984             assert(0 && "Unknown instruction!!");
8985           }
8986         }
8987       }
8988     }
8989   }
8990
8991   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
8992     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8993         !isa<Constant>(TrueVal)) {
8994       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8995         unsigned OpToFold = 0;
8996         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8997           OpToFold = 1;
8998         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8999           OpToFold = 2;
9000         }
9001
9002         if (OpToFold) {
9003           Constant *C = GetSelectFoldableConstant(FVI);
9004           Value *OOp = FVI->getOperand(2-OpToFold);
9005           // Avoid creating select between 2 constants unless it's selecting
9006           // between 0 and 1.
9007           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9008             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9009             InsertNewInstBefore(NewSel, SI);
9010             NewSel->takeName(FVI);
9011             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9012               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9013             assert(0 && "Unknown instruction!!");
9014           }
9015         }
9016       }
9017     }
9018   }
9019
9020   return 0;
9021 }
9022
9023 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9024 /// ICmpInst as its first operand.
9025 ///
9026 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9027                                                    ICmpInst *ICI) {
9028   bool Changed = false;
9029   ICmpInst::Predicate Pred = ICI->getPredicate();
9030   Value *CmpLHS = ICI->getOperand(0);
9031   Value *CmpRHS = ICI->getOperand(1);
9032   Value *TrueVal = SI.getTrueValue();
9033   Value *FalseVal = SI.getFalseValue();
9034
9035   // Check cases where the comparison is with a constant that
9036   // can be adjusted to fit the min/max idiom. We may edit ICI in
9037   // place here, so make sure the select is the only user.
9038   if (ICI->hasOneUse())
9039     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9040       switch (Pred) {
9041       default: break;
9042       case ICmpInst::ICMP_ULT:
9043       case ICmpInst::ICMP_SLT: {
9044         // X < MIN ? T : F  -->  F
9045         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9046           return ReplaceInstUsesWith(SI, FalseVal);
9047         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9048         Constant *AdjustedRHS = SubOne(CI);
9049         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9050             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9051           Pred = ICmpInst::getSwappedPredicate(Pred);
9052           CmpRHS = AdjustedRHS;
9053           std::swap(FalseVal, TrueVal);
9054           ICI->setPredicate(Pred);
9055           ICI->setOperand(1, CmpRHS);
9056           SI.setOperand(1, TrueVal);
9057           SI.setOperand(2, FalseVal);
9058           Changed = true;
9059         }
9060         break;
9061       }
9062       case ICmpInst::ICMP_UGT:
9063       case ICmpInst::ICMP_SGT: {
9064         // X > MAX ? T : F  -->  F
9065         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9066           return ReplaceInstUsesWith(SI, FalseVal);
9067         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9068         Constant *AdjustedRHS = AddOne(CI);
9069         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9070             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9071           Pred = ICmpInst::getSwappedPredicate(Pred);
9072           CmpRHS = AdjustedRHS;
9073           std::swap(FalseVal, TrueVal);
9074           ICI->setPredicate(Pred);
9075           ICI->setOperand(1, CmpRHS);
9076           SI.setOperand(1, TrueVal);
9077           SI.setOperand(2, FalseVal);
9078           Changed = true;
9079         }
9080         break;
9081       }
9082       }
9083
9084       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9085       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9086       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9087       if (match(TrueVal, m_ConstantInt<-1>()) &&
9088           match(FalseVal, m_ConstantInt<0>()))
9089         Pred = ICI->getPredicate();
9090       else if (match(TrueVal, m_ConstantInt<0>()) &&
9091                match(FalseVal, m_ConstantInt<-1>()))
9092         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9093       
9094       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9095         // If we are just checking for a icmp eq of a single bit and zext'ing it
9096         // to an integer, then shift the bit to the appropriate place and then
9097         // cast to integer to avoid the comparison.
9098         const APInt &Op1CV = CI->getValue();
9099     
9100         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9101         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9102         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9103             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9104           Value *In = ICI->getOperand(0);
9105           Value *Sh = ConstantInt::get(In->getType(),
9106                                        In->getType()->getPrimitiveSizeInBits()-1);
9107           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9108                                                           In->getName()+".lobit"),
9109                                    *ICI);
9110           if (In->getType() != SI.getType())
9111             In = CastInst::CreateIntegerCast(In, SI.getType(),
9112                                              true/*SExt*/, "tmp", ICI);
9113     
9114           if (Pred == ICmpInst::ICMP_SGT)
9115             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9116                                        In->getName()+".not"), *ICI);
9117     
9118           return ReplaceInstUsesWith(SI, In);
9119         }
9120       }
9121     }
9122
9123   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9124     // Transform (X == Y) ? X : Y  -> Y
9125     if (Pred == ICmpInst::ICMP_EQ)
9126       return ReplaceInstUsesWith(SI, FalseVal);
9127     // Transform (X != Y) ? X : Y  -> X
9128     if (Pred == ICmpInst::ICMP_NE)
9129       return ReplaceInstUsesWith(SI, TrueVal);
9130     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9131
9132   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9133     // Transform (X == Y) ? Y : X  -> X
9134     if (Pred == ICmpInst::ICMP_EQ)
9135       return ReplaceInstUsesWith(SI, FalseVal);
9136     // Transform (X != Y) ? Y : X  -> Y
9137     if (Pred == ICmpInst::ICMP_NE)
9138       return ReplaceInstUsesWith(SI, TrueVal);
9139     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9140   }
9141
9142   /// NOTE: if we wanted to, this is where to detect integer ABS
9143
9144   return Changed ? &SI : 0;
9145 }
9146
9147 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9148   Value *CondVal = SI.getCondition();
9149   Value *TrueVal = SI.getTrueValue();
9150   Value *FalseVal = SI.getFalseValue();
9151
9152   // select true, X, Y  -> X
9153   // select false, X, Y -> Y
9154   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9155     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9156
9157   // select C, X, X -> X
9158   if (TrueVal == FalseVal)
9159     return ReplaceInstUsesWith(SI, TrueVal);
9160
9161   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9162     return ReplaceInstUsesWith(SI, FalseVal);
9163   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9164     return ReplaceInstUsesWith(SI, TrueVal);
9165   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9166     if (isa<Constant>(TrueVal))
9167       return ReplaceInstUsesWith(SI, TrueVal);
9168     else
9169       return ReplaceInstUsesWith(SI, FalseVal);
9170   }
9171
9172   if (SI.getType() == Type::Int1Ty) {
9173     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9174       if (C->getZExtValue()) {
9175         // Change: A = select B, true, C --> A = or B, C
9176         return BinaryOperator::CreateOr(CondVal, FalseVal);
9177       } else {
9178         // Change: A = select B, false, C --> A = and !B, C
9179         Value *NotCond =
9180           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9181                                              "not."+CondVal->getName()), SI);
9182         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9183       }
9184     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9185       if (C->getZExtValue() == false) {
9186         // Change: A = select B, C, false --> A = and B, C
9187         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9188       } else {
9189         // Change: A = select B, C, true --> A = or !B, C
9190         Value *NotCond =
9191           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9192                                              "not."+CondVal->getName()), SI);
9193         return BinaryOperator::CreateOr(NotCond, TrueVal);
9194       }
9195     }
9196     
9197     // select a, b, a  -> a&b
9198     // select a, a, b  -> a|b
9199     if (CondVal == TrueVal)
9200       return BinaryOperator::CreateOr(CondVal, FalseVal);
9201     else if (CondVal == FalseVal)
9202       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9203   }
9204
9205   // Selecting between two integer constants?
9206   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9207     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9208       // select C, 1, 0 -> zext C to int
9209       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9210         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9211       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9212         // select C, 0, 1 -> zext !C to int
9213         Value *NotCond =
9214           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9215                                                "not."+CondVal->getName()), SI);
9216         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9217       }
9218
9219       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9220
9221         // (x <s 0) ? -1 : 0 -> ashr x, 31
9222         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9223           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9224             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9225               // The comparison constant and the result are not neccessarily the
9226               // same width. Make an all-ones value by inserting a AShr.
9227               Value *X = IC->getOperand(0);
9228               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
9229               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
9230               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
9231                                                         ShAmt, "ones");
9232               InsertNewInstBefore(SRA, SI);
9233
9234               // Then cast to the appropriate width.
9235               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
9236             }
9237           }
9238
9239
9240         // If one of the constants is zero (we know they can't both be) and we
9241         // have an icmp instruction with zero, and we have an 'and' with the
9242         // non-constant value, eliminate this whole mess.  This corresponds to
9243         // cases like this: ((X & 27) ? 27 : 0)
9244         if (TrueValC->isZero() || FalseValC->isZero())
9245           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9246               cast<Constant>(IC->getOperand(1))->isNullValue())
9247             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9248               if (ICA->getOpcode() == Instruction::And &&
9249                   isa<ConstantInt>(ICA->getOperand(1)) &&
9250                   (ICA->getOperand(1) == TrueValC ||
9251                    ICA->getOperand(1) == FalseValC) &&
9252                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9253                 // Okay, now we know that everything is set up, we just don't
9254                 // know whether we have a icmp_ne or icmp_eq and whether the 
9255                 // true or false val is the zero.
9256                 bool ShouldNotVal = !TrueValC->isZero();
9257                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9258                 Value *V = ICA;
9259                 if (ShouldNotVal)
9260                   V = InsertNewInstBefore(BinaryOperator::Create(
9261                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9262                 return ReplaceInstUsesWith(SI, V);
9263               }
9264       }
9265     }
9266
9267   // See if we are selecting two values based on a comparison of the two values.
9268   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9269     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9270       // Transform (X == Y) ? X : Y  -> Y
9271       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9272         // This is not safe in general for floating point:  
9273         // consider X== -0, Y== +0.
9274         // It becomes safe if either operand is a nonzero constant.
9275         ConstantFP *CFPt, *CFPf;
9276         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9277               !CFPt->getValueAPF().isZero()) ||
9278             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9279              !CFPf->getValueAPF().isZero()))
9280         return ReplaceInstUsesWith(SI, FalseVal);
9281       }
9282       // Transform (X != Y) ? X : Y  -> X
9283       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9284         return ReplaceInstUsesWith(SI, TrueVal);
9285       // NOTE: if we wanted to, this is where to detect MIN/MAX
9286
9287     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9288       // Transform (X == Y) ? Y : X  -> X
9289       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9290         // This is not safe in general for floating point:  
9291         // consider X== -0, Y== +0.
9292         // It becomes safe if either operand is a nonzero constant.
9293         ConstantFP *CFPt, *CFPf;
9294         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9295               !CFPt->getValueAPF().isZero()) ||
9296             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9297              !CFPf->getValueAPF().isZero()))
9298           return ReplaceInstUsesWith(SI, FalseVal);
9299       }
9300       // Transform (X != Y) ? Y : X  -> Y
9301       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9302         return ReplaceInstUsesWith(SI, TrueVal);
9303       // NOTE: if we wanted to, this is where to detect MIN/MAX
9304     }
9305     // NOTE: if we wanted to, this is where to detect ABS
9306   }
9307
9308   // See if we are selecting two values based on a comparison of the two values.
9309   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9310     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9311       return Result;
9312
9313   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9314     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9315       if (TI->hasOneUse() && FI->hasOneUse()) {
9316         Instruction *AddOp = 0, *SubOp = 0;
9317
9318         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9319         if (TI->getOpcode() == FI->getOpcode())
9320           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9321             return IV;
9322
9323         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9324         // even legal for FP.
9325         if (TI->getOpcode() == Instruction::Sub &&
9326             FI->getOpcode() == Instruction::Add) {
9327           AddOp = FI; SubOp = TI;
9328         } else if (FI->getOpcode() == Instruction::Sub &&
9329                    TI->getOpcode() == Instruction::Add) {
9330           AddOp = TI; SubOp = FI;
9331         }
9332
9333         if (AddOp) {
9334           Value *OtherAddOp = 0;
9335           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9336             OtherAddOp = AddOp->getOperand(1);
9337           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9338             OtherAddOp = AddOp->getOperand(0);
9339           }
9340
9341           if (OtherAddOp) {
9342             // So at this point we know we have (Y -> OtherAddOp):
9343             //        select C, (add X, Y), (sub X, Z)
9344             Value *NegVal;  // Compute -Z
9345             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9346               NegVal = ConstantExpr::getNeg(C);
9347             } else {
9348               NegVal = InsertNewInstBefore(
9349                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9350             }
9351
9352             Value *NewTrueOp = OtherAddOp;
9353             Value *NewFalseOp = NegVal;
9354             if (AddOp != TI)
9355               std::swap(NewTrueOp, NewFalseOp);
9356             Instruction *NewSel =
9357               SelectInst::Create(CondVal, NewTrueOp,
9358                                  NewFalseOp, SI.getName() + ".p");
9359
9360             NewSel = InsertNewInstBefore(NewSel, SI);
9361             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9362           }
9363         }
9364       }
9365
9366   // See if we can fold the select into one of our operands.
9367   if (SI.getType()->isInteger()) {
9368     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9369     if (FoldI)
9370       return FoldI;
9371   }
9372
9373   if (BinaryOperator::isNot(CondVal)) {
9374     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9375     SI.setOperand(1, FalseVal);
9376     SI.setOperand(2, TrueVal);
9377     return &SI;
9378   }
9379
9380   return 0;
9381 }
9382
9383 /// EnforceKnownAlignment - If the specified pointer points to an object that
9384 /// we control, modify the object's alignment to PrefAlign. This isn't
9385 /// often possible though. If alignment is important, a more reliable approach
9386 /// is to simply align all global variables and allocation instructions to
9387 /// their preferred alignment from the beginning.
9388 ///
9389 static unsigned EnforceKnownAlignment(Value *V,
9390                                       unsigned Align, unsigned PrefAlign) {
9391
9392   User *U = dyn_cast<User>(V);
9393   if (!U) return Align;
9394
9395   switch (getOpcode(U)) {
9396   default: break;
9397   case Instruction::BitCast:
9398     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9399   case Instruction::GetElementPtr: {
9400     // If all indexes are zero, it is just the alignment of the base pointer.
9401     bool AllZeroOperands = true;
9402     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9403       if (!isa<Constant>(*i) ||
9404           !cast<Constant>(*i)->isNullValue()) {
9405         AllZeroOperands = false;
9406         break;
9407       }
9408
9409     if (AllZeroOperands) {
9410       // Treat this like a bitcast.
9411       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9412     }
9413     break;
9414   }
9415   }
9416
9417   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9418     // If there is a large requested alignment and we can, bump up the alignment
9419     // of the global.
9420     if (!GV->isDeclaration()) {
9421       if (GV->getAlignment() >= PrefAlign)
9422         Align = GV->getAlignment();
9423       else {
9424         GV->setAlignment(PrefAlign);
9425         Align = PrefAlign;
9426       }
9427     }
9428   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9429     // If there is a requested alignment and if this is an alloca, round up.  We
9430     // don't do this for malloc, because some systems can't respect the request.
9431     if (isa<AllocaInst>(AI)) {
9432       if (AI->getAlignment() >= PrefAlign)
9433         Align = AI->getAlignment();
9434       else {
9435         AI->setAlignment(PrefAlign);
9436         Align = PrefAlign;
9437       }
9438     }
9439   }
9440
9441   return Align;
9442 }
9443
9444 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9445 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9446 /// and it is more than the alignment of the ultimate object, see if we can
9447 /// increase the alignment of the ultimate object, making this check succeed.
9448 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9449                                                   unsigned PrefAlign) {
9450   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9451                       sizeof(PrefAlign) * CHAR_BIT;
9452   APInt Mask = APInt::getAllOnesValue(BitWidth);
9453   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9454   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9455   unsigned TrailZ = KnownZero.countTrailingOnes();
9456   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9457
9458   if (PrefAlign > Align)
9459     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9460   
9461     // We don't need to make any adjustment.
9462   return Align;
9463 }
9464
9465 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9466   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9467   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9468   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9469   unsigned CopyAlign = MI->getAlignment();
9470
9471   if (CopyAlign < MinAlign) {
9472     MI->setAlignment(MinAlign);
9473     return MI;
9474   }
9475   
9476   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9477   // load/store.
9478   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9479   if (MemOpLength == 0) return 0;
9480   
9481   // Source and destination pointer types are always "i8*" for intrinsic.  See
9482   // if the size is something we can handle with a single primitive load/store.
9483   // A single load+store correctly handles overlapping memory in the memmove
9484   // case.
9485   unsigned Size = MemOpLength->getZExtValue();
9486   if (Size == 0) return MI;  // Delete this mem transfer.
9487   
9488   if (Size > 8 || (Size&(Size-1)))
9489     return 0;  // If not 1/2/4/8 bytes, exit.
9490   
9491   // Use an integer load+store unless we can find something better.
9492   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9493   
9494   // Memcpy forces the use of i8* for the source and destination.  That means
9495   // that if you're using memcpy to move one double around, you'll get a cast
9496   // from double* to i8*.  We'd much rather use a double load+store rather than
9497   // an i64 load+store, here because this improves the odds that the source or
9498   // dest address will be promotable.  See if we can find a better type than the
9499   // integer datatype.
9500   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9501     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9502     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9503       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9504       // down through these levels if so.
9505       while (!SrcETy->isSingleValueType()) {
9506         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9507           if (STy->getNumElements() == 1)
9508             SrcETy = STy->getElementType(0);
9509           else
9510             break;
9511         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9512           if (ATy->getNumElements() == 1)
9513             SrcETy = ATy->getElementType();
9514           else
9515             break;
9516         } else
9517           break;
9518       }
9519       
9520       if (SrcETy->isSingleValueType())
9521         NewPtrTy = PointerType::getUnqual(SrcETy);
9522     }
9523   }
9524   
9525   
9526   // If the memcpy/memmove provides better alignment info than we can
9527   // infer, use it.
9528   SrcAlign = std::max(SrcAlign, CopyAlign);
9529   DstAlign = std::max(DstAlign, CopyAlign);
9530   
9531   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9532   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9533   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9534   InsertNewInstBefore(L, *MI);
9535   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9536
9537   // Set the size of the copy to 0, it will be deleted on the next iteration.
9538   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9539   return MI;
9540 }
9541
9542 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9543   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9544   if (MI->getAlignment() < Alignment) {
9545     MI->setAlignment(Alignment);
9546     return MI;
9547   }
9548   
9549   // Extract the length and alignment and fill if they are constant.
9550   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9551   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9552   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9553     return 0;
9554   uint64_t Len = LenC->getZExtValue();
9555   Alignment = MI->getAlignment();
9556   
9557   // If the length is zero, this is a no-op
9558   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9559   
9560   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9561   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9562     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9563     
9564     Value *Dest = MI->getDest();
9565     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9566
9567     // Alignment 0 is identity for alignment 1 for memset, but not store.
9568     if (Alignment == 0) Alignment = 1;
9569     
9570     // Extract the fill value and store.
9571     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9572     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9573                                       Alignment), *MI);
9574     
9575     // Set the size of the copy to 0, it will be deleted on the next iteration.
9576     MI->setLength(Constant::getNullValue(LenC->getType()));
9577     return MI;
9578   }
9579
9580   return 0;
9581 }
9582
9583
9584 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9585 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9586 /// the heavy lifting.
9587 ///
9588 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9589   // If the caller function is nounwind, mark the call as nounwind, even if the
9590   // callee isn't.
9591   if (CI.getParent()->getParent()->doesNotThrow() &&
9592       !CI.doesNotThrow()) {
9593     CI.setDoesNotThrow();
9594     return &CI;
9595   }
9596   
9597   
9598   
9599   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9600   if (!II) return visitCallSite(&CI);
9601   
9602   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9603   // visitCallSite.
9604   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9605     bool Changed = false;
9606
9607     // memmove/cpy/set of zero bytes is a noop.
9608     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9609       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9610
9611       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9612         if (CI->getZExtValue() == 1) {
9613           // Replace the instruction with just byte operations.  We would
9614           // transform other cases to loads/stores, but we don't know if
9615           // alignment is sufficient.
9616         }
9617     }
9618
9619     // If we have a memmove and the source operation is a constant global,
9620     // then the source and dest pointers can't alias, so we can change this
9621     // into a call to memcpy.
9622     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9623       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9624         if (GVSrc->isConstant()) {
9625           Module *M = CI.getParent()->getParent()->getParent();
9626           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9627           const Type *Tys[1];
9628           Tys[0] = CI.getOperand(3)->getType();
9629           CI.setOperand(0, 
9630                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9631           Changed = true;
9632         }
9633
9634       // memmove(x,x,size) -> noop.
9635       if (MMI->getSource() == MMI->getDest())
9636         return EraseInstFromFunction(CI);
9637     }
9638
9639     // If we can determine a pointer alignment that is bigger than currently
9640     // set, update the alignment.
9641     if (isa<MemTransferInst>(MI)) {
9642       if (Instruction *I = SimplifyMemTransfer(MI))
9643         return I;
9644     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9645       if (Instruction *I = SimplifyMemSet(MSI))
9646         return I;
9647     }
9648           
9649     if (Changed) return II;
9650   }
9651   
9652   switch (II->getIntrinsicID()) {
9653   default: break;
9654   case Intrinsic::bswap:
9655     // bswap(bswap(x)) -> x
9656     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9657       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9658         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9659     break;
9660   case Intrinsic::ppc_altivec_lvx:
9661   case Intrinsic::ppc_altivec_lvxl:
9662   case Intrinsic::x86_sse_loadu_ps:
9663   case Intrinsic::x86_sse2_loadu_pd:
9664   case Intrinsic::x86_sse2_loadu_dq:
9665     // Turn PPC lvx     -> load if the pointer is known aligned.
9666     // Turn X86 loadups -> load if the pointer is known aligned.
9667     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9668       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9669                                        PointerType::getUnqual(II->getType()),
9670                                        CI);
9671       return new LoadInst(Ptr);
9672     }
9673     break;
9674   case Intrinsic::ppc_altivec_stvx:
9675   case Intrinsic::ppc_altivec_stvxl:
9676     // Turn stvx -> store if the pointer is known aligned.
9677     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9678       const Type *OpPtrTy = 
9679         PointerType::getUnqual(II->getOperand(1)->getType());
9680       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9681       return new StoreInst(II->getOperand(1), Ptr);
9682     }
9683     break;
9684   case Intrinsic::x86_sse_storeu_ps:
9685   case Intrinsic::x86_sse2_storeu_pd:
9686   case Intrinsic::x86_sse2_storeu_dq:
9687     // Turn X86 storeu -> store if the pointer is known aligned.
9688     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9689       const Type *OpPtrTy = 
9690         PointerType::getUnqual(II->getOperand(2)->getType());
9691       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9692       return new StoreInst(II->getOperand(2), Ptr);
9693     }
9694     break;
9695     
9696   case Intrinsic::x86_sse_cvttss2si: {
9697     // These intrinsics only demands the 0th element of its input vector.  If
9698     // we can simplify the input based on that, do so now.
9699     unsigned VWidth =
9700       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9701     APInt DemandedElts(VWidth, 1);
9702     APInt UndefElts(VWidth, 0);
9703     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9704                                               UndefElts)) {
9705       II->setOperand(1, V);
9706       return II;
9707     }
9708     break;
9709   }
9710     
9711   case Intrinsic::ppc_altivec_vperm:
9712     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9713     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9714       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9715       
9716       // Check that all of the elements are integer constants or undefs.
9717       bool AllEltsOk = true;
9718       for (unsigned i = 0; i != 16; ++i) {
9719         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9720             !isa<UndefValue>(Mask->getOperand(i))) {
9721           AllEltsOk = false;
9722           break;
9723         }
9724       }
9725       
9726       if (AllEltsOk) {
9727         // Cast the input vectors to byte vectors.
9728         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9729         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9730         Value *Result = UndefValue::get(Op0->getType());
9731         
9732         // Only extract each element once.
9733         Value *ExtractedElts[32];
9734         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9735         
9736         for (unsigned i = 0; i != 16; ++i) {
9737           if (isa<UndefValue>(Mask->getOperand(i)))
9738             continue;
9739           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9740           Idx &= 31;  // Match the hardware behavior.
9741           
9742           if (ExtractedElts[Idx] == 0) {
9743             Instruction *Elt = 
9744               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9745             InsertNewInstBefore(Elt, CI);
9746             ExtractedElts[Idx] = Elt;
9747           }
9748         
9749           // Insert this value into the result vector.
9750           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9751                                              i, "tmp");
9752           InsertNewInstBefore(cast<Instruction>(Result), CI);
9753         }
9754         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9755       }
9756     }
9757     break;
9758
9759   case Intrinsic::stackrestore: {
9760     // If the save is right next to the restore, remove the restore.  This can
9761     // happen when variable allocas are DCE'd.
9762     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9763       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9764         BasicBlock::iterator BI = SS;
9765         if (&*++BI == II)
9766           return EraseInstFromFunction(CI);
9767       }
9768     }
9769     
9770     // Scan down this block to see if there is another stack restore in the
9771     // same block without an intervening call/alloca.
9772     BasicBlock::iterator BI = II;
9773     TerminatorInst *TI = II->getParent()->getTerminator();
9774     bool CannotRemove = false;
9775     for (++BI; &*BI != TI; ++BI) {
9776       if (isa<AllocaInst>(BI)) {
9777         CannotRemove = true;
9778         break;
9779       }
9780       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9781         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9782           // If there is a stackrestore below this one, remove this one.
9783           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9784             return EraseInstFromFunction(CI);
9785           // Otherwise, ignore the intrinsic.
9786         } else {
9787           // If we found a non-intrinsic call, we can't remove the stack
9788           // restore.
9789           CannotRemove = true;
9790           break;
9791         }
9792       }
9793     }
9794     
9795     // If the stack restore is in a return/unwind block and if there are no
9796     // allocas or calls between the restore and the return, nuke the restore.
9797     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9798       return EraseInstFromFunction(CI);
9799     break;
9800   }
9801   }
9802
9803   return visitCallSite(II);
9804 }
9805
9806 // InvokeInst simplification
9807 //
9808 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9809   return visitCallSite(&II);
9810 }
9811
9812 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9813 /// passed through the varargs area, we can eliminate the use of the cast.
9814 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9815                                          const CastInst * const CI,
9816                                          const TargetData * const TD,
9817                                          const int ix) {
9818   if (!CI->isLosslessCast())
9819     return false;
9820
9821   // The size of ByVal arguments is derived from the type, so we
9822   // can't change to a type with a different size.  If the size were
9823   // passed explicitly we could avoid this check.
9824   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9825     return true;
9826
9827   const Type* SrcTy = 
9828             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9829   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9830   if (!SrcTy->isSized() || !DstTy->isSized())
9831     return false;
9832   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9833     return false;
9834   return true;
9835 }
9836
9837 // visitCallSite - Improvements for call and invoke instructions.
9838 //
9839 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9840   bool Changed = false;
9841
9842   // If the callee is a constexpr cast of a function, attempt to move the cast
9843   // to the arguments of the call/invoke.
9844   if (transformConstExprCastCall(CS)) return 0;
9845
9846   Value *Callee = CS.getCalledValue();
9847
9848   if (Function *CalleeF = dyn_cast<Function>(Callee))
9849     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9850       Instruction *OldCall = CS.getInstruction();
9851       // If the call and callee calling conventions don't match, this call must
9852       // be unreachable, as the call is undefined.
9853       new StoreInst(ConstantInt::getTrue(),
9854                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9855                                     OldCall);
9856       if (!OldCall->use_empty())
9857         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9858       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9859         return EraseInstFromFunction(*OldCall);
9860       return 0;
9861     }
9862
9863   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9864     // This instruction is not reachable, just remove it.  We insert a store to
9865     // undef so that we know that this code is not reachable, despite the fact
9866     // that we can't modify the CFG here.
9867     new StoreInst(ConstantInt::getTrue(),
9868                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9869                   CS.getInstruction());
9870
9871     if (!CS.getInstruction()->use_empty())
9872       CS.getInstruction()->
9873         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9874
9875     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9876       // Don't break the CFG, insert a dummy cond branch.
9877       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9878                          ConstantInt::getTrue(), II);
9879     }
9880     return EraseInstFromFunction(*CS.getInstruction());
9881   }
9882
9883   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9884     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9885       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9886         return transformCallThroughTrampoline(CS);
9887
9888   const PointerType *PTy = cast<PointerType>(Callee->getType());
9889   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9890   if (FTy->isVarArg()) {
9891     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9892     // See if we can optimize any arguments passed through the varargs area of
9893     // the call.
9894     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9895            E = CS.arg_end(); I != E; ++I, ++ix) {
9896       CastInst *CI = dyn_cast<CastInst>(*I);
9897       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9898         *I = CI->getOperand(0);
9899         Changed = true;
9900       }
9901     }
9902   }
9903
9904   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9905     // Inline asm calls cannot throw - mark them 'nounwind'.
9906     CS.setDoesNotThrow();
9907     Changed = true;
9908   }
9909
9910   return Changed ? CS.getInstruction() : 0;
9911 }
9912
9913 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9914 // attempt to move the cast to the arguments of the call/invoke.
9915 //
9916 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9917   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9918   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9919   if (CE->getOpcode() != Instruction::BitCast || 
9920       !isa<Function>(CE->getOperand(0)))
9921     return false;
9922   Function *Callee = cast<Function>(CE->getOperand(0));
9923   Instruction *Caller = CS.getInstruction();
9924   const AttrListPtr &CallerPAL = CS.getAttributes();
9925
9926   // Okay, this is a cast from a function to a different type.  Unless doing so
9927   // would cause a type conversion of one of our arguments, change this call to
9928   // be a direct call with arguments casted to the appropriate types.
9929   //
9930   const FunctionType *FT = Callee->getFunctionType();
9931   const Type *OldRetTy = Caller->getType();
9932   const Type *NewRetTy = FT->getReturnType();
9933
9934   if (isa<StructType>(NewRetTy))
9935     return false; // TODO: Handle multiple return values.
9936
9937   // Check to see if we are changing the return type...
9938   if (OldRetTy != NewRetTy) {
9939     if (Callee->isDeclaration() &&
9940         // Conversion is ok if changing from one pointer type to another or from
9941         // a pointer to an integer of the same size.
9942         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9943           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9944       return false;   // Cannot transform this return value.
9945
9946     if (!Caller->use_empty() &&
9947         // void -> non-void is handled specially
9948         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9949       return false;   // Cannot transform this return value.
9950
9951     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9952       Attributes RAttrs = CallerPAL.getRetAttributes();
9953       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9954         return false;   // Attribute not compatible with transformed value.
9955     }
9956
9957     // If the callsite is an invoke instruction, and the return value is used by
9958     // a PHI node in a successor, we cannot change the return type of the call
9959     // because there is no place to put the cast instruction (without breaking
9960     // the critical edge).  Bail out in this case.
9961     if (!Caller->use_empty())
9962       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9963         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9964              UI != E; ++UI)
9965           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9966             if (PN->getParent() == II->getNormalDest() ||
9967                 PN->getParent() == II->getUnwindDest())
9968               return false;
9969   }
9970
9971   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9972   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9973
9974   CallSite::arg_iterator AI = CS.arg_begin();
9975   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9976     const Type *ParamTy = FT->getParamType(i);
9977     const Type *ActTy = (*AI)->getType();
9978
9979     if (!CastInst::isCastable(ActTy, ParamTy))
9980       return false;   // Cannot transform this parameter value.
9981
9982     if (CallerPAL.getParamAttributes(i + 1) 
9983         & Attribute::typeIncompatible(ParamTy))
9984       return false;   // Attribute not compatible with transformed value.
9985
9986     // Converting from one pointer type to another or between a pointer and an
9987     // integer of the same size is safe even if we do not have a body.
9988     bool isConvertible = ActTy == ParamTy ||
9989       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9990        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9991     if (Callee->isDeclaration() && !isConvertible) return false;
9992   }
9993
9994   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9995       Callee->isDeclaration())
9996     return false;   // Do not delete arguments unless we have a function body.
9997
9998   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9999       !CallerPAL.isEmpty())
10000     // In this case we have more arguments than the new function type, but we
10001     // won't be dropping them.  Check that these extra arguments have attributes
10002     // that are compatible with being a vararg call argument.
10003     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10004       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10005         break;
10006       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10007       if (PAttrs & Attribute::VarArgsIncompatible)
10008         return false;
10009     }
10010
10011   // Okay, we decided that this is a safe thing to do: go ahead and start
10012   // inserting cast instructions as necessary...
10013   std::vector<Value*> Args;
10014   Args.reserve(NumActualArgs);
10015   SmallVector<AttributeWithIndex, 8> attrVec;
10016   attrVec.reserve(NumCommonArgs);
10017
10018   // Get any return attributes.
10019   Attributes RAttrs = CallerPAL.getRetAttributes();
10020
10021   // If the return value is not being used, the type may not be compatible
10022   // with the existing attributes.  Wipe out any problematic attributes.
10023   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10024
10025   // Add the new return attributes.
10026   if (RAttrs)
10027     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10028
10029   AI = CS.arg_begin();
10030   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10031     const Type *ParamTy = FT->getParamType(i);
10032     if ((*AI)->getType() == ParamTy) {
10033       Args.push_back(*AI);
10034     } else {
10035       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10036           false, ParamTy, false);
10037       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10038       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10039     }
10040
10041     // Add any parameter attributes.
10042     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10043       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10044   }
10045
10046   // If the function takes more arguments than the call was taking, add them
10047   // now...
10048   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10049     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10050
10051   // If we are removing arguments to the function, emit an obnoxious warning...
10052   if (FT->getNumParams() < NumActualArgs) {
10053     if (!FT->isVarArg()) {
10054       cerr << "WARNING: While resolving call to function '"
10055            << Callee->getName() << "' arguments were dropped!\n";
10056     } else {
10057       // Add all of the arguments in their promoted form to the arg list...
10058       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10059         const Type *PTy = getPromotedType((*AI)->getType());
10060         if (PTy != (*AI)->getType()) {
10061           // Must promote to pass through va_arg area!
10062           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10063                                                                 PTy, false);
10064           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10065           InsertNewInstBefore(Cast, *Caller);
10066           Args.push_back(Cast);
10067         } else {
10068           Args.push_back(*AI);
10069         }
10070
10071         // Add any parameter attributes.
10072         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10073           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10074       }
10075     }
10076   }
10077
10078   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10079     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10080
10081   if (NewRetTy == Type::VoidTy)
10082     Caller->setName("");   // Void type should not have a name.
10083
10084   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10085
10086   Instruction *NC;
10087   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10088     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10089                             Args.begin(), Args.end(),
10090                             Caller->getName(), Caller);
10091     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10092     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10093   } else {
10094     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10095                           Caller->getName(), Caller);
10096     CallInst *CI = cast<CallInst>(Caller);
10097     if (CI->isTailCall())
10098       cast<CallInst>(NC)->setTailCall();
10099     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10100     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10101   }
10102
10103   // Insert a cast of the return type as necessary.
10104   Value *NV = NC;
10105   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10106     if (NV->getType() != Type::VoidTy) {
10107       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10108                                                             OldRetTy, false);
10109       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10110
10111       // If this is an invoke instruction, we should insert it after the first
10112       // non-phi, instruction in the normal successor block.
10113       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10114         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10115         InsertNewInstBefore(NC, *I);
10116       } else {
10117         // Otherwise, it's a call, just insert cast right after the call instr
10118         InsertNewInstBefore(NC, *Caller);
10119       }
10120       AddUsersToWorkList(*Caller);
10121     } else {
10122       NV = UndefValue::get(Caller->getType());
10123     }
10124   }
10125
10126   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10127     Caller->replaceAllUsesWith(NV);
10128   Caller->eraseFromParent();
10129   RemoveFromWorkList(Caller);
10130   return true;
10131 }
10132
10133 // transformCallThroughTrampoline - Turn a call to a function created by the
10134 // init_trampoline intrinsic into a direct call to the underlying function.
10135 //
10136 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10137   Value *Callee = CS.getCalledValue();
10138   const PointerType *PTy = cast<PointerType>(Callee->getType());
10139   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10140   const AttrListPtr &Attrs = CS.getAttributes();
10141
10142   // If the call already has the 'nest' attribute somewhere then give up -
10143   // otherwise 'nest' would occur twice after splicing in the chain.
10144   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10145     return 0;
10146
10147   IntrinsicInst *Tramp =
10148     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10149
10150   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10151   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10152   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10153
10154   const AttrListPtr &NestAttrs = NestF->getAttributes();
10155   if (!NestAttrs.isEmpty()) {
10156     unsigned NestIdx = 1;
10157     const Type *NestTy = 0;
10158     Attributes NestAttr = Attribute::None;
10159
10160     // Look for a parameter marked with the 'nest' attribute.
10161     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10162          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10163       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10164         // Record the parameter type and any other attributes.
10165         NestTy = *I;
10166         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10167         break;
10168       }
10169
10170     if (NestTy) {
10171       Instruction *Caller = CS.getInstruction();
10172       std::vector<Value*> NewArgs;
10173       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10174
10175       SmallVector<AttributeWithIndex, 8> NewAttrs;
10176       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10177
10178       // Insert the nest argument into the call argument list, which may
10179       // mean appending it.  Likewise for attributes.
10180
10181       // Add any result attributes.
10182       if (Attributes Attr = Attrs.getRetAttributes())
10183         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10184
10185       {
10186         unsigned Idx = 1;
10187         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10188         do {
10189           if (Idx == NestIdx) {
10190             // Add the chain argument and attributes.
10191             Value *NestVal = Tramp->getOperand(3);
10192             if (NestVal->getType() != NestTy)
10193               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10194             NewArgs.push_back(NestVal);
10195             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10196           }
10197
10198           if (I == E)
10199             break;
10200
10201           // Add the original argument and attributes.
10202           NewArgs.push_back(*I);
10203           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10204             NewAttrs.push_back
10205               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10206
10207           ++Idx, ++I;
10208         } while (1);
10209       }
10210
10211       // Add any function attributes.
10212       if (Attributes Attr = Attrs.getFnAttributes())
10213         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10214
10215       // The trampoline may have been bitcast to a bogus type (FTy).
10216       // Handle this by synthesizing a new function type, equal to FTy
10217       // with the chain parameter inserted.
10218
10219       std::vector<const Type*> NewTypes;
10220       NewTypes.reserve(FTy->getNumParams()+1);
10221
10222       // Insert the chain's type into the list of parameter types, which may
10223       // mean appending it.
10224       {
10225         unsigned Idx = 1;
10226         FunctionType::param_iterator I = FTy->param_begin(),
10227           E = FTy->param_end();
10228
10229         do {
10230           if (Idx == NestIdx)
10231             // Add the chain's type.
10232             NewTypes.push_back(NestTy);
10233
10234           if (I == E)
10235             break;
10236
10237           // Add the original type.
10238           NewTypes.push_back(*I);
10239
10240           ++Idx, ++I;
10241         } while (1);
10242       }
10243
10244       // Replace the trampoline call with a direct call.  Let the generic
10245       // code sort out any function type mismatches.
10246       FunctionType *NewFTy =
10247         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
10248       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10249         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
10250       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10251
10252       Instruction *NewCaller;
10253       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10254         NewCaller = InvokeInst::Create(NewCallee,
10255                                        II->getNormalDest(), II->getUnwindDest(),
10256                                        NewArgs.begin(), NewArgs.end(),
10257                                        Caller->getName(), Caller);
10258         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10259         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10260       } else {
10261         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10262                                      Caller->getName(), Caller);
10263         if (cast<CallInst>(Caller)->isTailCall())
10264           cast<CallInst>(NewCaller)->setTailCall();
10265         cast<CallInst>(NewCaller)->
10266           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10267         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10268       }
10269       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10270         Caller->replaceAllUsesWith(NewCaller);
10271       Caller->eraseFromParent();
10272       RemoveFromWorkList(Caller);
10273       return 0;
10274     }
10275   }
10276
10277   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10278   // parameter, there is no need to adjust the argument list.  Let the generic
10279   // code sort out any function type mismatches.
10280   Constant *NewCallee =
10281     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10282   CS.setCalledFunction(NewCallee);
10283   return CS.getInstruction();
10284 }
10285
10286 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10287 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10288 /// and a single binop.
10289 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10290   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10291   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10292   unsigned Opc = FirstInst->getOpcode();
10293   Value *LHSVal = FirstInst->getOperand(0);
10294   Value *RHSVal = FirstInst->getOperand(1);
10295     
10296   const Type *LHSType = LHSVal->getType();
10297   const Type *RHSType = RHSVal->getType();
10298   
10299   // Scan to see if all operands are the same opcode, all have one use, and all
10300   // kill their operands (i.e. the operands have one use).
10301   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10302     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10303     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10304         // Verify type of the LHS matches so we don't fold cmp's of different
10305         // types or GEP's with different index types.
10306         I->getOperand(0)->getType() != LHSType ||
10307         I->getOperand(1)->getType() != RHSType)
10308       return 0;
10309
10310     // If they are CmpInst instructions, check their predicates
10311     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10312       if (cast<CmpInst>(I)->getPredicate() !=
10313           cast<CmpInst>(FirstInst)->getPredicate())
10314         return 0;
10315     
10316     // Keep track of which operand needs a phi node.
10317     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10318     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10319   }
10320   
10321   // Otherwise, this is safe to transform!
10322   
10323   Value *InLHS = FirstInst->getOperand(0);
10324   Value *InRHS = FirstInst->getOperand(1);
10325   PHINode *NewLHS = 0, *NewRHS = 0;
10326   if (LHSVal == 0) {
10327     NewLHS = PHINode::Create(LHSType,
10328                              FirstInst->getOperand(0)->getName() + ".pn");
10329     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10330     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10331     InsertNewInstBefore(NewLHS, PN);
10332     LHSVal = NewLHS;
10333   }
10334   
10335   if (RHSVal == 0) {
10336     NewRHS = PHINode::Create(RHSType,
10337                              FirstInst->getOperand(1)->getName() + ".pn");
10338     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10339     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10340     InsertNewInstBefore(NewRHS, PN);
10341     RHSVal = NewRHS;
10342   }
10343   
10344   // Add all operands to the new PHIs.
10345   if (NewLHS || NewRHS) {
10346     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10347       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10348       if (NewLHS) {
10349         Value *NewInLHS = InInst->getOperand(0);
10350         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10351       }
10352       if (NewRHS) {
10353         Value *NewInRHS = InInst->getOperand(1);
10354         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10355       }
10356     }
10357   }
10358     
10359   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10360     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10361   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10362   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10363                          RHSVal);
10364 }
10365
10366 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10367   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10368   
10369   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10370                                         FirstInst->op_end());
10371   // This is true if all GEP bases are allocas and if all indices into them are
10372   // constants.
10373   bool AllBasePointersAreAllocas = true;
10374   
10375   // Scan to see if all operands are the same opcode, all have one use, and all
10376   // kill their operands (i.e. the operands have one use).
10377   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10378     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10379     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10380       GEP->getNumOperands() != FirstInst->getNumOperands())
10381       return 0;
10382
10383     // Keep track of whether or not all GEPs are of alloca pointers.
10384     if (AllBasePointersAreAllocas &&
10385         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10386          !GEP->hasAllConstantIndices()))
10387       AllBasePointersAreAllocas = false;
10388     
10389     // Compare the operand lists.
10390     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10391       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10392         continue;
10393       
10394       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10395       // if one of the PHIs has a constant for the index.  The index may be
10396       // substantially cheaper to compute for the constants, so making it a
10397       // variable index could pessimize the path.  This also handles the case
10398       // for struct indices, which must always be constant.
10399       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10400           isa<ConstantInt>(GEP->getOperand(op)))
10401         return 0;
10402       
10403       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10404         return 0;
10405       FixedOperands[op] = 0;  // Needs a PHI.
10406     }
10407   }
10408   
10409   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10410   // bother doing this transformation.  At best, this will just save a bit of
10411   // offset calculation, but all the predecessors will have to materialize the
10412   // stack address into a register anyway.  We'd actually rather *clone* the
10413   // load up into the predecessors so that we have a load of a gep of an alloca,
10414   // which can usually all be folded into the load.
10415   if (AllBasePointersAreAllocas)
10416     return 0;
10417   
10418   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10419   // that is variable.
10420   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10421   
10422   bool HasAnyPHIs = false;
10423   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10424     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10425     Value *FirstOp = FirstInst->getOperand(i);
10426     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10427                                      FirstOp->getName()+".pn");
10428     InsertNewInstBefore(NewPN, PN);
10429     
10430     NewPN->reserveOperandSpace(e);
10431     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10432     OperandPhis[i] = NewPN;
10433     FixedOperands[i] = NewPN;
10434     HasAnyPHIs = true;
10435   }
10436
10437   
10438   // Add all operands to the new PHIs.
10439   if (HasAnyPHIs) {
10440     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10441       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10442       BasicBlock *InBB = PN.getIncomingBlock(i);
10443       
10444       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10445         if (PHINode *OpPhi = OperandPhis[op])
10446           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10447     }
10448   }
10449   
10450   Value *Base = FixedOperands[0];
10451   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10452                                    FixedOperands.end());
10453 }
10454
10455
10456 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10457 /// sink the load out of the block that defines it.  This means that it must be
10458 /// obvious the value of the load is not changed from the point of the load to
10459 /// the end of the block it is in.
10460 ///
10461 /// Finally, it is safe, but not profitable, to sink a load targetting a
10462 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10463 /// to a register.
10464 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10465   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10466   
10467   for (++BBI; BBI != E; ++BBI)
10468     if (BBI->mayWriteToMemory())
10469       return false;
10470   
10471   // Check for non-address taken alloca.  If not address-taken already, it isn't
10472   // profitable to do this xform.
10473   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10474     bool isAddressTaken = false;
10475     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10476          UI != E; ++UI) {
10477       if (isa<LoadInst>(UI)) continue;
10478       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10479         // If storing TO the alloca, then the address isn't taken.
10480         if (SI->getOperand(1) == AI) continue;
10481       }
10482       isAddressTaken = true;
10483       break;
10484     }
10485     
10486     if (!isAddressTaken && AI->isStaticAlloca())
10487       return false;
10488   }
10489   
10490   // If this load is a load from a GEP with a constant offset from an alloca,
10491   // then we don't want to sink it.  In its present form, it will be
10492   // load [constant stack offset].  Sinking it will cause us to have to
10493   // materialize the stack addresses in each predecessor in a register only to
10494   // do a shared load from register in the successor.
10495   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10496     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10497       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10498         return false;
10499   
10500   return true;
10501 }
10502
10503
10504 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10505 // operator and they all are only used by the PHI, PHI together their
10506 // inputs, and do the operation once, to the result of the PHI.
10507 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10508   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10509
10510   // Scan the instruction, looking for input operations that can be folded away.
10511   // If all input operands to the phi are the same instruction (e.g. a cast from
10512   // the same type or "+42") we can pull the operation through the PHI, reducing
10513   // code size and simplifying code.
10514   Constant *ConstantOp = 0;
10515   const Type *CastSrcTy = 0;
10516   bool isVolatile = false;
10517   if (isa<CastInst>(FirstInst)) {
10518     CastSrcTy = FirstInst->getOperand(0)->getType();
10519   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10520     // Can fold binop, compare or shift here if the RHS is a constant, 
10521     // otherwise call FoldPHIArgBinOpIntoPHI.
10522     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10523     if (ConstantOp == 0)
10524       return FoldPHIArgBinOpIntoPHI(PN);
10525   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10526     isVolatile = LI->isVolatile();
10527     // We can't sink the load if the loaded value could be modified between the
10528     // load and the PHI.
10529     if (LI->getParent() != PN.getIncomingBlock(0) ||
10530         !isSafeAndProfitableToSinkLoad(LI))
10531       return 0;
10532     
10533     // If the PHI is of volatile loads and the load block has multiple
10534     // successors, sinking it would remove a load of the volatile value from
10535     // the path through the other successor.
10536     if (isVolatile &&
10537         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10538       return 0;
10539     
10540   } else if (isa<GetElementPtrInst>(FirstInst)) {
10541     return FoldPHIArgGEPIntoPHI(PN);
10542   } else {
10543     return 0;  // Cannot fold this operation.
10544   }
10545
10546   // Check to see if all arguments are the same operation.
10547   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10548     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10549     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10550     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10551       return 0;
10552     if (CastSrcTy) {
10553       if (I->getOperand(0)->getType() != CastSrcTy)
10554         return 0;  // Cast operation must match.
10555     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10556       // We can't sink the load if the loaded value could be modified between 
10557       // the load and the PHI.
10558       if (LI->isVolatile() != isVolatile ||
10559           LI->getParent() != PN.getIncomingBlock(i) ||
10560           !isSafeAndProfitableToSinkLoad(LI))
10561         return 0;
10562       
10563       // If the PHI is of volatile loads and the load block has multiple
10564       // successors, sinking it would remove a load of the volatile value from
10565       // the path through the other successor.
10566       if (isVolatile &&
10567           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10568         return 0;
10569       
10570     } else if (I->getOperand(1) != ConstantOp) {
10571       return 0;
10572     }
10573   }
10574
10575   // Okay, they are all the same operation.  Create a new PHI node of the
10576   // correct type, and PHI together all of the LHS's of the instructions.
10577   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10578                                    PN.getName()+".in");
10579   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10580
10581   Value *InVal = FirstInst->getOperand(0);
10582   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10583
10584   // Add all operands to the new PHI.
10585   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10586     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10587     if (NewInVal != InVal)
10588       InVal = 0;
10589     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10590   }
10591
10592   Value *PhiVal;
10593   if (InVal) {
10594     // The new PHI unions all of the same values together.  This is really
10595     // common, so we handle it intelligently here for compile-time speed.
10596     PhiVal = InVal;
10597     delete NewPN;
10598   } else {
10599     InsertNewInstBefore(NewPN, PN);
10600     PhiVal = NewPN;
10601   }
10602
10603   // Insert and return the new operation.
10604   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10605     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10606   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10607     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10608   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10609     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10610                            PhiVal, ConstantOp);
10611   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10612   
10613   // If this was a volatile load that we are merging, make sure to loop through
10614   // and mark all the input loads as non-volatile.  If we don't do this, we will
10615   // insert a new volatile load and the old ones will not be deletable.
10616   if (isVolatile)
10617     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10618       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10619   
10620   return new LoadInst(PhiVal, "", isVolatile);
10621 }
10622
10623 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10624 /// that is dead.
10625 static bool DeadPHICycle(PHINode *PN,
10626                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10627   if (PN->use_empty()) return true;
10628   if (!PN->hasOneUse()) return false;
10629
10630   // Remember this node, and if we find the cycle, return.
10631   if (!PotentiallyDeadPHIs.insert(PN))
10632     return true;
10633   
10634   // Don't scan crazily complex things.
10635   if (PotentiallyDeadPHIs.size() == 16)
10636     return false;
10637
10638   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10639     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10640
10641   return false;
10642 }
10643
10644 /// PHIsEqualValue - Return true if this phi node is always equal to
10645 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10646 ///   z = some value; x = phi (y, z); y = phi (x, z)
10647 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10648                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10649   // See if we already saw this PHI node.
10650   if (!ValueEqualPHIs.insert(PN))
10651     return true;
10652   
10653   // Don't scan crazily complex things.
10654   if (ValueEqualPHIs.size() == 16)
10655     return false;
10656  
10657   // Scan the operands to see if they are either phi nodes or are equal to
10658   // the value.
10659   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10660     Value *Op = PN->getIncomingValue(i);
10661     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10662       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10663         return false;
10664     } else if (Op != NonPhiInVal)
10665       return false;
10666   }
10667   
10668   return true;
10669 }
10670
10671
10672 // PHINode simplification
10673 //
10674 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10675   // If LCSSA is around, don't mess with Phi nodes
10676   if (MustPreserveLCSSA) return 0;
10677   
10678   if (Value *V = PN.hasConstantValue())
10679     return ReplaceInstUsesWith(PN, V);
10680
10681   // If all PHI operands are the same operation, pull them through the PHI,
10682   // reducing code size.
10683   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10684       isa<Instruction>(PN.getIncomingValue(1)) &&
10685       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10686       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10687       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10688       // than themselves more than once.
10689       PN.getIncomingValue(0)->hasOneUse())
10690     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10691       return Result;
10692
10693   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10694   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10695   // PHI)... break the cycle.
10696   if (PN.hasOneUse()) {
10697     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10698     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10699       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10700       PotentiallyDeadPHIs.insert(&PN);
10701       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10702         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10703     }
10704    
10705     // If this phi has a single use, and if that use just computes a value for
10706     // the next iteration of a loop, delete the phi.  This occurs with unused
10707     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10708     // common case here is good because the only other things that catch this
10709     // are induction variable analysis (sometimes) and ADCE, which is only run
10710     // late.
10711     if (PHIUser->hasOneUse() &&
10712         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10713         PHIUser->use_back() == &PN) {
10714       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10715     }
10716   }
10717
10718   // We sometimes end up with phi cycles that non-obviously end up being the
10719   // same value, for example:
10720   //   z = some value; x = phi (y, z); y = phi (x, z)
10721   // where the phi nodes don't necessarily need to be in the same block.  Do a
10722   // quick check to see if the PHI node only contains a single non-phi value, if
10723   // so, scan to see if the phi cycle is actually equal to that value.
10724   {
10725     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10726     // Scan for the first non-phi operand.
10727     while (InValNo != NumOperandVals && 
10728            isa<PHINode>(PN.getIncomingValue(InValNo)))
10729       ++InValNo;
10730
10731     if (InValNo != NumOperandVals) {
10732       Value *NonPhiInVal = PN.getOperand(InValNo);
10733       
10734       // Scan the rest of the operands to see if there are any conflicts, if so
10735       // there is no need to recursively scan other phis.
10736       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10737         Value *OpVal = PN.getIncomingValue(InValNo);
10738         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10739           break;
10740       }
10741       
10742       // If we scanned over all operands, then we have one unique value plus
10743       // phi values.  Scan PHI nodes to see if they all merge in each other or
10744       // the value.
10745       if (InValNo == NumOperandVals) {
10746         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10747         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10748           return ReplaceInstUsesWith(PN, NonPhiInVal);
10749       }
10750     }
10751   }
10752   return 0;
10753 }
10754
10755 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10756                                    Instruction *InsertPoint,
10757                                    InstCombiner *IC) {
10758   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10759   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10760   // We must cast correctly to the pointer type. Ensure that we
10761   // sign extend the integer value if it is smaller as this is
10762   // used for address computation.
10763   Instruction::CastOps opcode = 
10764      (VTySize < PtrSize ? Instruction::SExt :
10765       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10766   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10767 }
10768
10769
10770 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10771   Value *PtrOp = GEP.getOperand(0);
10772   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10773   // If so, eliminate the noop.
10774   if (GEP.getNumOperands() == 1)
10775     return ReplaceInstUsesWith(GEP, PtrOp);
10776
10777   if (isa<UndefValue>(GEP.getOperand(0)))
10778     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10779
10780   bool HasZeroPointerIndex = false;
10781   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10782     HasZeroPointerIndex = C->isNullValue();
10783
10784   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10785     return ReplaceInstUsesWith(GEP, PtrOp);
10786
10787   // Eliminate unneeded casts for indices.
10788   bool MadeChange = false;
10789   
10790   gep_type_iterator GTI = gep_type_begin(GEP);
10791   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10792        i != e; ++i, ++GTI) {
10793     if (isa<SequentialType>(*GTI)) {
10794       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10795         if (CI->getOpcode() == Instruction::ZExt ||
10796             CI->getOpcode() == Instruction::SExt) {
10797           const Type *SrcTy = CI->getOperand(0)->getType();
10798           // We can eliminate a cast from i32 to i64 iff the target 
10799           // is a 32-bit pointer target.
10800           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10801             MadeChange = true;
10802             *i = CI->getOperand(0);
10803           }
10804         }
10805       }
10806       // If we are using a wider index than needed for this platform, shrink it
10807       // to what we need.  If narrower, sign-extend it to what we need.
10808       // If the incoming value needs a cast instruction,
10809       // insert it.  This explicit cast can make subsequent optimizations more
10810       // obvious.
10811       Value *Op = *i;
10812       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10813         if (Constant *C = dyn_cast<Constant>(Op)) {
10814           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10815           MadeChange = true;
10816         } else {
10817           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10818                                 GEP);
10819           *i = Op;
10820           MadeChange = true;
10821         }
10822       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10823         if (Constant *C = dyn_cast<Constant>(Op)) {
10824           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10825           MadeChange = true;
10826         } else {
10827           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10828                                 GEP);
10829           *i = Op;
10830           MadeChange = true;
10831         }
10832       }
10833     }
10834   }
10835   if (MadeChange) return &GEP;
10836
10837   // Combine Indices - If the source pointer to this getelementptr instruction
10838   // is a getelementptr instruction, combine the indices of the two
10839   // getelementptr instructions into a single instruction.
10840   //
10841   SmallVector<Value*, 8> SrcGEPOperands;
10842   if (User *Src = dyn_castGetElementPtr(PtrOp))
10843     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10844
10845   if (!SrcGEPOperands.empty()) {
10846     // Note that if our source is a gep chain itself that we wait for that
10847     // chain to be resolved before we perform this transformation.  This
10848     // avoids us creating a TON of code in some cases.
10849     //
10850     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10851         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10852       return 0;   // Wait until our source is folded to completion.
10853
10854     SmallVector<Value*, 8> Indices;
10855
10856     // Find out whether the last index in the source GEP is a sequential idx.
10857     bool EndsWithSequential = false;
10858     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10859            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10860       EndsWithSequential = !isa<StructType>(*I);
10861
10862     // Can we combine the two pointer arithmetics offsets?
10863     if (EndsWithSequential) {
10864       // Replace: gep (gep %P, long B), long A, ...
10865       // With:    T = long A+B; gep %P, T, ...
10866       //
10867       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10868       if (SO1 == Constant::getNullValue(SO1->getType())) {
10869         Sum = GO1;
10870       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10871         Sum = SO1;
10872       } else {
10873         // If they aren't the same type, convert both to an integer of the
10874         // target's pointer size.
10875         if (SO1->getType() != GO1->getType()) {
10876           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10877             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10878           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10879             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10880           } else {
10881             unsigned PS = TD->getPointerSizeInBits();
10882             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10883               // Convert GO1 to SO1's type.
10884               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10885
10886             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10887               // Convert SO1 to GO1's type.
10888               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10889             } else {
10890               const Type *PT = TD->getIntPtrType();
10891               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10892               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10893             }
10894           }
10895         }
10896         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10897           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10898         else {
10899           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10900           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10901         }
10902       }
10903
10904       // Recycle the GEP we already have if possible.
10905       if (SrcGEPOperands.size() == 2) {
10906         GEP.setOperand(0, SrcGEPOperands[0]);
10907         GEP.setOperand(1, Sum);
10908         return &GEP;
10909       } else {
10910         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10911                        SrcGEPOperands.end()-1);
10912         Indices.push_back(Sum);
10913         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10914       }
10915     } else if (isa<Constant>(*GEP.idx_begin()) &&
10916                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10917                SrcGEPOperands.size() != 1) {
10918       // Otherwise we can do the fold if the first index of the GEP is a zero
10919       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10920                      SrcGEPOperands.end());
10921       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10922     }
10923
10924     if (!Indices.empty())
10925       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10926                                        Indices.end(), GEP.getName());
10927
10928   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10929     // GEP of global variable.  If all of the indices for this GEP are
10930     // constants, we can promote this to a constexpr instead of an instruction.
10931
10932     // Scan for nonconstants...
10933     SmallVector<Constant*, 8> Indices;
10934     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10935     for (; I != E && isa<Constant>(*I); ++I)
10936       Indices.push_back(cast<Constant>(*I));
10937
10938     if (I == E) {  // If they are all constants...
10939       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10940                                                     &Indices[0],Indices.size());
10941
10942       // Replace all uses of the GEP with the new constexpr...
10943       return ReplaceInstUsesWith(GEP, CE);
10944     }
10945   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10946     if (!isa<PointerType>(X->getType())) {
10947       // Not interesting.  Source pointer must be a cast from pointer.
10948     } else if (HasZeroPointerIndex) {
10949       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10950       // into     : GEP [10 x i8]* X, i32 0, ...
10951       //
10952       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10953       //           into     : GEP i8* X, ...
10954       // 
10955       // This occurs when the program declares an array extern like "int X[];"
10956       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10957       const PointerType *XTy = cast<PointerType>(X->getType());
10958       if (const ArrayType *CATy =
10959           dyn_cast<ArrayType>(CPTy->getElementType())) {
10960         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10961         if (CATy->getElementType() == XTy->getElementType()) {
10962           // -> GEP i8* X, ...
10963           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10964           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10965                                            GEP.getName());
10966         } else if (const ArrayType *XATy =
10967                  dyn_cast<ArrayType>(XTy->getElementType())) {
10968           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
10969           if (CATy->getElementType() == XATy->getElementType()) {
10970             // -> GEP [10 x i8]* X, i32 0, ...
10971             // At this point, we know that the cast source type is a pointer
10972             // to an array of the same type as the destination pointer
10973             // array.  Because the array type is never stepped over (there
10974             // is a leading zero) we can fold the cast into this GEP.
10975             GEP.setOperand(0, X);
10976             return &GEP;
10977           }
10978         }
10979       }
10980     } else if (GEP.getNumOperands() == 2) {
10981       // Transform things like:
10982       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10983       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10984       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10985       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10986       if (isa<ArrayType>(SrcElTy) &&
10987           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10988           TD->getTypeAllocSize(ResElTy)) {
10989         Value *Idx[2];
10990         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10991         Idx[1] = GEP.getOperand(1);
10992         Value *V = InsertNewInstBefore(
10993                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10994         // V and GEP are both pointer types --> BitCast
10995         return new BitCastInst(V, GEP.getType());
10996       }
10997       
10998       // Transform things like:
10999       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11000       //   (where tmp = 8*tmp2) into:
11001       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11002       
11003       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11004         uint64_t ArrayEltSize =
11005             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11006         
11007         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11008         // allow either a mul, shift, or constant here.
11009         Value *NewIdx = 0;
11010         ConstantInt *Scale = 0;
11011         if (ArrayEltSize == 1) {
11012           NewIdx = GEP.getOperand(1);
11013           Scale = ConstantInt::get(NewIdx->getType(), 1);
11014         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11015           NewIdx = ConstantInt::get(CI->getType(), 1);
11016           Scale = CI;
11017         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11018           if (Inst->getOpcode() == Instruction::Shl &&
11019               isa<ConstantInt>(Inst->getOperand(1))) {
11020             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11021             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11022             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
11023             NewIdx = Inst->getOperand(0);
11024           } else if (Inst->getOpcode() == Instruction::Mul &&
11025                      isa<ConstantInt>(Inst->getOperand(1))) {
11026             Scale = cast<ConstantInt>(Inst->getOperand(1));
11027             NewIdx = Inst->getOperand(0);
11028           }
11029         }
11030         
11031         // If the index will be to exactly the right offset with the scale taken
11032         // out, perform the transformation. Note, we don't know whether Scale is
11033         // signed or not. We'll use unsigned version of division/modulo
11034         // operation after making sure Scale doesn't have the sign bit set.
11035         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11036             Scale->getZExtValue() % ArrayEltSize == 0) {
11037           Scale = ConstantInt::get(Scale->getType(),
11038                                    Scale->getZExtValue() / ArrayEltSize);
11039           if (Scale->getZExtValue() != 1) {
11040             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11041                                                        false /*ZExt*/);
11042             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11043             NewIdx = InsertNewInstBefore(Sc, GEP);
11044           }
11045
11046           // Insert the new GEP instruction.
11047           Value *Idx[2];
11048           Idx[0] = Constant::getNullValue(Type::Int32Ty);
11049           Idx[1] = NewIdx;
11050           Instruction *NewGEP =
11051             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11052           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11053           // The NewGEP must be pointer typed, so must the old one -> BitCast
11054           return new BitCastInst(NewGEP, GEP.getType());
11055         }
11056       }
11057     }
11058   }
11059   
11060   /// See if we can simplify:
11061   ///   X = bitcast A to B*
11062   ///   Y = gep X, <...constant indices...>
11063   /// into a gep of the original struct.  This is important for SROA and alias
11064   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11065   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11066     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11067       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11068       // a constant back from EmitGEPOffset.
11069       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11070       int64_t Offset = OffsetV->getSExtValue();
11071       
11072       // If this GEP instruction doesn't move the pointer, just replace the GEP
11073       // with a bitcast of the real input to the dest type.
11074       if (Offset == 0) {
11075         // If the bitcast is of an allocation, and the allocation will be
11076         // converted to match the type of the cast, don't touch this.
11077         if (isa<AllocationInst>(BCI->getOperand(0))) {
11078           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11079           if (Instruction *I = visitBitCast(*BCI)) {
11080             if (I != BCI) {
11081               I->takeName(BCI);
11082               BCI->getParent()->getInstList().insert(BCI, I);
11083               ReplaceInstUsesWith(*BCI, I);
11084             }
11085             return &GEP;
11086           }
11087         }
11088         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11089       }
11090       
11091       // Otherwise, if the offset is non-zero, we need to find out if there is a
11092       // field at Offset in 'A's type.  If so, we can pull the cast through the
11093       // GEP.
11094       SmallVector<Value*, 8> NewIndices;
11095       const Type *InTy =
11096         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11097       if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
11098         Instruction *NGEP =
11099            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11100                                      NewIndices.end());
11101         if (NGEP->getType() == GEP.getType()) return NGEP;
11102         InsertNewInstBefore(NGEP, GEP);
11103         NGEP->takeName(&GEP);
11104         return new BitCastInst(NGEP, GEP.getType());
11105       }
11106     }
11107   }    
11108     
11109   return 0;
11110 }
11111
11112 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11113   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11114   if (AI.isArrayAllocation()) {  // Check C != 1
11115     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11116       const Type *NewTy = 
11117         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11118       AllocationInst *New = 0;
11119
11120       // Create and insert the replacement instruction...
11121       if (isa<MallocInst>(AI))
11122         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11123       else {
11124         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11125         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11126       }
11127
11128       InsertNewInstBefore(New, AI);
11129
11130       // Scan to the end of the allocation instructions, to skip over a block of
11131       // allocas if possible...also skip interleaved debug info
11132       //
11133       BasicBlock::iterator It = New;
11134       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11135
11136       // Now that I is pointing to the first non-allocation-inst in the block,
11137       // insert our getelementptr instruction...
11138       //
11139       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
11140       Value *Idx[2];
11141       Idx[0] = NullIdx;
11142       Idx[1] = NullIdx;
11143       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11144                                            New->getName()+".sub", It);
11145
11146       // Now make everything use the getelementptr instead of the original
11147       // allocation.
11148       return ReplaceInstUsesWith(AI, V);
11149     } else if (isa<UndefValue>(AI.getArraySize())) {
11150       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11151     }
11152   }
11153
11154   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11155     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11156     // Note that we only do this for alloca's, because malloc should allocate
11157     // and return a unique pointer, even for a zero byte allocation.
11158     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11159       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11160
11161     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11162     if (AI.getAlignment() == 0)
11163       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11164   }
11165
11166   return 0;
11167 }
11168
11169 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11170   Value *Op = FI.getOperand(0);
11171
11172   // free undef -> unreachable.
11173   if (isa<UndefValue>(Op)) {
11174     // Insert a new store to null because we cannot modify the CFG here.
11175     new StoreInst(ConstantInt::getTrue(),
11176                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
11177     return EraseInstFromFunction(FI);
11178   }
11179   
11180   // If we have 'free null' delete the instruction.  This can happen in stl code
11181   // when lots of inlining happens.
11182   if (isa<ConstantPointerNull>(Op))
11183     return EraseInstFromFunction(FI);
11184   
11185   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11186   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11187     FI.setOperand(0, CI->getOperand(0));
11188     return &FI;
11189   }
11190   
11191   // Change free (gep X, 0,0,0,0) into free(X)
11192   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11193     if (GEPI->hasAllZeroIndices()) {
11194       AddToWorkList(GEPI);
11195       FI.setOperand(0, GEPI->getOperand(0));
11196       return &FI;
11197     }
11198   }
11199   
11200   // Change free(malloc) into nothing, if the malloc has a single use.
11201   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11202     if (MI->hasOneUse()) {
11203       EraseInstFromFunction(FI);
11204       return EraseInstFromFunction(*MI);
11205     }
11206
11207   return 0;
11208 }
11209
11210
11211 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11212 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11213                                         const TargetData *TD) {
11214   User *CI = cast<User>(LI.getOperand(0));
11215   Value *CastOp = CI->getOperand(0);
11216
11217   if (TD) {
11218     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11219       // Instead of loading constant c string, use corresponding integer value
11220       // directly if string length is small enough.
11221       std::string Str;
11222       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11223         unsigned len = Str.length();
11224         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11225         unsigned numBits = Ty->getPrimitiveSizeInBits();
11226         // Replace LI with immediate integer store.
11227         if ((numBits >> 3) == len + 1) {
11228           APInt StrVal(numBits, 0);
11229           APInt SingleChar(numBits, 0);
11230           if (TD->isLittleEndian()) {
11231             for (signed i = len-1; i >= 0; i--) {
11232               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11233               StrVal = (StrVal << 8) | SingleChar;
11234             }
11235           } else {
11236             for (unsigned i = 0; i < len; i++) {
11237               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11238               StrVal = (StrVal << 8) | SingleChar;
11239             }
11240             // Append NULL at the end.
11241             SingleChar = 0;
11242             StrVal = (StrVal << 8) | SingleChar;
11243           }
11244           Value *NL = ConstantInt::get(StrVal);
11245           return IC.ReplaceInstUsesWith(LI, NL);
11246         }
11247       }
11248     }
11249   }
11250
11251   const PointerType *DestTy = cast<PointerType>(CI->getType());
11252   const Type *DestPTy = DestTy->getElementType();
11253   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11254
11255     // If the address spaces don't match, don't eliminate the cast.
11256     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11257       return 0;
11258
11259     const Type *SrcPTy = SrcTy->getElementType();
11260
11261     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11262          isa<VectorType>(DestPTy)) {
11263       // If the source is an array, the code below will not succeed.  Check to
11264       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11265       // constants.
11266       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11267         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11268           if (ASrcTy->getNumElements() != 0) {
11269             Value *Idxs[2];
11270             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11271             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11272             SrcTy = cast<PointerType>(CastOp->getType());
11273             SrcPTy = SrcTy->getElementType();
11274           }
11275
11276       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11277             isa<VectorType>(SrcPTy)) &&
11278           // Do not allow turning this into a load of an integer, which is then
11279           // casted to a pointer, this pessimizes pointer analysis a lot.
11280           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11281           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11282                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11283
11284         // Okay, we are casting from one integer or pointer type to another of
11285         // the same size.  Instead of casting the pointer before the load, cast
11286         // the result of the loaded value.
11287         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11288                                                              CI->getName(),
11289                                                          LI.isVolatile()),LI);
11290         // Now cast the result of the load.
11291         return new BitCastInst(NewLoad, LI.getType());
11292       }
11293     }
11294   }
11295   return 0;
11296 }
11297
11298 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
11299 /// from this value cannot trap.  If it is not obviously safe to load from the
11300 /// specified pointer, we do a quick local scan of the basic block containing
11301 /// ScanFrom, to determine if the address is already accessed.
11302 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
11303   // If it is an alloca it is always safe to load from.
11304   if (isa<AllocaInst>(V)) return true;
11305
11306   // If it is a global variable it is mostly safe to load from.
11307   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
11308     // Don't try to evaluate aliases.  External weak GV can be null.
11309     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
11310
11311   // Otherwise, be a little bit agressive by scanning the local block where we
11312   // want to check to see if the pointer is already being loaded or stored
11313   // from/to.  If so, the previous load or store would have already trapped,
11314   // so there is no harm doing an extra load (also, CSE will later eliminate
11315   // the load entirely).
11316   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11317
11318   while (BBI != E) {
11319     --BBI;
11320
11321     // If we see a free or a call (which might do a free) the pointer could be
11322     // marked invalid.
11323     if (isa<FreeInst>(BBI) || 
11324         (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)))
11325       return false;
11326     
11327     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11328       if (LI->getOperand(0) == V) return true;
11329     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
11330       if (SI->getOperand(1) == V) return true;
11331     }
11332
11333   }
11334   return false;
11335 }
11336
11337 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11338   Value *Op = LI.getOperand(0);
11339
11340   // Attempt to improve the alignment.
11341   unsigned KnownAlign =
11342     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11343   if (KnownAlign >
11344       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11345                                 LI.getAlignment()))
11346     LI.setAlignment(KnownAlign);
11347
11348   // load (cast X) --> cast (load X) iff safe
11349   if (isa<CastInst>(Op))
11350     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11351       return Res;
11352
11353   // None of the following transforms are legal for volatile loads.
11354   if (LI.isVolatile()) return 0;
11355   
11356   // Do really simple store-to-load forwarding and load CSE, to catch cases
11357   // where there are several consequtive memory accesses to the same location,
11358   // separated by a few arithmetic operations.
11359   BasicBlock::iterator BBI = &LI;
11360   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11361     return ReplaceInstUsesWith(LI, AvailableVal);
11362
11363   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11364     const Value *GEPI0 = GEPI->getOperand(0);
11365     // TODO: Consider a target hook for valid address spaces for this xform.
11366     if (isa<ConstantPointerNull>(GEPI0) &&
11367         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11368       // Insert a new store to null instruction before the load to indicate
11369       // that this code is not reachable.  We do this instead of inserting
11370       // an unreachable instruction directly because we cannot modify the
11371       // CFG.
11372       new StoreInst(UndefValue::get(LI.getType()),
11373                     Constant::getNullValue(Op->getType()), &LI);
11374       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11375     }
11376   } 
11377
11378   if (Constant *C = dyn_cast<Constant>(Op)) {
11379     // load null/undef -> undef
11380     // TODO: Consider a target hook for valid address spaces for this xform.
11381     if (isa<UndefValue>(C) || (C->isNullValue() && 
11382         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11383       // Insert a new store to null instruction before the load to indicate that
11384       // this code is not reachable.  We do this instead of inserting an
11385       // unreachable instruction directly because we cannot modify the CFG.
11386       new StoreInst(UndefValue::get(LI.getType()),
11387                     Constant::getNullValue(Op->getType()), &LI);
11388       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11389     }
11390
11391     // Instcombine load (constant global) into the value loaded.
11392     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11393       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11394         return ReplaceInstUsesWith(LI, GV->getInitializer());
11395
11396     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11397     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11398       if (CE->getOpcode() == Instruction::GetElementPtr) {
11399         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11400           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11401             if (Constant *V = 
11402                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11403               return ReplaceInstUsesWith(LI, V);
11404         if (CE->getOperand(0)->isNullValue()) {
11405           // Insert a new store to null instruction before the load to indicate
11406           // that this code is not reachable.  We do this instead of inserting
11407           // an unreachable instruction directly because we cannot modify the
11408           // CFG.
11409           new StoreInst(UndefValue::get(LI.getType()),
11410                         Constant::getNullValue(Op->getType()), &LI);
11411           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11412         }
11413
11414       } else if (CE->isCast()) {
11415         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11416           return Res;
11417       }
11418     }
11419   }
11420     
11421   // If this load comes from anywhere in a constant global, and if the global
11422   // is all undef or zero, we know what it loads.
11423   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11424     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11425       if (GV->getInitializer()->isNullValue())
11426         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11427       else if (isa<UndefValue>(GV->getInitializer()))
11428         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11429     }
11430   }
11431
11432   if (Op->hasOneUse()) {
11433     // Change select and PHI nodes to select values instead of addresses: this
11434     // helps alias analysis out a lot, allows many others simplifications, and
11435     // exposes redundancy in the code.
11436     //
11437     // Note that we cannot do the transformation unless we know that the
11438     // introduced loads cannot trap!  Something like this is valid as long as
11439     // the condition is always false: load (select bool %C, int* null, int* %G),
11440     // but it would not be valid if we transformed it to load from null
11441     // unconditionally.
11442     //
11443     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11444       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11445       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11446           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11447         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11448                                      SI->getOperand(1)->getName()+".val"), LI);
11449         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11450                                      SI->getOperand(2)->getName()+".val"), LI);
11451         return SelectInst::Create(SI->getCondition(), V1, V2);
11452       }
11453
11454       // load (select (cond, null, P)) -> load P
11455       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11456         if (C->isNullValue()) {
11457           LI.setOperand(0, SI->getOperand(2));
11458           return &LI;
11459         }
11460
11461       // load (select (cond, P, null)) -> load P
11462       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11463         if (C->isNullValue()) {
11464           LI.setOperand(0, SI->getOperand(1));
11465           return &LI;
11466         }
11467     }
11468   }
11469   return 0;
11470 }
11471
11472 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11473 /// when possible.  This makes it generally easy to do alias analysis and/or
11474 /// SROA/mem2reg of the memory object.
11475 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11476   User *CI = cast<User>(SI.getOperand(1));
11477   Value *CastOp = CI->getOperand(0);
11478
11479   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11480   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11481   if (SrcTy == 0) return 0;
11482   
11483   const Type *SrcPTy = SrcTy->getElementType();
11484
11485   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11486     return 0;
11487   
11488   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11489   /// to its first element.  This allows us to handle things like:
11490   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11491   /// on 32-bit hosts.
11492   SmallVector<Value*, 4> NewGEPIndices;
11493   
11494   // If the source is an array, the code below will not succeed.  Check to
11495   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11496   // constants.
11497   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11498     // Index through pointer.
11499     Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11500     NewGEPIndices.push_back(Zero);
11501     
11502     while (1) {
11503       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11504         if (!STy->getNumElements()) /* Struct can be empty {} */
11505           break;
11506         NewGEPIndices.push_back(Zero);
11507         SrcPTy = STy->getElementType(0);
11508       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11509         NewGEPIndices.push_back(Zero);
11510         SrcPTy = ATy->getElementType();
11511       } else {
11512         break;
11513       }
11514     }
11515     
11516     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11517   }
11518
11519   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11520     return 0;
11521   
11522   // If the pointers point into different address spaces or if they point to
11523   // values with different sizes, we can't do the transformation.
11524   if (SrcTy->getAddressSpace() != 
11525         cast<PointerType>(CI->getType())->getAddressSpace() ||
11526       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11527       IC.getTargetData().getTypeSizeInBits(DestPTy))
11528     return 0;
11529
11530   // Okay, we are casting from one integer or pointer type to another of
11531   // the same size.  Instead of casting the pointer before 
11532   // the store, cast the value to be stored.
11533   Value *NewCast;
11534   Value *SIOp0 = SI.getOperand(0);
11535   Instruction::CastOps opcode = Instruction::BitCast;
11536   const Type* CastSrcTy = SIOp0->getType();
11537   const Type* CastDstTy = SrcPTy;
11538   if (isa<PointerType>(CastDstTy)) {
11539     if (CastSrcTy->isInteger())
11540       opcode = Instruction::IntToPtr;
11541   } else if (isa<IntegerType>(CastDstTy)) {
11542     if (isa<PointerType>(SIOp0->getType()))
11543       opcode = Instruction::PtrToInt;
11544   }
11545   
11546   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11547   // emit a GEP to index into its first field.
11548   if (!NewGEPIndices.empty()) {
11549     if (Constant *C = dyn_cast<Constant>(CastOp))
11550       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11551                                               NewGEPIndices.size());
11552     else
11553       CastOp = IC.InsertNewInstBefore(
11554               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11555                                         NewGEPIndices.end()), SI);
11556   }
11557   
11558   if (Constant *C = dyn_cast<Constant>(SIOp0))
11559     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11560   else
11561     NewCast = IC.InsertNewInstBefore(
11562       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11563       SI);
11564   return new StoreInst(NewCast, CastOp);
11565 }
11566
11567 /// equivalentAddressValues - Test if A and B will obviously have the same
11568 /// value. This includes recognizing that %t0 and %t1 will have the same
11569 /// value in code like this:
11570 ///   %t0 = getelementptr \@a, 0, 3
11571 ///   store i32 0, i32* %t0
11572 ///   %t1 = getelementptr \@a, 0, 3
11573 ///   %t2 = load i32* %t1
11574 ///
11575 static bool equivalentAddressValues(Value *A, Value *B) {
11576   // Test if the values are trivially equivalent.
11577   if (A == B) return true;
11578   
11579   // Test if the values come form identical arithmetic instructions.
11580   if (isa<BinaryOperator>(A) ||
11581       isa<CastInst>(A) ||
11582       isa<PHINode>(A) ||
11583       isa<GetElementPtrInst>(A))
11584     if (Instruction *BI = dyn_cast<Instruction>(B))
11585       if (cast<Instruction>(A)->isIdenticalTo(BI))
11586         return true;
11587   
11588   // Otherwise they may not be equivalent.
11589   return false;
11590 }
11591
11592 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11593 // return the llvm.dbg.declare.
11594 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11595   if (!V->hasNUses(2))
11596     return 0;
11597   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11598        UI != E; ++UI) {
11599     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11600       return DI;
11601     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11602       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11603         return DI;
11604       }
11605   }
11606   return 0;
11607 }
11608
11609 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11610   Value *Val = SI.getOperand(0);
11611   Value *Ptr = SI.getOperand(1);
11612
11613   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11614     EraseInstFromFunction(SI);
11615     ++NumCombined;
11616     return 0;
11617   }
11618   
11619   // If the RHS is an alloca with a single use, zapify the store, making the
11620   // alloca dead.
11621   // If the RHS is an alloca with a two uses, the other one being a 
11622   // llvm.dbg.declare, zapify the store and the declare, making the
11623   // alloca dead.  We must do this to prevent declare's from affecting
11624   // codegen.
11625   if (!SI.isVolatile()) {
11626     if (Ptr->hasOneUse()) {
11627       if (isa<AllocaInst>(Ptr)) {
11628         EraseInstFromFunction(SI);
11629         ++NumCombined;
11630         return 0;
11631       }
11632       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11633         if (isa<AllocaInst>(GEP->getOperand(0))) {
11634           if (GEP->getOperand(0)->hasOneUse()) {
11635             EraseInstFromFunction(SI);
11636             ++NumCombined;
11637             return 0;
11638           }
11639           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11640             EraseInstFromFunction(*DI);
11641             EraseInstFromFunction(SI);
11642             ++NumCombined;
11643             return 0;
11644           }
11645         }
11646       }
11647     }
11648     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11649       EraseInstFromFunction(*DI);
11650       EraseInstFromFunction(SI);
11651       ++NumCombined;
11652       return 0;
11653     }
11654   }
11655
11656   // Attempt to improve the alignment.
11657   unsigned KnownAlign =
11658     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11659   if (KnownAlign >
11660       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11661                                 SI.getAlignment()))
11662     SI.setAlignment(KnownAlign);
11663
11664   // Do really simple DSE, to catch cases where there are several consecutive
11665   // stores to the same location, separated by a few arithmetic operations. This
11666   // situation often occurs with bitfield accesses.
11667   BasicBlock::iterator BBI = &SI;
11668   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11669        --ScanInsts) {
11670     --BBI;
11671     // Don't count debug info directives, lest they affect codegen,
11672     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11673     // It is necessary for correctness to skip those that feed into a
11674     // llvm.dbg.declare, as these are not present when debugging is off.
11675     if (isa<DbgInfoIntrinsic>(BBI) ||
11676         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11677       ScanInsts++;
11678       continue;
11679     }    
11680     
11681     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11682       // Prev store isn't volatile, and stores to the same location?
11683       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11684                                                           SI.getOperand(1))) {
11685         ++NumDeadStore;
11686         ++BBI;
11687         EraseInstFromFunction(*PrevSI);
11688         continue;
11689       }
11690       break;
11691     }
11692     
11693     // If this is a load, we have to stop.  However, if the loaded value is from
11694     // the pointer we're loading and is producing the pointer we're storing,
11695     // then *this* store is dead (X = load P; store X -> P).
11696     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11697       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11698           !SI.isVolatile()) {
11699         EraseInstFromFunction(SI);
11700         ++NumCombined;
11701         return 0;
11702       }
11703       // Otherwise, this is a load from some other location.  Stores before it
11704       // may not be dead.
11705       break;
11706     }
11707     
11708     // Don't skip over loads or things that can modify memory.
11709     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11710       break;
11711   }
11712   
11713   
11714   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11715
11716   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11717   if (isa<ConstantPointerNull>(Ptr)) {
11718     if (!isa<UndefValue>(Val)) {
11719       SI.setOperand(0, UndefValue::get(Val->getType()));
11720       if (Instruction *U = dyn_cast<Instruction>(Val))
11721         AddToWorkList(U);  // Dropped a use.
11722       ++NumCombined;
11723     }
11724     return 0;  // Do not modify these!
11725   }
11726
11727   // store undef, Ptr -> noop
11728   if (isa<UndefValue>(Val)) {
11729     EraseInstFromFunction(SI);
11730     ++NumCombined;
11731     return 0;
11732   }
11733
11734   // If the pointer destination is a cast, see if we can fold the cast into the
11735   // source instead.
11736   if (isa<CastInst>(Ptr))
11737     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11738       return Res;
11739   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11740     if (CE->isCast())
11741       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11742         return Res;
11743
11744   
11745   // If this store is the last instruction in the basic block (possibly
11746   // excepting debug info instructions and the pointer bitcasts that feed
11747   // into them), and if the block ends with an unconditional branch, try
11748   // to move it to the successor block.
11749   BBI = &SI; 
11750   do {
11751     ++BBI;
11752   } while (isa<DbgInfoIntrinsic>(BBI) ||
11753            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11754   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11755     if (BI->isUnconditional())
11756       if (SimplifyStoreAtEndOfBlock(SI))
11757         return 0;  // xform done!
11758   
11759   return 0;
11760 }
11761
11762 /// SimplifyStoreAtEndOfBlock - Turn things like:
11763 ///   if () { *P = v1; } else { *P = v2 }
11764 /// into a phi node with a store in the successor.
11765 ///
11766 /// Simplify things like:
11767 ///   *P = v1; if () { *P = v2; }
11768 /// into a phi node with a store in the successor.
11769 ///
11770 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11771   BasicBlock *StoreBB = SI.getParent();
11772   
11773   // Check to see if the successor block has exactly two incoming edges.  If
11774   // so, see if the other predecessor contains a store to the same location.
11775   // if so, insert a PHI node (if needed) and move the stores down.
11776   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11777   
11778   // Determine whether Dest has exactly two predecessors and, if so, compute
11779   // the other predecessor.
11780   pred_iterator PI = pred_begin(DestBB);
11781   BasicBlock *OtherBB = 0;
11782   if (*PI != StoreBB)
11783     OtherBB = *PI;
11784   ++PI;
11785   if (PI == pred_end(DestBB))
11786     return false;
11787   
11788   if (*PI != StoreBB) {
11789     if (OtherBB)
11790       return false;
11791     OtherBB = *PI;
11792   }
11793   if (++PI != pred_end(DestBB))
11794     return false;
11795
11796   // Bail out if all the relevant blocks aren't distinct (this can happen,
11797   // for example, if SI is in an infinite loop)
11798   if (StoreBB == DestBB || OtherBB == DestBB)
11799     return false;
11800
11801   // Verify that the other block ends in a branch and is not otherwise empty.
11802   BasicBlock::iterator BBI = OtherBB->getTerminator();
11803   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11804   if (!OtherBr || BBI == OtherBB->begin())
11805     return false;
11806   
11807   // If the other block ends in an unconditional branch, check for the 'if then
11808   // else' case.  there is an instruction before the branch.
11809   StoreInst *OtherStore = 0;
11810   if (OtherBr->isUnconditional()) {
11811     --BBI;
11812     // Skip over debugging info.
11813     while (isa<DbgInfoIntrinsic>(BBI) ||
11814            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11815       if (BBI==OtherBB->begin())
11816         return false;
11817       --BBI;
11818     }
11819     // If this isn't a store, or isn't a store to the same location, bail out.
11820     OtherStore = dyn_cast<StoreInst>(BBI);
11821     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11822       return false;
11823   } else {
11824     // Otherwise, the other block ended with a conditional branch. If one of the
11825     // destinations is StoreBB, then we have the if/then case.
11826     if (OtherBr->getSuccessor(0) != StoreBB && 
11827         OtherBr->getSuccessor(1) != StoreBB)
11828       return false;
11829     
11830     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11831     // if/then triangle.  See if there is a store to the same ptr as SI that
11832     // lives in OtherBB.
11833     for (;; --BBI) {
11834       // Check to see if we find the matching store.
11835       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11836         if (OtherStore->getOperand(1) != SI.getOperand(1))
11837           return false;
11838         break;
11839       }
11840       // If we find something that may be using or overwriting the stored
11841       // value, or if we run out of instructions, we can't do the xform.
11842       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11843           BBI == OtherBB->begin())
11844         return false;
11845     }
11846     
11847     // In order to eliminate the store in OtherBr, we have to
11848     // make sure nothing reads or overwrites the stored value in
11849     // StoreBB.
11850     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11851       // FIXME: This should really be AA driven.
11852       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11853         return false;
11854     }
11855   }
11856   
11857   // Insert a PHI node now if we need it.
11858   Value *MergedVal = OtherStore->getOperand(0);
11859   if (MergedVal != SI.getOperand(0)) {
11860     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11861     PN->reserveOperandSpace(2);
11862     PN->addIncoming(SI.getOperand(0), SI.getParent());
11863     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11864     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11865   }
11866   
11867   // Advance to a place where it is safe to insert the new store and
11868   // insert it.
11869   BBI = DestBB->getFirstNonPHI();
11870   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11871                                     OtherStore->isVolatile()), *BBI);
11872   
11873   // Nuke the old stores.
11874   EraseInstFromFunction(SI);
11875   EraseInstFromFunction(*OtherStore);
11876   ++NumCombined;
11877   return true;
11878 }
11879
11880
11881 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11882   // Change br (not X), label True, label False to: br X, label False, True
11883   Value *X = 0;
11884   BasicBlock *TrueDest;
11885   BasicBlock *FalseDest;
11886   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11887       !isa<Constant>(X)) {
11888     // Swap Destinations and condition...
11889     BI.setCondition(X);
11890     BI.setSuccessor(0, FalseDest);
11891     BI.setSuccessor(1, TrueDest);
11892     return &BI;
11893   }
11894
11895   // Cannonicalize fcmp_one -> fcmp_oeq
11896   FCmpInst::Predicate FPred; Value *Y;
11897   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11898                              TrueDest, FalseDest)))
11899     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11900          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11901       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11902       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11903       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11904       NewSCC->takeName(I);
11905       // Swap Destinations and condition...
11906       BI.setCondition(NewSCC);
11907       BI.setSuccessor(0, FalseDest);
11908       BI.setSuccessor(1, TrueDest);
11909       RemoveFromWorkList(I);
11910       I->eraseFromParent();
11911       AddToWorkList(NewSCC);
11912       return &BI;
11913     }
11914
11915   // Cannonicalize icmp_ne -> icmp_eq
11916   ICmpInst::Predicate IPred;
11917   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11918                       TrueDest, FalseDest)))
11919     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11920          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11921          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11922       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11923       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11924       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11925       NewSCC->takeName(I);
11926       // Swap Destinations and condition...
11927       BI.setCondition(NewSCC);
11928       BI.setSuccessor(0, FalseDest);
11929       BI.setSuccessor(1, TrueDest);
11930       RemoveFromWorkList(I);
11931       I->eraseFromParent();;
11932       AddToWorkList(NewSCC);
11933       return &BI;
11934     }
11935
11936   return 0;
11937 }
11938
11939 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11940   Value *Cond = SI.getCondition();
11941   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11942     if (I->getOpcode() == Instruction::Add)
11943       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11944         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11945         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11946           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11947                                                 AddRHS));
11948         SI.setOperand(0, I->getOperand(0));
11949         AddToWorkList(I);
11950         return &SI;
11951       }
11952   }
11953   return 0;
11954 }
11955
11956 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11957   Value *Agg = EV.getAggregateOperand();
11958
11959   if (!EV.hasIndices())
11960     return ReplaceInstUsesWith(EV, Agg);
11961
11962   if (Constant *C = dyn_cast<Constant>(Agg)) {
11963     if (isa<UndefValue>(C))
11964       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11965       
11966     if (isa<ConstantAggregateZero>(C))
11967       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11968
11969     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11970       // Extract the element indexed by the first index out of the constant
11971       Value *V = C->getOperand(*EV.idx_begin());
11972       if (EV.getNumIndices() > 1)
11973         // Extract the remaining indices out of the constant indexed by the
11974         // first index
11975         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11976       else
11977         return ReplaceInstUsesWith(EV, V);
11978     }
11979     return 0; // Can't handle other constants
11980   } 
11981   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11982     // We're extracting from an insertvalue instruction, compare the indices
11983     const unsigned *exti, *exte, *insi, *inse;
11984     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11985          exte = EV.idx_end(), inse = IV->idx_end();
11986          exti != exte && insi != inse;
11987          ++exti, ++insi) {
11988       if (*insi != *exti)
11989         // The insert and extract both reference distinctly different elements.
11990         // This means the extract is not influenced by the insert, and we can
11991         // replace the aggregate operand of the extract with the aggregate
11992         // operand of the insert. i.e., replace
11993         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11994         // %E = extractvalue { i32, { i32 } } %I, 0
11995         // with
11996         // %E = extractvalue { i32, { i32 } } %A, 0
11997         return ExtractValueInst::Create(IV->getAggregateOperand(),
11998                                         EV.idx_begin(), EV.idx_end());
11999     }
12000     if (exti == exte && insi == inse)
12001       // Both iterators are at the end: Index lists are identical. Replace
12002       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12003       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12004       // with "i32 42"
12005       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12006     if (exti == exte) {
12007       // The extract list is a prefix of the insert list. i.e. replace
12008       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12009       // %E = extractvalue { i32, { i32 } } %I, 1
12010       // with
12011       // %X = extractvalue { i32, { i32 } } %A, 1
12012       // %E = insertvalue { i32 } %X, i32 42, 0
12013       // by switching the order of the insert and extract (though the
12014       // insertvalue should be left in, since it may have other uses).
12015       Value *NewEV = InsertNewInstBefore(
12016         ExtractValueInst::Create(IV->getAggregateOperand(),
12017                                  EV.idx_begin(), EV.idx_end()),
12018         EV);
12019       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12020                                      insi, inse);
12021     }
12022     if (insi == inse)
12023       // The insert list is a prefix of the extract list
12024       // We can simply remove the common indices from the extract and make it
12025       // operate on the inserted value instead of the insertvalue result.
12026       // i.e., replace
12027       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12028       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12029       // with
12030       // %E extractvalue { i32 } { i32 42 }, 0
12031       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12032                                       exti, exte);
12033   }
12034   // Can't simplify extracts from other values. Note that nested extracts are
12035   // already simplified implicitely by the above (extract ( extract (insert) )
12036   // will be translated into extract ( insert ( extract ) ) first and then just
12037   // the value inserted, if appropriate).
12038   return 0;
12039 }
12040
12041 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12042 /// is to leave as a vector operation.
12043 static bool CheapToScalarize(Value *V, bool isConstant) {
12044   if (isa<ConstantAggregateZero>(V)) 
12045     return true;
12046   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12047     if (isConstant) return true;
12048     // If all elts are the same, we can extract.
12049     Constant *Op0 = C->getOperand(0);
12050     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12051       if (C->getOperand(i) != Op0)
12052         return false;
12053     return true;
12054   }
12055   Instruction *I = dyn_cast<Instruction>(V);
12056   if (!I) return false;
12057   
12058   // Insert element gets simplified to the inserted element or is deleted if
12059   // this is constant idx extract element and its a constant idx insertelt.
12060   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12061       isa<ConstantInt>(I->getOperand(2)))
12062     return true;
12063   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12064     return true;
12065   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12066     if (BO->hasOneUse() &&
12067         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12068          CheapToScalarize(BO->getOperand(1), isConstant)))
12069       return true;
12070   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12071     if (CI->hasOneUse() &&
12072         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12073          CheapToScalarize(CI->getOperand(1), isConstant)))
12074       return true;
12075   
12076   return false;
12077 }
12078
12079 /// Read and decode a shufflevector mask.
12080 ///
12081 /// It turns undef elements into values that are larger than the number of
12082 /// elements in the input.
12083 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12084   unsigned NElts = SVI->getType()->getNumElements();
12085   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12086     return std::vector<unsigned>(NElts, 0);
12087   if (isa<UndefValue>(SVI->getOperand(2)))
12088     return std::vector<unsigned>(NElts, 2*NElts);
12089
12090   std::vector<unsigned> Result;
12091   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12092   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12093     if (isa<UndefValue>(*i))
12094       Result.push_back(NElts*2);  // undef -> 8
12095     else
12096       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12097   return Result;
12098 }
12099
12100 /// FindScalarElement - Given a vector and an element number, see if the scalar
12101 /// value is already around as a register, for example if it were inserted then
12102 /// extracted from the vector.
12103 static Value *FindScalarElement(Value *V, unsigned EltNo) {
12104   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12105   const VectorType *PTy = cast<VectorType>(V->getType());
12106   unsigned Width = PTy->getNumElements();
12107   if (EltNo >= Width)  // Out of range access.
12108     return UndefValue::get(PTy->getElementType());
12109   
12110   if (isa<UndefValue>(V))
12111     return UndefValue::get(PTy->getElementType());
12112   else if (isa<ConstantAggregateZero>(V))
12113     return Constant::getNullValue(PTy->getElementType());
12114   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12115     return CP->getOperand(EltNo);
12116   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12117     // If this is an insert to a variable element, we don't know what it is.
12118     if (!isa<ConstantInt>(III->getOperand(2))) 
12119       return 0;
12120     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12121     
12122     // If this is an insert to the element we are looking for, return the
12123     // inserted value.
12124     if (EltNo == IIElt) 
12125       return III->getOperand(1);
12126     
12127     // Otherwise, the insertelement doesn't modify the value, recurse on its
12128     // vector input.
12129     return FindScalarElement(III->getOperand(0), EltNo);
12130   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12131     unsigned LHSWidth =
12132       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12133     unsigned InEl = getShuffleMask(SVI)[EltNo];
12134     if (InEl < LHSWidth)
12135       return FindScalarElement(SVI->getOperand(0), InEl);
12136     else if (InEl < LHSWidth*2)
12137       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
12138     else
12139       return UndefValue::get(PTy->getElementType());
12140   }
12141   
12142   // Otherwise, we don't know.
12143   return 0;
12144 }
12145
12146 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12147   // If vector val is undef, replace extract with scalar undef.
12148   if (isa<UndefValue>(EI.getOperand(0)))
12149     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12150
12151   // If vector val is constant 0, replace extract with scalar 0.
12152   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12153     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12154   
12155   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12156     // If vector val is constant with all elements the same, replace EI with
12157     // that element. When the elements are not identical, we cannot replace yet
12158     // (we do that below, but only when the index is constant).
12159     Constant *op0 = C->getOperand(0);
12160     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12161       if (C->getOperand(i) != op0) {
12162         op0 = 0; 
12163         break;
12164       }
12165     if (op0)
12166       return ReplaceInstUsesWith(EI, op0);
12167   }
12168   
12169   // If extracting a specified index from the vector, see if we can recursively
12170   // find a previously computed scalar that was inserted into the vector.
12171   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12172     unsigned IndexVal = IdxC->getZExtValue();
12173     unsigned VectorWidth = 
12174       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12175       
12176     // If this is extracting an invalid index, turn this into undef, to avoid
12177     // crashing the code below.
12178     if (IndexVal >= VectorWidth)
12179       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12180     
12181     // This instruction only demands the single element from the input vector.
12182     // If the input vector has a single use, simplify it based on this use
12183     // property.
12184     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12185       APInt UndefElts(VectorWidth, 0);
12186       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12187       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12188                                                 DemandedMask, UndefElts)) {
12189         EI.setOperand(0, V);
12190         return &EI;
12191       }
12192     }
12193     
12194     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
12195       return ReplaceInstUsesWith(EI, Elt);
12196     
12197     // If the this extractelement is directly using a bitcast from a vector of
12198     // the same number of elements, see if we can find the source element from
12199     // it.  In this case, we will end up needing to bitcast the scalars.
12200     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12201       if (const VectorType *VT = 
12202               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12203         if (VT->getNumElements() == VectorWidth)
12204           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12205             return new BitCastInst(Elt, EI.getType());
12206     }
12207   }
12208   
12209   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12210     if (I->hasOneUse()) {
12211       // Push extractelement into predecessor operation if legal and
12212       // profitable to do so
12213       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12214         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12215         if (CheapToScalarize(BO, isConstantElt)) {
12216           ExtractElementInst *newEI0 = 
12217             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12218                                    EI.getName()+".lhs");
12219           ExtractElementInst *newEI1 =
12220             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12221                                    EI.getName()+".rhs");
12222           InsertNewInstBefore(newEI0, EI);
12223           InsertNewInstBefore(newEI1, EI);
12224           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12225         }
12226       } else if (isa<LoadInst>(I)) {
12227         unsigned AS = 
12228           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12229         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12230                                          PointerType::get(EI.getType(), AS),EI);
12231         GetElementPtrInst *GEP =
12232           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12233         InsertNewInstBefore(GEP, EI);
12234         return new LoadInst(GEP);
12235       }
12236     }
12237     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12238       // Extracting the inserted element?
12239       if (IE->getOperand(2) == EI.getOperand(1))
12240         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12241       // If the inserted and extracted elements are constants, they must not
12242       // be the same value, extract from the pre-inserted value instead.
12243       if (isa<Constant>(IE->getOperand(2)) &&
12244           isa<Constant>(EI.getOperand(1))) {
12245         AddUsesToWorkList(EI);
12246         EI.setOperand(0, IE->getOperand(0));
12247         return &EI;
12248       }
12249     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12250       // If this is extracting an element from a shufflevector, figure out where
12251       // it came from and extract from the appropriate input element instead.
12252       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12253         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12254         Value *Src;
12255         unsigned LHSWidth =
12256           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12257
12258         if (SrcIdx < LHSWidth)
12259           Src = SVI->getOperand(0);
12260         else if (SrcIdx < LHSWidth*2) {
12261           SrcIdx -= LHSWidth;
12262           Src = SVI->getOperand(1);
12263         } else {
12264           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12265         }
12266         return new ExtractElementInst(Src, SrcIdx);
12267       }
12268     }
12269   }
12270   return 0;
12271 }
12272
12273 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12274 /// elements from either LHS or RHS, return the shuffle mask and true. 
12275 /// Otherwise, return false.
12276 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12277                                          std::vector<Constant*> &Mask) {
12278   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12279          "Invalid CollectSingleShuffleElements");
12280   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12281
12282   if (isa<UndefValue>(V)) {
12283     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12284     return true;
12285   } else if (V == LHS) {
12286     for (unsigned i = 0; i != NumElts; ++i)
12287       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12288     return true;
12289   } else if (V == RHS) {
12290     for (unsigned i = 0; i != NumElts; ++i)
12291       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12292     return true;
12293   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12294     // If this is an insert of an extract from some other vector, include it.
12295     Value *VecOp    = IEI->getOperand(0);
12296     Value *ScalarOp = IEI->getOperand(1);
12297     Value *IdxOp    = IEI->getOperand(2);
12298     
12299     if (!isa<ConstantInt>(IdxOp))
12300       return false;
12301     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12302     
12303     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12304       // Okay, we can handle this if the vector we are insertinting into is
12305       // transitively ok.
12306       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12307         // If so, update the mask to reflect the inserted undef.
12308         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12309         return true;
12310       }      
12311     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12312       if (isa<ConstantInt>(EI->getOperand(1)) &&
12313           EI->getOperand(0)->getType() == V->getType()) {
12314         unsigned ExtractedIdx =
12315           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12316         
12317         // This must be extracting from either LHS or RHS.
12318         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12319           // Okay, we can handle this if the vector we are insertinting into is
12320           // transitively ok.
12321           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12322             // If so, update the mask to reflect the inserted value.
12323             if (EI->getOperand(0) == LHS) {
12324               Mask[InsertedIdx % NumElts] = 
12325                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12326             } else {
12327               assert(EI->getOperand(0) == RHS);
12328               Mask[InsertedIdx % NumElts] = 
12329                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12330               
12331             }
12332             return true;
12333           }
12334         }
12335       }
12336     }
12337   }
12338   // TODO: Handle shufflevector here!
12339   
12340   return false;
12341 }
12342
12343 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12344 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12345 /// that computes V and the LHS value of the shuffle.
12346 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12347                                      Value *&RHS) {
12348   assert(isa<VectorType>(V->getType()) && 
12349          (RHS == 0 || V->getType() == RHS->getType()) &&
12350          "Invalid shuffle!");
12351   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12352
12353   if (isa<UndefValue>(V)) {
12354     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12355     return V;
12356   } else if (isa<ConstantAggregateZero>(V)) {
12357     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12358     return V;
12359   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12360     // If this is an insert of an extract from some other vector, include it.
12361     Value *VecOp    = IEI->getOperand(0);
12362     Value *ScalarOp = IEI->getOperand(1);
12363     Value *IdxOp    = IEI->getOperand(2);
12364     
12365     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12366       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12367           EI->getOperand(0)->getType() == V->getType()) {
12368         unsigned ExtractedIdx =
12369           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12370         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12371         
12372         // Either the extracted from or inserted into vector must be RHSVec,
12373         // otherwise we'd end up with a shuffle of three inputs.
12374         if (EI->getOperand(0) == RHS || RHS == 0) {
12375           RHS = EI->getOperand(0);
12376           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
12377           Mask[InsertedIdx % NumElts] = 
12378             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12379           return V;
12380         }
12381         
12382         if (VecOp == RHS) {
12383           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
12384           // Everything but the extracted element is replaced with the RHS.
12385           for (unsigned i = 0; i != NumElts; ++i) {
12386             if (i != InsertedIdx)
12387               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12388           }
12389           return V;
12390         }
12391         
12392         // If this insertelement is a chain that comes from exactly these two
12393         // vectors, return the vector and the effective shuffle.
12394         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12395           return EI->getOperand(0);
12396         
12397       }
12398     }
12399   }
12400   // TODO: Handle shufflevector here!
12401   
12402   // Otherwise, can't do anything fancy.  Return an identity vector.
12403   for (unsigned i = 0; i != NumElts; ++i)
12404     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12405   return V;
12406 }
12407
12408 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12409   Value *VecOp    = IE.getOperand(0);
12410   Value *ScalarOp = IE.getOperand(1);
12411   Value *IdxOp    = IE.getOperand(2);
12412   
12413   // Inserting an undef or into an undefined place, remove this.
12414   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12415     ReplaceInstUsesWith(IE, VecOp);
12416   
12417   // If the inserted element was extracted from some other vector, and if the 
12418   // indexes are constant, try to turn this into a shufflevector operation.
12419   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12420     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12421         EI->getOperand(0)->getType() == IE.getType()) {
12422       unsigned NumVectorElts = IE.getType()->getNumElements();
12423       unsigned ExtractedIdx =
12424         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12425       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12426       
12427       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12428         return ReplaceInstUsesWith(IE, VecOp);
12429       
12430       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12431         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12432       
12433       // If we are extracting a value from a vector, then inserting it right
12434       // back into the same place, just use the input vector.
12435       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12436         return ReplaceInstUsesWith(IE, VecOp);      
12437       
12438       // We could theoretically do this for ANY input.  However, doing so could
12439       // turn chains of insertelement instructions into a chain of shufflevector
12440       // instructions, and right now we do not merge shufflevectors.  As such,
12441       // only do this in a situation where it is clear that there is benefit.
12442       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12443         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12444         // the values of VecOp, except then one read from EIOp0.
12445         // Build a new shuffle mask.
12446         std::vector<Constant*> Mask;
12447         if (isa<UndefValue>(VecOp))
12448           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12449         else {
12450           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12451           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12452                                                        NumVectorElts));
12453         } 
12454         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12455         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12456                                      ConstantVector::get(Mask));
12457       }
12458       
12459       // If this insertelement isn't used by some other insertelement, turn it
12460       // (and any insertelements it points to), into one big shuffle.
12461       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12462         std::vector<Constant*> Mask;
12463         Value *RHS = 0;
12464         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12465         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12466         // We now have a shuffle of LHS, RHS, Mask.
12467         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12468       }
12469     }
12470   }
12471
12472   return 0;
12473 }
12474
12475
12476 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12477   Value *LHS = SVI.getOperand(0);
12478   Value *RHS = SVI.getOperand(1);
12479   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12480
12481   bool MadeChange = false;
12482
12483   // Undefined shuffle mask -> undefined value.
12484   if (isa<UndefValue>(SVI.getOperand(2)))
12485     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12486
12487   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12488
12489   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12490     return 0;
12491
12492   APInt UndefElts(VWidth, 0);
12493   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12494   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12495     LHS = SVI.getOperand(0);
12496     RHS = SVI.getOperand(1);
12497     MadeChange = true;
12498   }
12499   
12500   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12501   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12502   if (LHS == RHS || isa<UndefValue>(LHS)) {
12503     if (isa<UndefValue>(LHS) && LHS == RHS) {
12504       // shuffle(undef,undef,mask) -> undef.
12505       return ReplaceInstUsesWith(SVI, LHS);
12506     }
12507     
12508     // Remap any references to RHS to use LHS.
12509     std::vector<Constant*> Elts;
12510     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12511       if (Mask[i] >= 2*e)
12512         Elts.push_back(UndefValue::get(Type::Int32Ty));
12513       else {
12514         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12515             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12516           Mask[i] = 2*e;     // Turn into undef.
12517           Elts.push_back(UndefValue::get(Type::Int32Ty));
12518         } else {
12519           Mask[i] = Mask[i] % e;  // Force to LHS.
12520           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12521         }
12522       }
12523     }
12524     SVI.setOperand(0, SVI.getOperand(1));
12525     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12526     SVI.setOperand(2, ConstantVector::get(Elts));
12527     LHS = SVI.getOperand(0);
12528     RHS = SVI.getOperand(1);
12529     MadeChange = true;
12530   }
12531   
12532   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12533   bool isLHSID = true, isRHSID = true;
12534     
12535   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12536     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12537     // Is this an identity shuffle of the LHS value?
12538     isLHSID &= (Mask[i] == i);
12539       
12540     // Is this an identity shuffle of the RHS value?
12541     isRHSID &= (Mask[i]-e == i);
12542   }
12543
12544   // Eliminate identity shuffles.
12545   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12546   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12547   
12548   // If the LHS is a shufflevector itself, see if we can combine it with this
12549   // one without producing an unusual shuffle.  Here we are really conservative:
12550   // we are absolutely afraid of producing a shuffle mask not in the input
12551   // program, because the code gen may not be smart enough to turn a merged
12552   // shuffle into two specific shuffles: it may produce worse code.  As such,
12553   // we only merge two shuffles if the result is one of the two input shuffle
12554   // masks.  In this case, merging the shuffles just removes one instruction,
12555   // which we know is safe.  This is good for things like turning:
12556   // (splat(splat)) -> splat.
12557   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12558     if (isa<UndefValue>(RHS)) {
12559       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12560
12561       std::vector<unsigned> NewMask;
12562       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12563         if (Mask[i] >= 2*e)
12564           NewMask.push_back(2*e);
12565         else
12566           NewMask.push_back(LHSMask[Mask[i]]);
12567       
12568       // If the result mask is equal to the src shuffle or this shuffle mask, do
12569       // the replacement.
12570       if (NewMask == LHSMask || NewMask == Mask) {
12571         unsigned LHSInNElts =
12572           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12573         std::vector<Constant*> Elts;
12574         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12575           if (NewMask[i] >= LHSInNElts*2) {
12576             Elts.push_back(UndefValue::get(Type::Int32Ty));
12577           } else {
12578             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12579           }
12580         }
12581         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12582                                      LHSSVI->getOperand(1),
12583                                      ConstantVector::get(Elts));
12584       }
12585     }
12586   }
12587
12588   return MadeChange ? &SVI : 0;
12589 }
12590
12591
12592
12593
12594 /// TryToSinkInstruction - Try to move the specified instruction from its
12595 /// current block into the beginning of DestBlock, which can only happen if it's
12596 /// safe to move the instruction past all of the instructions between it and the
12597 /// end of its block.
12598 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12599   assert(I->hasOneUse() && "Invariants didn't hold!");
12600
12601   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12602   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12603     return false;
12604
12605   // Do not sink alloca instructions out of the entry block.
12606   if (isa<AllocaInst>(I) && I->getParent() ==
12607         &DestBlock->getParent()->getEntryBlock())
12608     return false;
12609
12610   // We can only sink load instructions if there is nothing between the load and
12611   // the end of block that could change the value.
12612   if (I->mayReadFromMemory()) {
12613     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12614          Scan != E; ++Scan)
12615       if (Scan->mayWriteToMemory())
12616         return false;
12617   }
12618
12619   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12620
12621   CopyPrecedingStopPoint(I, InsertPos);
12622   I->moveBefore(InsertPos);
12623   ++NumSunkInst;
12624   return true;
12625 }
12626
12627
12628 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12629 /// all reachable code to the worklist.
12630 ///
12631 /// This has a couple of tricks to make the code faster and more powerful.  In
12632 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12633 /// them to the worklist (this significantly speeds up instcombine on code where
12634 /// many instructions are dead or constant).  Additionally, if we find a branch
12635 /// whose condition is a known constant, we only visit the reachable successors.
12636 ///
12637 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12638                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12639                                        InstCombiner &IC,
12640                                        const TargetData *TD) {
12641   SmallVector<BasicBlock*, 256> Worklist;
12642   Worklist.push_back(BB);
12643
12644   while (!Worklist.empty()) {
12645     BB = Worklist.back();
12646     Worklist.pop_back();
12647     
12648     // We have now visited this block!  If we've already been here, ignore it.
12649     if (!Visited.insert(BB)) continue;
12650
12651     DbgInfoIntrinsic *DBI_Prev = NULL;
12652     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12653       Instruction *Inst = BBI++;
12654       
12655       // DCE instruction if trivially dead.
12656       if (isInstructionTriviallyDead(Inst)) {
12657         ++NumDeadInst;
12658         DOUT << "IC: DCE: " << *Inst;
12659         Inst->eraseFromParent();
12660         continue;
12661       }
12662       
12663       // ConstantProp instruction if trivially constant.
12664       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12665         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12666         Inst->replaceAllUsesWith(C);
12667         ++NumConstProp;
12668         Inst->eraseFromParent();
12669         continue;
12670       }
12671      
12672       // If there are two consecutive llvm.dbg.stoppoint calls then
12673       // it is likely that the optimizer deleted code in between these
12674       // two intrinsics. 
12675       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12676       if (DBI_Next) {
12677         if (DBI_Prev
12678             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12679             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12680           IC.RemoveFromWorkList(DBI_Prev);
12681           DBI_Prev->eraseFromParent();
12682         }
12683         DBI_Prev = DBI_Next;
12684       } else {
12685         DBI_Prev = 0;
12686       }
12687
12688       IC.AddToWorkList(Inst);
12689     }
12690
12691     // Recursively visit successors.  If this is a branch or switch on a
12692     // constant, only visit the reachable successor.
12693     TerminatorInst *TI = BB->getTerminator();
12694     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12695       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12696         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12697         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12698         Worklist.push_back(ReachableBB);
12699         continue;
12700       }
12701     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12702       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12703         // See if this is an explicit destination.
12704         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12705           if (SI->getCaseValue(i) == Cond) {
12706             BasicBlock *ReachableBB = SI->getSuccessor(i);
12707             Worklist.push_back(ReachableBB);
12708             continue;
12709           }
12710         
12711         // Otherwise it is the default destination.
12712         Worklist.push_back(SI->getSuccessor(0));
12713         continue;
12714       }
12715     }
12716     
12717     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12718       Worklist.push_back(TI->getSuccessor(i));
12719   }
12720 }
12721
12722 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12723   bool Changed = false;
12724   TD = &getAnalysis<TargetData>();
12725   
12726   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12727              << F.getNameStr() << "\n");
12728
12729   {
12730     // Do a depth-first traversal of the function, populate the worklist with
12731     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12732     // track of which blocks we visit.
12733     SmallPtrSet<BasicBlock*, 64> Visited;
12734     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12735
12736     // Do a quick scan over the function.  If we find any blocks that are
12737     // unreachable, remove any instructions inside of them.  This prevents
12738     // the instcombine code from having to deal with some bad special cases.
12739     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12740       if (!Visited.count(BB)) {
12741         Instruction *Term = BB->getTerminator();
12742         while (Term != BB->begin()) {   // Remove instrs bottom-up
12743           BasicBlock::iterator I = Term; --I;
12744
12745           DOUT << "IC: DCE: " << *I;
12746           // A debug intrinsic shouldn't force another iteration if we weren't
12747           // going to do one without it.
12748           if (!isa<DbgInfoIntrinsic>(I)) {
12749             ++NumDeadInst;
12750             Changed = true;
12751           }
12752           if (!I->use_empty())
12753             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12754           I->eraseFromParent();
12755         }
12756       }
12757   }
12758
12759   while (!Worklist.empty()) {
12760     Instruction *I = RemoveOneFromWorkList();
12761     if (I == 0) continue;  // skip null values.
12762
12763     // Check to see if we can DCE the instruction.
12764     if (isInstructionTriviallyDead(I)) {
12765       // Add operands to the worklist.
12766       if (I->getNumOperands() < 4)
12767         AddUsesToWorkList(*I);
12768       ++NumDeadInst;
12769
12770       DOUT << "IC: DCE: " << *I;
12771
12772       I->eraseFromParent();
12773       RemoveFromWorkList(I);
12774       Changed = true;
12775       continue;
12776     }
12777
12778     // Instruction isn't dead, see if we can constant propagate it.
12779     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12780       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12781
12782       // Add operands to the worklist.
12783       AddUsesToWorkList(*I);
12784       ReplaceInstUsesWith(*I, C);
12785
12786       ++NumConstProp;
12787       I->eraseFromParent();
12788       RemoveFromWorkList(I);
12789       Changed = true;
12790       continue;
12791     }
12792
12793     if (TD &&
12794         (I->getType()->getTypeID() == Type::VoidTyID ||
12795          I->isTrapping())) {
12796       // See if we can constant fold its operands.
12797       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12798         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12799           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12800             if (NewC != CE) {
12801               i->set(NewC);
12802               Changed = true;
12803             }
12804     }
12805
12806     // See if we can trivially sink this instruction to a successor basic block.
12807     if (I->hasOneUse()) {
12808       BasicBlock *BB = I->getParent();
12809       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12810       if (UserParent != BB) {
12811         bool UserIsSuccessor = false;
12812         // See if the user is one of our successors.
12813         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12814           if (*SI == UserParent) {
12815             UserIsSuccessor = true;
12816             break;
12817           }
12818
12819         // If the user is one of our immediate successors, and if that successor
12820         // only has us as a predecessors (we'd have to split the critical edge
12821         // otherwise), we can keep going.
12822         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12823             next(pred_begin(UserParent)) == pred_end(UserParent))
12824           // Okay, the CFG is simple enough, try to sink this instruction.
12825           Changed |= TryToSinkInstruction(I, UserParent);
12826       }
12827     }
12828
12829     // Now that we have an instruction, try combining it to simplify it...
12830 #ifndef NDEBUG
12831     std::string OrigI;
12832 #endif
12833     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12834     if (Instruction *Result = visit(*I)) {
12835       ++NumCombined;
12836       // Should we replace the old instruction with a new one?
12837       if (Result != I) {
12838         DOUT << "IC: Old = " << *I
12839              << "    New = " << *Result;
12840
12841         // Everything uses the new instruction now.
12842         I->replaceAllUsesWith(Result);
12843
12844         // Push the new instruction and any users onto the worklist.
12845         AddToWorkList(Result);
12846         AddUsersToWorkList(*Result);
12847
12848         // Move the name to the new instruction first.
12849         Result->takeName(I);
12850
12851         // Insert the new instruction into the basic block...
12852         BasicBlock *InstParent = I->getParent();
12853         BasicBlock::iterator InsertPos = I;
12854
12855         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12856           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12857             ++InsertPos;
12858
12859         InstParent->getInstList().insert(InsertPos, Result);
12860
12861         // Make sure that we reprocess all operands now that we reduced their
12862         // use counts.
12863         AddUsesToWorkList(*I);
12864
12865         // Instructions can end up on the worklist more than once.  Make sure
12866         // we do not process an instruction that has been deleted.
12867         RemoveFromWorkList(I);
12868
12869         // Erase the old instruction.
12870         InstParent->getInstList().erase(I);
12871       } else {
12872 #ifndef NDEBUG
12873         DOUT << "IC: Mod = " << OrigI
12874              << "    New = " << *I;
12875 #endif
12876
12877         // If the instruction was modified, it's possible that it is now dead.
12878         // if so, remove it.
12879         if (isInstructionTriviallyDead(I)) {
12880           // Make sure we process all operands now that we are reducing their
12881           // use counts.
12882           AddUsesToWorkList(*I);
12883
12884           // Instructions may end up in the worklist more than once.  Erase all
12885           // occurrences of this instruction.
12886           RemoveFromWorkList(I);
12887           I->eraseFromParent();
12888         } else {
12889           AddToWorkList(I);
12890           AddUsersToWorkList(*I);
12891         }
12892       }
12893       Changed = true;
12894     }
12895   }
12896
12897   assert(WorklistMap.empty() && "Worklist empty, but map not?");
12898     
12899   // Do an explicit clear, this shrinks the map if needed.
12900   WorklistMap.clear();
12901   return Changed;
12902 }
12903
12904
12905 bool InstCombiner::runOnFunction(Function &F) {
12906   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12907   
12908   bool EverMadeChange = false;
12909
12910   // Iterate while there is work to do.
12911   unsigned Iteration = 0;
12912   while (DoOneIteration(F, Iteration++))
12913     EverMadeChange = true;
12914   return EverMadeChange;
12915 }
12916
12917 FunctionPass *llvm::createInstructionCombiningPass() {
12918   return new InstCombiner();
12919 }