Return null instead of false, as appropriate.
[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   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2589     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2590
2591   // Simplify mul instructions with a constant RHS...
2592   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2593     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2594
2595       // ((X << C1)*C2) == (X * (C2 << C1))
2596       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2597         if (SI->getOpcode() == Instruction::Shl)
2598           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2599             return BinaryOperator::CreateMul(SI->getOperand(0),
2600                                              ConstantExpr::getShl(CI, ShOp));
2601
2602       if (CI->isZero())
2603         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2604       if (CI->equalsInt(1))                  // X * 1  == X
2605         return ReplaceInstUsesWith(I, Op0);
2606       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2607         return BinaryOperator::CreateNeg(Op0, I.getName());
2608
2609       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2610       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2611         return BinaryOperator::CreateShl(Op0,
2612                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2613       }
2614     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2615       if (Op1F->isNullValue())
2616         return ReplaceInstUsesWith(I, Op1);
2617
2618       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2619       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2620       if (Op1F->isExactlyValue(1.0))
2621         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2622     } else if (isa<VectorType>(Op1->getType())) {
2623       if (isa<ConstantAggregateZero>(Op1))
2624         return ReplaceInstUsesWith(I, Op1);
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.getTypePaddedSize(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.getTypePaddedSize(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.getTypePaddedSize(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.getTypePaddedSize(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 = ConstantExpr::getFPToSI(RHSC, IntTy);
5602   if (!RHS.isZero() &&
5603       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5604     // If we had a comparison against a fractional value, we have to adjust the
5605     // compare predicate and sometimes the value.  RHSC is rounded towards zero
5606     // at this point.
5607     switch (Pred) {
5608     default: assert(0 && "Unexpected integer comparison!");
5609     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5610       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5611     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5612       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5613     case ICmpInst::ICMP_ULE:
5614       // (float)int <= 4.4   --> int <= 4
5615       // (float)int <= -4.4  --> false
5616       if (RHS.isNegative())
5617         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5618       break;
5619     case ICmpInst::ICMP_SLE:
5620       // (float)int <= 4.4   --> int <= 4
5621       // (float)int <= -4.4  --> int < -4
5622       if (RHS.isNegative())
5623         Pred = ICmpInst::ICMP_SLT;
5624       break;
5625     case ICmpInst::ICMP_ULT:
5626       // (float)int < -4.4   --> false
5627       // (float)int < 4.4    --> int <= 4
5628       if (RHS.isNegative())
5629         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5630       Pred = ICmpInst::ICMP_ULE;
5631       break;
5632     case ICmpInst::ICMP_SLT:
5633       // (float)int < -4.4   --> int < -4
5634       // (float)int < 4.4    --> int <= 4
5635       if (!RHS.isNegative())
5636         Pred = ICmpInst::ICMP_SLE;
5637       break;
5638     case ICmpInst::ICMP_UGT:
5639       // (float)int > 4.4    --> int > 4
5640       // (float)int > -4.4   --> true
5641       if (RHS.isNegative())
5642         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5643       break;
5644     case ICmpInst::ICMP_SGT:
5645       // (float)int > 4.4    --> int > 4
5646       // (float)int > -4.4   --> int >= -4
5647       if (RHS.isNegative())
5648         Pred = ICmpInst::ICMP_SGE;
5649       break;
5650     case ICmpInst::ICMP_UGE:
5651       // (float)int >= -4.4   --> true
5652       // (float)int >= 4.4    --> int > 4
5653       if (!RHS.isNegative())
5654         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5655       Pred = ICmpInst::ICMP_UGT;
5656       break;
5657     case ICmpInst::ICMP_SGE:
5658       // (float)int >= -4.4   --> int >= -4
5659       // (float)int >= 4.4    --> int > 4
5660       if (!RHS.isNegative())
5661         Pred = ICmpInst::ICMP_SGT;
5662       break;
5663     }
5664   }
5665
5666   // Lower this FP comparison into an appropriate integer version of the
5667   // comparison.
5668   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5669 }
5670
5671 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5672   bool Changed = SimplifyCompare(I);
5673   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5674
5675   // Fold trivial predicates.
5676   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5677     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5678   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5679     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5680   
5681   // Simplify 'fcmp pred X, X'
5682   if (Op0 == Op1) {
5683     switch (I.getPredicate()) {
5684     default: assert(0 && "Unknown predicate!");
5685     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5686     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5687     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5688       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5689     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5690     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5691     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5692       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5693       
5694     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5695     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5696     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5697     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5698       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5699       I.setPredicate(FCmpInst::FCMP_UNO);
5700       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5701       return &I;
5702       
5703     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5704     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5705     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5706     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5707       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5708       I.setPredicate(FCmpInst::FCMP_ORD);
5709       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5710       return &I;
5711     }
5712   }
5713     
5714   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5715     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5716
5717   // Handle fcmp with constant RHS
5718   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5719     // If the constant is a nan, see if we can fold the comparison based on it.
5720     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5721       if (CFP->getValueAPF().isNaN()) {
5722         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5723           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5724         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5725                "Comparison must be either ordered or unordered!");
5726         // True if unordered.
5727         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5728       }
5729     }
5730     
5731     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5732       switch (LHSI->getOpcode()) {
5733       case Instruction::PHI:
5734         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5735         // block.  If in the same block, we're encouraging jump threading.  If
5736         // not, we are just pessimizing the code by making an i1 phi.
5737         if (LHSI->getParent() == I.getParent())
5738           if (Instruction *NV = FoldOpIntoPhi(I))
5739             return NV;
5740         break;
5741       case Instruction::SIToFP:
5742       case Instruction::UIToFP:
5743         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5744           return NV;
5745         break;
5746       case Instruction::Select:
5747         // If either operand of the select is a constant, we can fold the
5748         // comparison into the select arms, which will cause one to be
5749         // constant folded and the select turned into a bitwise or.
5750         Value *Op1 = 0, *Op2 = 0;
5751         if (LHSI->hasOneUse()) {
5752           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5753             // Fold the known value into the constant operand.
5754             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5755             // Insert a new FCmp of the other select operand.
5756             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5757                                                       LHSI->getOperand(2), RHSC,
5758                                                       I.getName()), I);
5759           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5760             // Fold the known value into the constant operand.
5761             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5762             // Insert a new FCmp of the other select operand.
5763             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5764                                                       LHSI->getOperand(1), RHSC,
5765                                                       I.getName()), I);
5766           }
5767         }
5768
5769         if (Op1)
5770           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5771         break;
5772       }
5773   }
5774
5775   return Changed ? &I : 0;
5776 }
5777
5778 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5779   bool Changed = SimplifyCompare(I);
5780   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5781   const Type *Ty = Op0->getType();
5782
5783   // icmp X, X
5784   if (Op0 == Op1)
5785     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5786                                                    I.isTrueWhenEqual()));
5787
5788   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5789     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5790   
5791   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5792   // addresses never equal each other!  We already know that Op0 != Op1.
5793   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5794        isa<ConstantPointerNull>(Op0)) &&
5795       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5796        isa<ConstantPointerNull>(Op1)))
5797     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5798                                                    !I.isTrueWhenEqual()));
5799
5800   // icmp's with boolean values can always be turned into bitwise operations
5801   if (Ty == Type::Int1Ty) {
5802     switch (I.getPredicate()) {
5803     default: assert(0 && "Invalid icmp instruction!");
5804     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5805       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5806       InsertNewInstBefore(Xor, I);
5807       return BinaryOperator::CreateNot(Xor);
5808     }
5809     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5810       return BinaryOperator::CreateXor(Op0, Op1);
5811
5812     case ICmpInst::ICMP_UGT:
5813       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5814       // FALL THROUGH
5815     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5816       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5817       InsertNewInstBefore(Not, I);
5818       return BinaryOperator::CreateAnd(Not, Op1);
5819     }
5820     case ICmpInst::ICMP_SGT:
5821       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5822       // FALL THROUGH
5823     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5824       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5825       InsertNewInstBefore(Not, I);
5826       return BinaryOperator::CreateAnd(Not, Op0);
5827     }
5828     case ICmpInst::ICMP_UGE:
5829       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5830       // FALL THROUGH
5831     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5832       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5833       InsertNewInstBefore(Not, I);
5834       return BinaryOperator::CreateOr(Not, Op1);
5835     }
5836     case ICmpInst::ICMP_SGE:
5837       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5838       // FALL THROUGH
5839     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5840       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5841       InsertNewInstBefore(Not, I);
5842       return BinaryOperator::CreateOr(Not, Op0);
5843     }
5844     }
5845   }
5846
5847   unsigned BitWidth = 0;
5848   if (TD)
5849     BitWidth = TD->getTypeSizeInBits(Ty);
5850   else if (isa<IntegerType>(Ty))
5851     BitWidth = Ty->getPrimitiveSizeInBits();
5852
5853   bool isSignBit = false;
5854
5855   // See if we are doing a comparison with a constant.
5856   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5857     Value *A = 0, *B = 0;
5858     
5859     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5860     if (I.isEquality() && CI->isNullValue() &&
5861         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5862       // (icmp cond A B) if cond is equality
5863       return new ICmpInst(I.getPredicate(), A, B);
5864     }
5865     
5866     // If we have an icmp le or icmp ge instruction, turn it into the
5867     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5868     // them being folded in the code below.
5869     switch (I.getPredicate()) {
5870     default: break;
5871     case ICmpInst::ICMP_ULE:
5872       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5873         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5874       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5875     case ICmpInst::ICMP_SLE:
5876       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5877         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5878       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5879     case ICmpInst::ICMP_UGE:
5880       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5881         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5882       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5883     case ICmpInst::ICMP_SGE:
5884       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5885         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5886       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5887     }
5888     
5889     // If this comparison is a normal comparison, it demands all
5890     // bits, if it is a sign bit comparison, it only demands the sign bit.
5891     bool UnusedBit;
5892     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5893   }
5894
5895   // See if we can fold the comparison based on range information we can get
5896   // by checking whether bits are known to be zero or one in the input.
5897   if (BitWidth != 0) {
5898     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
5899     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
5900
5901     if (SimplifyDemandedBits(I.getOperandUse(0),
5902                              isSignBit ? APInt::getSignBit(BitWidth)
5903                                        : APInt::getAllOnesValue(BitWidth),
5904                              Op0KnownZero, Op0KnownOne, 0))
5905       return &I;
5906     if (SimplifyDemandedBits(I.getOperandUse(1),
5907                              APInt::getAllOnesValue(BitWidth),
5908                              Op1KnownZero, Op1KnownOne, 0))
5909       return &I;
5910
5911     // Given the known and unknown bits, compute a range that the LHS could be
5912     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5913     // EQ and NE we use unsigned values.
5914     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
5915     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
5916     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5917       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
5918                                              Op0Min, Op0Max);
5919       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
5920                                              Op1Min, Op1Max);
5921     } else {
5922       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
5923                                                Op0Min, Op0Max);
5924       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
5925                                                Op1Min, Op1Max);
5926     }
5927
5928     // If Min and Max are known to be the same, then SimplifyDemandedBits
5929     // figured out that the LHS is a constant.  Just constant fold this now so
5930     // that code below can assume that Min != Max.
5931     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
5932       return new ICmpInst(I.getPredicate(), ConstantInt::get(Op0Min), Op1);
5933     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
5934       return new ICmpInst(I.getPredicate(), Op0, ConstantInt::get(Op1Min));
5935
5936     // Based on the range information we know about the LHS, see if we can
5937     // simplify this comparison.  For example, (x&4) < 8  is always true.
5938     switch (I.getPredicate()) {
5939     default: assert(0 && "Unknown icmp opcode!");
5940     case ICmpInst::ICMP_EQ:
5941       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
5942         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5943       break;
5944     case ICmpInst::ICMP_NE:
5945       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
5946         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5947       break;
5948     case ICmpInst::ICMP_ULT:
5949       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
5950         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5951       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
5952         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5953       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
5954         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5955       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5956         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
5957           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5958
5959         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5960         if (CI->isMinValue(true))
5961           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5962                             ConstantInt::getAllOnesValue(Op0->getType()));
5963       }
5964       break;
5965     case ICmpInst::ICMP_UGT:
5966       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
5967         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5968       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
5969         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5970
5971       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
5972         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5973       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5974         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
5975           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5976
5977         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5978         if (CI->isMaxValue(true))
5979           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5980                               ConstantInt::getNullValue(Op0->getType()));
5981       }
5982       break;
5983     case ICmpInst::ICMP_SLT:
5984       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
5985         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5986       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
5987         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5988       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
5989         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5990       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5991         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
5992           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5993       }
5994       break;
5995     case ICmpInst::ICMP_SGT:
5996       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
5997         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5998       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
5999         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6000
6001       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6002         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6003       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6004         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6005           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6006       }
6007       break;
6008     case ICmpInst::ICMP_SGE:
6009       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6010       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6011         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6012       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6013         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6014       break;
6015     case ICmpInst::ICMP_SLE:
6016       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6017       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6018         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6019       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6020         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6021       break;
6022     case ICmpInst::ICMP_UGE:
6023       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6024       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6025         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6026       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6027         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6028       break;
6029     case ICmpInst::ICMP_ULE:
6030       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6031       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6032         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6033       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6034         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6035       break;
6036     }
6037
6038     // Turn a signed comparison into an unsigned one if both operands
6039     // are known to have the same sign.
6040     if (I.isSignedPredicate() &&
6041         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6042          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6043       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6044   }
6045
6046   // Test if the ICmpInst instruction is used exclusively by a select as
6047   // part of a minimum or maximum operation. If so, refrain from doing
6048   // any other folding. This helps out other analyses which understand
6049   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6050   // and CodeGen. And in this case, at least one of the comparison
6051   // operands has at least one user besides the compare (the select),
6052   // which would often largely negate the benefit of folding anyway.
6053   if (I.hasOneUse())
6054     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6055       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6056           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6057         return 0;
6058
6059   // See if we are doing a comparison between a constant and an instruction that
6060   // can be folded into the comparison.
6061   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6062     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6063     // instruction, see if that instruction also has constants so that the 
6064     // instruction can be folded into the icmp 
6065     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6066       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6067         return Res;
6068   }
6069
6070   // Handle icmp with constant (but not simple integer constant) RHS
6071   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6072     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6073       switch (LHSI->getOpcode()) {
6074       case Instruction::GetElementPtr:
6075         if (RHSC->isNullValue()) {
6076           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6077           bool isAllZeros = true;
6078           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6079             if (!isa<Constant>(LHSI->getOperand(i)) ||
6080                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6081               isAllZeros = false;
6082               break;
6083             }
6084           if (isAllZeros)
6085             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6086                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6087         }
6088         break;
6089
6090       case Instruction::PHI:
6091         // Only fold icmp into the PHI if the phi and fcmp are in the same
6092         // block.  If in the same block, we're encouraging jump threading.  If
6093         // not, we are just pessimizing the code by making an i1 phi.
6094         if (LHSI->getParent() == I.getParent())
6095           if (Instruction *NV = FoldOpIntoPhi(I))
6096             return NV;
6097         break;
6098       case Instruction::Select: {
6099         // If either operand of the select is a constant, we can fold the
6100         // comparison into the select arms, which will cause one to be
6101         // constant folded and the select turned into a bitwise or.
6102         Value *Op1 = 0, *Op2 = 0;
6103         if (LHSI->hasOneUse()) {
6104           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6105             // Fold the known value into the constant operand.
6106             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6107             // Insert a new ICmp of the other select operand.
6108             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6109                                                    LHSI->getOperand(2), RHSC,
6110                                                    I.getName()), I);
6111           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6112             // Fold the known value into the constant operand.
6113             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6114             // Insert a new ICmp of the other select operand.
6115             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6116                                                    LHSI->getOperand(1), RHSC,
6117                                                    I.getName()), I);
6118           }
6119         }
6120
6121         if (Op1)
6122           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6123         break;
6124       }
6125       case Instruction::Malloc:
6126         // If we have (malloc != null), and if the malloc has a single use, we
6127         // can assume it is successful and remove the malloc.
6128         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6129           AddToWorkList(LHSI);
6130           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6131                                                          !I.isTrueWhenEqual()));
6132         }
6133         break;
6134       }
6135   }
6136
6137   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6138   if (User *GEP = dyn_castGetElementPtr(Op0))
6139     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6140       return NI;
6141   if (User *GEP = dyn_castGetElementPtr(Op1))
6142     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6143                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6144       return NI;
6145
6146   // Test to see if the operands of the icmp are casted versions of other
6147   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6148   // now.
6149   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6150     if (isa<PointerType>(Op0->getType()) && 
6151         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6152       // We keep moving the cast from the left operand over to the right
6153       // operand, where it can often be eliminated completely.
6154       Op0 = CI->getOperand(0);
6155
6156       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6157       // so eliminate it as well.
6158       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6159         Op1 = CI2->getOperand(0);
6160
6161       // If Op1 is a constant, we can fold the cast into the constant.
6162       if (Op0->getType() != Op1->getType()) {
6163         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6164           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6165         } else {
6166           // Otherwise, cast the RHS right before the icmp
6167           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6168         }
6169       }
6170       return new ICmpInst(I.getPredicate(), Op0, Op1);
6171     }
6172   }
6173   
6174   if (isa<CastInst>(Op0)) {
6175     // Handle the special case of: icmp (cast bool to X), <cst>
6176     // This comes up when you have code like
6177     //   int X = A < B;
6178     //   if (X) ...
6179     // For generality, we handle any zero-extension of any operand comparison
6180     // with a constant or another cast from the same type.
6181     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6182       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6183         return R;
6184   }
6185   
6186   // See if it's the same type of instruction on the left and right.
6187   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6188     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6189       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6190           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6191         switch (Op0I->getOpcode()) {
6192         default: break;
6193         case Instruction::Add:
6194         case Instruction::Sub:
6195         case Instruction::Xor:
6196           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6197             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6198                                 Op1I->getOperand(0));
6199           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6200           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6201             if (CI->getValue().isSignBit()) {
6202               ICmpInst::Predicate Pred = I.isSignedPredicate()
6203                                              ? I.getUnsignedPredicate()
6204                                              : I.getSignedPredicate();
6205               return new ICmpInst(Pred, Op0I->getOperand(0),
6206                                   Op1I->getOperand(0));
6207             }
6208             
6209             if (CI->getValue().isMaxSignedValue()) {
6210               ICmpInst::Predicate Pred = I.isSignedPredicate()
6211                                              ? I.getUnsignedPredicate()
6212                                              : I.getSignedPredicate();
6213               Pred = I.getSwappedPredicate(Pred);
6214               return new ICmpInst(Pred, Op0I->getOperand(0),
6215                                   Op1I->getOperand(0));
6216             }
6217           }
6218           break;
6219         case Instruction::Mul:
6220           if (!I.isEquality())
6221             break;
6222
6223           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6224             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6225             // Mask = -1 >> count-trailing-zeros(Cst).
6226             if (!CI->isZero() && !CI->isOne()) {
6227               const APInt &AP = CI->getValue();
6228               ConstantInt *Mask = ConstantInt::get(
6229                                       APInt::getLowBitsSet(AP.getBitWidth(),
6230                                                            AP.getBitWidth() -
6231                                                       AP.countTrailingZeros()));
6232               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6233                                                             Mask);
6234               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6235                                                             Mask);
6236               InsertNewInstBefore(And1, I);
6237               InsertNewInstBefore(And2, I);
6238               return new ICmpInst(I.getPredicate(), And1, And2);
6239             }
6240           }
6241           break;
6242         }
6243       }
6244     }
6245   }
6246   
6247   // ~x < ~y --> y < x
6248   { Value *A, *B;
6249     if (match(Op0, m_Not(m_Value(A))) &&
6250         match(Op1, m_Not(m_Value(B))))
6251       return new ICmpInst(I.getPredicate(), B, A);
6252   }
6253   
6254   if (I.isEquality()) {
6255     Value *A, *B, *C, *D;
6256     
6257     // -x == -y --> x == y
6258     if (match(Op0, m_Neg(m_Value(A))) &&
6259         match(Op1, m_Neg(m_Value(B))))
6260       return new ICmpInst(I.getPredicate(), A, B);
6261     
6262     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6263       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6264         Value *OtherVal = A == Op1 ? B : A;
6265         return new ICmpInst(I.getPredicate(), OtherVal,
6266                             Constant::getNullValue(A->getType()));
6267       }
6268
6269       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6270         // A^c1 == C^c2 --> A == C^(c1^c2)
6271         ConstantInt *C1, *C2;
6272         if (match(B, m_ConstantInt(C1)) &&
6273             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6274           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6275           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6276           return new ICmpInst(I.getPredicate(), A,
6277                               InsertNewInstBefore(Xor, I));
6278         }
6279         
6280         // A^B == A^D -> B == D
6281         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6282         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6283         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6284         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6285       }
6286     }
6287     
6288     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6289         (A == Op0 || B == Op0)) {
6290       // A == (A^B)  ->  B == 0
6291       Value *OtherVal = A == Op0 ? B : A;
6292       return new ICmpInst(I.getPredicate(), OtherVal,
6293                           Constant::getNullValue(A->getType()));
6294     }
6295
6296     // (A-B) == A  ->  B == 0
6297     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6298       return new ICmpInst(I.getPredicate(), B, 
6299                           Constant::getNullValue(B->getType()));
6300
6301     // A == (A-B)  ->  B == 0
6302     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6303       return new ICmpInst(I.getPredicate(), B,
6304                           Constant::getNullValue(B->getType()));
6305     
6306     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6307     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6308         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6309         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6310       Value *X = 0, *Y = 0, *Z = 0;
6311       
6312       if (A == C) {
6313         X = B; Y = D; Z = A;
6314       } else if (A == D) {
6315         X = B; Y = C; Z = A;
6316       } else if (B == C) {
6317         X = A; Y = D; Z = B;
6318       } else if (B == D) {
6319         X = A; Y = C; Z = B;
6320       }
6321       
6322       if (X) {   // Build (X^Y) & Z
6323         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6324         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6325         I.setOperand(0, Op1);
6326         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6327         return &I;
6328       }
6329     }
6330   }
6331   return Changed ? &I : 0;
6332 }
6333
6334
6335 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6336 /// and CmpRHS are both known to be integer constants.
6337 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6338                                           ConstantInt *DivRHS) {
6339   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6340   const APInt &CmpRHSV = CmpRHS->getValue();
6341   
6342   // FIXME: If the operand types don't match the type of the divide 
6343   // then don't attempt this transform. The code below doesn't have the
6344   // logic to deal with a signed divide and an unsigned compare (and
6345   // vice versa). This is because (x /s C1) <s C2  produces different 
6346   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6347   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6348   // work. :(  The if statement below tests that condition and bails 
6349   // if it finds it. 
6350   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6351   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6352     return 0;
6353   if (DivRHS->isZero())
6354     return 0; // The ProdOV computation fails on divide by zero.
6355   if (DivIsSigned && DivRHS->isAllOnesValue())
6356     return 0; // The overflow computation also screws up here
6357   if (DivRHS->isOne())
6358     return 0; // Not worth bothering, and eliminates some funny cases
6359               // with INT_MIN.
6360
6361   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6362   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6363   // C2 (CI). By solving for X we can turn this into a range check 
6364   // instead of computing a divide. 
6365   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6366
6367   // Determine if the product overflows by seeing if the product is
6368   // not equal to the divide. Make sure we do the same kind of divide
6369   // as in the LHS instruction that we're folding. 
6370   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6371                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6372
6373   // Get the ICmp opcode
6374   ICmpInst::Predicate Pred = ICI.getPredicate();
6375
6376   // Figure out the interval that is being checked.  For example, a comparison
6377   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6378   // Compute this interval based on the constants involved and the signedness of
6379   // the compare/divide.  This computes a half-open interval, keeping track of
6380   // whether either value in the interval overflows.  After analysis each
6381   // overflow variable is set to 0 if it's corresponding bound variable is valid
6382   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6383   int LoOverflow = 0, HiOverflow = 0;
6384   ConstantInt *LoBound = 0, *HiBound = 0;
6385   
6386   if (!DivIsSigned) {  // udiv
6387     // e.g. X/5 op 3  --> [15, 20)
6388     LoBound = Prod;
6389     HiOverflow = LoOverflow = ProdOV;
6390     if (!HiOverflow)
6391       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6392   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6393     if (CmpRHSV == 0) {       // (X / pos) op 0
6394       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6395       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6396       HiBound = DivRHS;
6397     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6398       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6399       HiOverflow = LoOverflow = ProdOV;
6400       if (!HiOverflow)
6401         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6402     } else {                       // (X / pos) op neg
6403       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6404       HiBound = AddOne(Prod);
6405       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6406       if (!LoOverflow) {
6407         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6408         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6409                                      true) ? -1 : 0;
6410        }
6411     }
6412   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6413     if (CmpRHSV == 0) {       // (X / neg) op 0
6414       // e.g. X/-5 op 0  --> [-4, 5)
6415       LoBound = AddOne(DivRHS);
6416       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6417       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6418         HiOverflow = 1;            // [INTMIN+1, overflow)
6419         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6420       }
6421     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6422       // e.g. X/-5 op 3  --> [-19, -14)
6423       HiBound = AddOne(Prod);
6424       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6425       if (!LoOverflow)
6426         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6427     } else {                       // (X / neg) op neg
6428       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6429       LoOverflow = HiOverflow = ProdOV;
6430       if (!HiOverflow)
6431         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6432     }
6433     
6434     // Dividing by a negative swaps the condition.  LT <-> GT
6435     Pred = ICmpInst::getSwappedPredicate(Pred);
6436   }
6437
6438   Value *X = DivI->getOperand(0);
6439   switch (Pred) {
6440   default: assert(0 && "Unhandled icmp opcode!");
6441   case ICmpInst::ICMP_EQ:
6442     if (LoOverflow && HiOverflow)
6443       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6444     else if (HiOverflow)
6445       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6446                           ICmpInst::ICMP_UGE, X, LoBound);
6447     else if (LoOverflow)
6448       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6449                           ICmpInst::ICMP_ULT, X, HiBound);
6450     else
6451       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6452   case ICmpInst::ICMP_NE:
6453     if (LoOverflow && HiOverflow)
6454       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6455     else if (HiOverflow)
6456       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6457                           ICmpInst::ICMP_ULT, X, LoBound);
6458     else if (LoOverflow)
6459       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6460                           ICmpInst::ICMP_UGE, X, HiBound);
6461     else
6462       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6463   case ICmpInst::ICMP_ULT:
6464   case ICmpInst::ICMP_SLT:
6465     if (LoOverflow == +1)   // Low bound is greater than input range.
6466       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6467     if (LoOverflow == -1)   // Low bound is less than input range.
6468       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6469     return new ICmpInst(Pred, X, LoBound);
6470   case ICmpInst::ICMP_UGT:
6471   case ICmpInst::ICMP_SGT:
6472     if (HiOverflow == +1)       // High bound greater than input range.
6473       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6474     else if (HiOverflow == -1)  // High bound less than input range.
6475       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6476     if (Pred == ICmpInst::ICMP_UGT)
6477       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6478     else
6479       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6480   }
6481 }
6482
6483
6484 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6485 ///
6486 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6487                                                           Instruction *LHSI,
6488                                                           ConstantInt *RHS) {
6489   const APInt &RHSV = RHS->getValue();
6490   
6491   switch (LHSI->getOpcode()) {
6492   case Instruction::Trunc:
6493     if (ICI.isEquality() && LHSI->hasOneUse()) {
6494       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6495       // of the high bits truncated out of x are known.
6496       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6497              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6498       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6499       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6500       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6501       
6502       // If all the high bits are known, we can do this xform.
6503       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6504         // Pull in the high bits from known-ones set.
6505         APInt NewRHS(RHS->getValue());
6506         NewRHS.zext(SrcBits);
6507         NewRHS |= KnownOne;
6508         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6509                             ConstantInt::get(NewRHS));
6510       }
6511     }
6512     break;
6513       
6514   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6515     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6516       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6517       // fold the xor.
6518       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6519           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6520         Value *CompareVal = LHSI->getOperand(0);
6521         
6522         // If the sign bit of the XorCST is not set, there is no change to
6523         // the operation, just stop using the Xor.
6524         if (!XorCST->getValue().isNegative()) {
6525           ICI.setOperand(0, CompareVal);
6526           AddToWorkList(LHSI);
6527           return &ICI;
6528         }
6529         
6530         // Was the old condition true if the operand is positive?
6531         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6532         
6533         // If so, the new one isn't.
6534         isTrueIfPositive ^= true;
6535         
6536         if (isTrueIfPositive)
6537           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6538         else
6539           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6540       }
6541
6542       if (LHSI->hasOneUse()) {
6543         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6544         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6545           const APInt &SignBit = XorCST->getValue();
6546           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6547                                          ? ICI.getUnsignedPredicate()
6548                                          : ICI.getSignedPredicate();
6549           return new ICmpInst(Pred, LHSI->getOperand(0),
6550                               ConstantInt::get(RHSV ^ SignBit));
6551         }
6552
6553         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6554         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6555           const APInt &NotSignBit = XorCST->getValue();
6556           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6557                                          ? ICI.getUnsignedPredicate()
6558                                          : ICI.getSignedPredicate();
6559           Pred = ICI.getSwappedPredicate(Pred);
6560           return new ICmpInst(Pred, LHSI->getOperand(0),
6561                               ConstantInt::get(RHSV ^ NotSignBit));
6562         }
6563       }
6564     }
6565     break;
6566   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6567     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6568         LHSI->getOperand(0)->hasOneUse()) {
6569       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6570       
6571       // If the LHS is an AND of a truncating cast, we can widen the
6572       // and/compare to be the input width without changing the value
6573       // produced, eliminating a cast.
6574       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6575         // We can do this transformation if either the AND constant does not
6576         // have its sign bit set or if it is an equality comparison. 
6577         // Extending a relational comparison when we're checking the sign
6578         // bit would not work.
6579         if (Cast->hasOneUse() &&
6580             (ICI.isEquality() ||
6581              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6582           uint32_t BitWidth = 
6583             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6584           APInt NewCST = AndCST->getValue();
6585           NewCST.zext(BitWidth);
6586           APInt NewCI = RHSV;
6587           NewCI.zext(BitWidth);
6588           Instruction *NewAnd = 
6589             BinaryOperator::CreateAnd(Cast->getOperand(0),
6590                                       ConstantInt::get(NewCST),LHSI->getName());
6591           InsertNewInstBefore(NewAnd, ICI);
6592           return new ICmpInst(ICI.getPredicate(), NewAnd,
6593                               ConstantInt::get(NewCI));
6594         }
6595       }
6596       
6597       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6598       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6599       // happens a LOT in code produced by the C front-end, for bitfield
6600       // access.
6601       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6602       if (Shift && !Shift->isShift())
6603         Shift = 0;
6604       
6605       ConstantInt *ShAmt;
6606       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6607       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6608       const Type *AndTy = AndCST->getType();          // Type of the and.
6609       
6610       // We can fold this as long as we can't shift unknown bits
6611       // into the mask.  This can only happen with signed shift
6612       // rights, as they sign-extend.
6613       if (ShAmt) {
6614         bool CanFold = Shift->isLogicalShift();
6615         if (!CanFold) {
6616           // To test for the bad case of the signed shr, see if any
6617           // of the bits shifted in could be tested after the mask.
6618           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6619           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6620           
6621           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6622           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6623                AndCST->getValue()) == 0)
6624             CanFold = true;
6625         }
6626         
6627         if (CanFold) {
6628           Constant *NewCst;
6629           if (Shift->getOpcode() == Instruction::Shl)
6630             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6631           else
6632             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6633           
6634           // Check to see if we are shifting out any of the bits being
6635           // compared.
6636           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6637             // If we shifted bits out, the fold is not going to work out.
6638             // As a special case, check to see if this means that the
6639             // result is always true or false now.
6640             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6641               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6642             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6643               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6644           } else {
6645             ICI.setOperand(1, NewCst);
6646             Constant *NewAndCST;
6647             if (Shift->getOpcode() == Instruction::Shl)
6648               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6649             else
6650               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6651             LHSI->setOperand(1, NewAndCST);
6652             LHSI->setOperand(0, Shift->getOperand(0));
6653             AddToWorkList(Shift); // Shift is dead.
6654             AddUsesToWorkList(ICI);
6655             return &ICI;
6656           }
6657         }
6658       }
6659       
6660       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6661       // preferable because it allows the C<<Y expression to be hoisted out
6662       // of a loop if Y is invariant and X is not.
6663       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6664           ICI.isEquality() && !Shift->isArithmeticShift() &&
6665           !isa<Constant>(Shift->getOperand(0))) {
6666         // Compute C << Y.
6667         Value *NS;
6668         if (Shift->getOpcode() == Instruction::LShr) {
6669           NS = BinaryOperator::CreateShl(AndCST, 
6670                                          Shift->getOperand(1), "tmp");
6671         } else {
6672           // Insert a logical shift.
6673           NS = BinaryOperator::CreateLShr(AndCST,
6674                                           Shift->getOperand(1), "tmp");
6675         }
6676         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6677         
6678         // Compute X & (C << Y).
6679         Instruction *NewAnd = 
6680           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6681         InsertNewInstBefore(NewAnd, ICI);
6682         
6683         ICI.setOperand(0, NewAnd);
6684         return &ICI;
6685       }
6686     }
6687     break;
6688     
6689   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6690     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6691     if (!ShAmt) break;
6692     
6693     uint32_t TypeBits = RHSV.getBitWidth();
6694     
6695     // Check that the shift amount is in range.  If not, don't perform
6696     // undefined shifts.  When the shift is visited it will be
6697     // simplified.
6698     if (ShAmt->uge(TypeBits))
6699       break;
6700     
6701     if (ICI.isEquality()) {
6702       // If we are comparing against bits always shifted out, the
6703       // comparison cannot succeed.
6704       Constant *Comp =
6705         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6706       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6707         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6708         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6709         return ReplaceInstUsesWith(ICI, Cst);
6710       }
6711       
6712       if (LHSI->hasOneUse()) {
6713         // Otherwise strength reduce the shift into an and.
6714         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6715         Constant *Mask =
6716           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6717         
6718         Instruction *AndI =
6719           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6720                                     Mask, LHSI->getName()+".mask");
6721         Value *And = InsertNewInstBefore(AndI, ICI);
6722         return new ICmpInst(ICI.getPredicate(), And,
6723                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6724       }
6725     }
6726     
6727     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6728     bool TrueIfSigned = false;
6729     if (LHSI->hasOneUse() &&
6730         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6731       // (X << 31) <s 0  --> (X&1) != 0
6732       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6733                                            (TypeBits-ShAmt->getZExtValue()-1));
6734       Instruction *AndI =
6735         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6736                                   Mask, LHSI->getName()+".mask");
6737       Value *And = InsertNewInstBefore(AndI, ICI);
6738       
6739       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6740                           And, Constant::getNullValue(And->getType()));
6741     }
6742     break;
6743   }
6744     
6745   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6746   case Instruction::AShr: {
6747     // Only handle equality comparisons of shift-by-constant.
6748     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6749     if (!ShAmt || !ICI.isEquality()) break;
6750
6751     // Check that the shift amount is in range.  If not, don't perform
6752     // undefined shifts.  When the shift is visited it will be
6753     // simplified.
6754     uint32_t TypeBits = RHSV.getBitWidth();
6755     if (ShAmt->uge(TypeBits))
6756       break;
6757     
6758     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6759       
6760     // If we are comparing against bits always shifted out, the
6761     // comparison cannot succeed.
6762     APInt Comp = RHSV << ShAmtVal;
6763     if (LHSI->getOpcode() == Instruction::LShr)
6764       Comp = Comp.lshr(ShAmtVal);
6765     else
6766       Comp = Comp.ashr(ShAmtVal);
6767     
6768     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6769       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6770       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6771       return ReplaceInstUsesWith(ICI, Cst);
6772     }
6773     
6774     // Otherwise, check to see if the bits shifted out are known to be zero.
6775     // If so, we can compare against the unshifted value:
6776     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6777     if (LHSI->hasOneUse() &&
6778         MaskedValueIsZero(LHSI->getOperand(0), 
6779                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6780       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6781                           ConstantExpr::getShl(RHS, ShAmt));
6782     }
6783       
6784     if (LHSI->hasOneUse()) {
6785       // Otherwise strength reduce the shift into an and.
6786       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6787       Constant *Mask = ConstantInt::get(Val);
6788       
6789       Instruction *AndI =
6790         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6791                                   Mask, LHSI->getName()+".mask");
6792       Value *And = InsertNewInstBefore(AndI, ICI);
6793       return new ICmpInst(ICI.getPredicate(), And,
6794                           ConstantExpr::getShl(RHS, ShAmt));
6795     }
6796     break;
6797   }
6798     
6799   case Instruction::SDiv:
6800   case Instruction::UDiv:
6801     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6802     // Fold this div into the comparison, producing a range check. 
6803     // Determine, based on the divide type, what the range is being 
6804     // checked.  If there is an overflow on the low or high side, remember 
6805     // it, otherwise compute the range [low, hi) bounding the new value.
6806     // See: InsertRangeTest above for the kinds of replacements possible.
6807     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6808       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6809                                           DivRHS))
6810         return R;
6811     break;
6812
6813   case Instruction::Add:
6814     // Fold: icmp pred (add, X, C1), C2
6815
6816     if (!ICI.isEquality()) {
6817       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6818       if (!LHSC) break;
6819       const APInt &LHSV = LHSC->getValue();
6820
6821       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6822                             .subtract(LHSV);
6823
6824       if (ICI.isSignedPredicate()) {
6825         if (CR.getLower().isSignBit()) {
6826           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6827                               ConstantInt::get(CR.getUpper()));
6828         } else if (CR.getUpper().isSignBit()) {
6829           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6830                               ConstantInt::get(CR.getLower()));
6831         }
6832       } else {
6833         if (CR.getLower().isMinValue()) {
6834           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6835                               ConstantInt::get(CR.getUpper()));
6836         } else if (CR.getUpper().isMinValue()) {
6837           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6838                               ConstantInt::get(CR.getLower()));
6839         }
6840       }
6841     }
6842     break;
6843   }
6844   
6845   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6846   if (ICI.isEquality()) {
6847     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6848     
6849     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6850     // the second operand is a constant, simplify a bit.
6851     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6852       switch (BO->getOpcode()) {
6853       case Instruction::SRem:
6854         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6855         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6856           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6857           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6858             Instruction *NewRem =
6859               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6860                                          BO->getName());
6861             InsertNewInstBefore(NewRem, ICI);
6862             return new ICmpInst(ICI.getPredicate(), NewRem, 
6863                                 Constant::getNullValue(BO->getType()));
6864           }
6865         }
6866         break;
6867       case Instruction::Add:
6868         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6869         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6870           if (BO->hasOneUse())
6871             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6872                                 Subtract(RHS, BOp1C));
6873         } else if (RHSV == 0) {
6874           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6875           // efficiently invertible, or if the add has just this one use.
6876           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6877           
6878           if (Value *NegVal = dyn_castNegVal(BOp1))
6879             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6880           else if (Value *NegVal = dyn_castNegVal(BOp0))
6881             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6882           else if (BO->hasOneUse()) {
6883             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6884             InsertNewInstBefore(Neg, ICI);
6885             Neg->takeName(BO);
6886             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6887           }
6888         }
6889         break;
6890       case Instruction::Xor:
6891         // For the xor case, we can xor two constants together, eliminating
6892         // the explicit xor.
6893         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6894           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6895                               ConstantExpr::getXor(RHS, BOC));
6896         
6897         // FALLTHROUGH
6898       case Instruction::Sub:
6899         // Replace (([sub|xor] A, B) != 0) with (A != B)
6900         if (RHSV == 0)
6901           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6902                               BO->getOperand(1));
6903         break;
6904         
6905       case Instruction::Or:
6906         // If bits are being or'd in that are not present in the constant we
6907         // are comparing against, then the comparison could never succeed!
6908         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6909           Constant *NotCI = ConstantExpr::getNot(RHS);
6910           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6911             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6912                                                              isICMP_NE));
6913         }
6914         break;
6915         
6916       case Instruction::And:
6917         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6918           // If bits are being compared against that are and'd out, then the
6919           // comparison can never succeed!
6920           if ((RHSV & ~BOC->getValue()) != 0)
6921             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6922                                                              isICMP_NE));
6923           
6924           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6925           if (RHS == BOC && RHSV.isPowerOf2())
6926             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6927                                 ICmpInst::ICMP_NE, LHSI,
6928                                 Constant::getNullValue(RHS->getType()));
6929           
6930           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6931           if (BOC->getValue().isSignBit()) {
6932             Value *X = BO->getOperand(0);
6933             Constant *Zero = Constant::getNullValue(X->getType());
6934             ICmpInst::Predicate pred = isICMP_NE ? 
6935               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6936             return new ICmpInst(pred, X, Zero);
6937           }
6938           
6939           // ((X & ~7) == 0) --> X < 8
6940           if (RHSV == 0 && isHighOnes(BOC)) {
6941             Value *X = BO->getOperand(0);
6942             Constant *NegX = ConstantExpr::getNeg(BOC);
6943             ICmpInst::Predicate pred = isICMP_NE ? 
6944               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6945             return new ICmpInst(pred, X, NegX);
6946           }
6947         }
6948       default: break;
6949       }
6950     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6951       // Handle icmp {eq|ne} <intrinsic>, intcst.
6952       if (II->getIntrinsicID() == Intrinsic::bswap) {
6953         AddToWorkList(II);
6954         ICI.setOperand(0, II->getOperand(1));
6955         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6956         return &ICI;
6957       }
6958     }
6959   }
6960   return 0;
6961 }
6962
6963 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6964 /// We only handle extending casts so far.
6965 ///
6966 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6967   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6968   Value *LHSCIOp        = LHSCI->getOperand(0);
6969   const Type *SrcTy     = LHSCIOp->getType();
6970   const Type *DestTy    = LHSCI->getType();
6971   Value *RHSCIOp;
6972
6973   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6974   // integer type is the same size as the pointer type.
6975   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6976       getTargetData().getPointerSizeInBits() == 
6977          cast<IntegerType>(DestTy)->getBitWidth()) {
6978     Value *RHSOp = 0;
6979     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6980       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6981     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6982       RHSOp = RHSC->getOperand(0);
6983       // If the pointer types don't match, insert a bitcast.
6984       if (LHSCIOp->getType() != RHSOp->getType())
6985         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6986     }
6987
6988     if (RHSOp)
6989       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6990   }
6991   
6992   // The code below only handles extension cast instructions, so far.
6993   // Enforce this.
6994   if (LHSCI->getOpcode() != Instruction::ZExt &&
6995       LHSCI->getOpcode() != Instruction::SExt)
6996     return 0;
6997
6998   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6999   bool isSignedCmp = ICI.isSignedPredicate();
7000
7001   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7002     // Not an extension from the same type?
7003     RHSCIOp = CI->getOperand(0);
7004     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7005       return 0;
7006     
7007     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7008     // and the other is a zext), then we can't handle this.
7009     if (CI->getOpcode() != LHSCI->getOpcode())
7010       return 0;
7011
7012     // Deal with equality cases early.
7013     if (ICI.isEquality())
7014       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7015
7016     // A signed comparison of sign extended values simplifies into a
7017     // signed comparison.
7018     if (isSignedCmp && isSignedExt)
7019       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7020
7021     // The other three cases all fold into an unsigned comparison.
7022     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7023   }
7024
7025   // If we aren't dealing with a constant on the RHS, exit early
7026   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7027   if (!CI)
7028     return 0;
7029
7030   // Compute the constant that would happen if we truncated to SrcTy then
7031   // reextended to DestTy.
7032   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7033   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
7034
7035   // If the re-extended constant didn't change...
7036   if (Res2 == CI) {
7037     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7038     // For example, we might have:
7039     //    %A = sext short %X to uint
7040     //    %B = icmp ugt uint %A, 1330
7041     // It is incorrect to transform this into 
7042     //    %B = icmp ugt short %X, 1330 
7043     // because %A may have negative value. 
7044     //
7045     // However, we allow this when the compare is EQ/NE, because they are
7046     // signless.
7047     if (isSignedExt == isSignedCmp || ICI.isEquality())
7048       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7049     return 0;
7050   }
7051
7052   // The re-extended constant changed so the constant cannot be represented 
7053   // in the shorter type. Consequently, we cannot emit a simple comparison.
7054
7055   // First, handle some easy cases. We know the result cannot be equal at this
7056   // point so handle the ICI.isEquality() cases
7057   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7058     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
7059   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7060     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
7061
7062   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7063   // should have been folded away previously and not enter in here.
7064   Value *Result;
7065   if (isSignedCmp) {
7066     // We're performing a signed comparison.
7067     if (cast<ConstantInt>(CI)->getValue().isNegative())
7068       Result = ConstantInt::getFalse();          // X < (small) --> false
7069     else
7070       Result = ConstantInt::getTrue();           // X < (large) --> true
7071   } else {
7072     // We're performing an unsigned comparison.
7073     if (isSignedExt) {
7074       // We're performing an unsigned comp with a sign extended value.
7075       // This is true if the input is >= 0. [aka >s -1]
7076       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
7077       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
7078                                    NegOne, ICI.getName()), ICI);
7079     } else {
7080       // Unsigned extend & unsigned compare -> always true.
7081       Result = ConstantInt::getTrue();
7082     }
7083   }
7084
7085   // Finally, return the value computed.
7086   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7087       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7088     return ReplaceInstUsesWith(ICI, Result);
7089
7090   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7091           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7092          "ICmp should be folded!");
7093   if (Constant *CI = dyn_cast<Constant>(Result))
7094     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7095   return BinaryOperator::CreateNot(Result);
7096 }
7097
7098 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7099   return commonShiftTransforms(I);
7100 }
7101
7102 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7103   return commonShiftTransforms(I);
7104 }
7105
7106 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7107   if (Instruction *R = commonShiftTransforms(I))
7108     return R;
7109   
7110   Value *Op0 = I.getOperand(0);
7111   
7112   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7113   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7114     if (CSI->isAllOnesValue())
7115       return ReplaceInstUsesWith(I, CSI);
7116   
7117   // See if we can turn a signed shr into an unsigned shr.
7118   if (!isa<VectorType>(I.getType())) {
7119     if (MaskedValueIsZero(Op0,
7120                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
7121       return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7122
7123     // Arithmetic shifting an all-sign-bit value is a no-op.
7124     unsigned NumSignBits = ComputeNumSignBits(Op0);
7125     if (NumSignBits == Op0->getType()->getPrimitiveSizeInBits())
7126       return ReplaceInstUsesWith(I, Op0);
7127   }
7128
7129   return 0;
7130 }
7131
7132 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7133   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7134   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7135
7136   // shl X, 0 == X and shr X, 0 == X
7137   // shl 0, X == 0 and shr 0, X == 0
7138   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7139       Op0 == Constant::getNullValue(Op0->getType()))
7140     return ReplaceInstUsesWith(I, Op0);
7141   
7142   if (isa<UndefValue>(Op0)) {            
7143     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7144       return ReplaceInstUsesWith(I, Op0);
7145     else                                    // undef << X -> 0, undef >>u X -> 0
7146       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7147   }
7148   if (isa<UndefValue>(Op1)) {
7149     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7150       return ReplaceInstUsesWith(I, Op0);          
7151     else                                     // X << undef, X >>u undef -> 0
7152       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7153   }
7154
7155   // Try to fold constant and into select arguments.
7156   if (isa<Constant>(Op0))
7157     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7158       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7159         return R;
7160
7161   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7162     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7163       return Res;
7164   return 0;
7165 }
7166
7167 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7168                                                BinaryOperator &I) {
7169   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7170
7171   // See if we can simplify any instructions used by the instruction whose sole 
7172   // purpose is to compute bits we don't care about.
7173   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
7174   if (SimplifyDemandedInstructionBits(I))
7175     return &I;
7176   
7177   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7178   // of a signed value.
7179   //
7180   if (Op1->uge(TypeBits)) {
7181     if (I.getOpcode() != Instruction::AShr)
7182       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7183     else {
7184       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7185       return &I;
7186     }
7187   }
7188   
7189   // ((X*C1) << C2) == (X * (C1 << C2))
7190   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7191     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7192       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7193         return BinaryOperator::CreateMul(BO->getOperand(0),
7194                                          ConstantExpr::getShl(BOOp, Op1));
7195   
7196   // Try to fold constant and into select arguments.
7197   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7198     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7199       return R;
7200   if (isa<PHINode>(Op0))
7201     if (Instruction *NV = FoldOpIntoPhi(I))
7202       return NV;
7203   
7204   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7205   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7206     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7207     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7208     // place.  Don't try to do this transformation in this case.  Also, we
7209     // require that the input operand is a shift-by-constant so that we have
7210     // confidence that the shifts will get folded together.  We could do this
7211     // xform in more cases, but it is unlikely to be profitable.
7212     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7213         isa<ConstantInt>(TrOp->getOperand(1))) {
7214       // Okay, we'll do this xform.  Make the shift of shift.
7215       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7216       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7217                                                 I.getName());
7218       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7219
7220       // For logical shifts, the truncation has the effect of making the high
7221       // part of the register be zeros.  Emulate this by inserting an AND to
7222       // clear the top bits as needed.  This 'and' will usually be zapped by
7223       // other xforms later if dead.
7224       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7225       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7226       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7227       
7228       // The mask we constructed says what the trunc would do if occurring
7229       // between the shifts.  We want to know the effect *after* the second
7230       // shift.  We know that it is a logical shift by a constant, so adjust the
7231       // mask as appropriate.
7232       if (I.getOpcode() == Instruction::Shl)
7233         MaskV <<= Op1->getZExtValue();
7234       else {
7235         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7236         MaskV = MaskV.lshr(Op1->getZExtValue());
7237       }
7238
7239       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7240                                                    TI->getName());
7241       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7242
7243       // Return the value truncated to the interesting size.
7244       return new TruncInst(And, I.getType());
7245     }
7246   }
7247   
7248   if (Op0->hasOneUse()) {
7249     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7250       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7251       Value *V1, *V2;
7252       ConstantInt *CC;
7253       switch (Op0BO->getOpcode()) {
7254         default: break;
7255         case Instruction::Add:
7256         case Instruction::And:
7257         case Instruction::Or:
7258         case Instruction::Xor: {
7259           // These operators commute.
7260           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7261           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7262               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7263             Instruction *YS = BinaryOperator::CreateShl(
7264                                             Op0BO->getOperand(0), Op1,
7265                                             Op0BO->getName());
7266             InsertNewInstBefore(YS, I); // (Y << C)
7267             Instruction *X = 
7268               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7269                                      Op0BO->getOperand(1)->getName());
7270             InsertNewInstBefore(X, I);  // (X + (Y << C))
7271             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7272             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7273                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7274           }
7275           
7276           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7277           Value *Op0BOOp1 = Op0BO->getOperand(1);
7278           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7279               match(Op0BOOp1, 
7280                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7281                           m_ConstantInt(CC))) &&
7282               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7283             Instruction *YS = BinaryOperator::CreateShl(
7284                                                      Op0BO->getOperand(0), Op1,
7285                                                      Op0BO->getName());
7286             InsertNewInstBefore(YS, I); // (Y << C)
7287             Instruction *XM =
7288               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7289                                         V1->getName()+".mask");
7290             InsertNewInstBefore(XM, I); // X & (CC << C)
7291             
7292             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7293           }
7294         }
7295           
7296         // FALL THROUGH.
7297         case Instruction::Sub: {
7298           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7299           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7300               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7301             Instruction *YS = BinaryOperator::CreateShl(
7302                                                      Op0BO->getOperand(1), Op1,
7303                                                      Op0BO->getName());
7304             InsertNewInstBefore(YS, I); // (Y << C)
7305             Instruction *X =
7306               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7307                                      Op0BO->getOperand(0)->getName());
7308             InsertNewInstBefore(X, I);  // (X + (Y << C))
7309             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7310             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7311                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7312           }
7313           
7314           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7315           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7316               match(Op0BO->getOperand(0),
7317                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7318                           m_ConstantInt(CC))) && V2 == Op1 &&
7319               cast<BinaryOperator>(Op0BO->getOperand(0))
7320                   ->getOperand(0)->hasOneUse()) {
7321             Instruction *YS = BinaryOperator::CreateShl(
7322                                                      Op0BO->getOperand(1), Op1,
7323                                                      Op0BO->getName());
7324             InsertNewInstBefore(YS, I); // (Y << C)
7325             Instruction *XM =
7326               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7327                                         V1->getName()+".mask");
7328             InsertNewInstBefore(XM, I); // X & (CC << C)
7329             
7330             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7331           }
7332           
7333           break;
7334         }
7335       }
7336       
7337       
7338       // If the operand is an bitwise operator with a constant RHS, and the
7339       // shift is the only use, we can pull it out of the shift.
7340       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7341         bool isValid = true;     // Valid only for And, Or, Xor
7342         bool highBitSet = false; // Transform if high bit of constant set?
7343         
7344         switch (Op0BO->getOpcode()) {
7345           default: isValid = false; break;   // Do not perform transform!
7346           case Instruction::Add:
7347             isValid = isLeftShift;
7348             break;
7349           case Instruction::Or:
7350           case Instruction::Xor:
7351             highBitSet = false;
7352             break;
7353           case Instruction::And:
7354             highBitSet = true;
7355             break;
7356         }
7357         
7358         // If this is a signed shift right, and the high bit is modified
7359         // by the logical operation, do not perform the transformation.
7360         // The highBitSet boolean indicates the value of the high bit of
7361         // the constant which would cause it to be modified for this
7362         // operation.
7363         //
7364         if (isValid && I.getOpcode() == Instruction::AShr)
7365           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7366         
7367         if (isValid) {
7368           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7369           
7370           Instruction *NewShift =
7371             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7372           InsertNewInstBefore(NewShift, I);
7373           NewShift->takeName(Op0BO);
7374           
7375           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7376                                         NewRHS);
7377         }
7378       }
7379     }
7380   }
7381   
7382   // Find out if this is a shift of a shift by a constant.
7383   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7384   if (ShiftOp && !ShiftOp->isShift())
7385     ShiftOp = 0;
7386   
7387   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7388     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7389     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7390     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7391     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7392     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7393     Value *X = ShiftOp->getOperand(0);
7394     
7395     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7396     
7397     const IntegerType *Ty = cast<IntegerType>(I.getType());
7398     
7399     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7400     if (I.getOpcode() == ShiftOp->getOpcode()) {
7401       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7402       // saturates.
7403       if (AmtSum >= TypeBits) {
7404         if (I.getOpcode() != Instruction::AShr)
7405           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7406         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7407       }
7408       
7409       return BinaryOperator::Create(I.getOpcode(), X,
7410                                     ConstantInt::get(Ty, AmtSum));
7411     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7412                I.getOpcode() == Instruction::AShr) {
7413       if (AmtSum >= TypeBits)
7414         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7415       
7416       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7417       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7418     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7419                I.getOpcode() == Instruction::LShr) {
7420       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7421       if (AmtSum >= TypeBits)
7422         AmtSum = TypeBits-1;
7423       
7424       Instruction *Shift =
7425         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7426       InsertNewInstBefore(Shift, I);
7427
7428       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7429       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7430     }
7431     
7432     // Okay, if we get here, one shift must be left, and the other shift must be
7433     // right.  See if the amounts are equal.
7434     if (ShiftAmt1 == ShiftAmt2) {
7435       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7436       if (I.getOpcode() == Instruction::Shl) {
7437         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7438         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7439       }
7440       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7441       if (I.getOpcode() == Instruction::LShr) {
7442         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7443         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7444       }
7445       // We can simplify ((X << C) >>s C) into a trunc + sext.
7446       // NOTE: we could do this for any C, but that would make 'unusual' integer
7447       // types.  For now, just stick to ones well-supported by the code
7448       // generators.
7449       const Type *SExtType = 0;
7450       switch (Ty->getBitWidth() - ShiftAmt1) {
7451       case 1  :
7452       case 8  :
7453       case 16 :
7454       case 32 :
7455       case 64 :
7456       case 128:
7457         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7458         break;
7459       default: break;
7460       }
7461       if (SExtType) {
7462         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7463         InsertNewInstBefore(NewTrunc, I);
7464         return new SExtInst(NewTrunc, Ty);
7465       }
7466       // Otherwise, we can't handle it yet.
7467     } else if (ShiftAmt1 < ShiftAmt2) {
7468       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7469       
7470       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7471       if (I.getOpcode() == Instruction::Shl) {
7472         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7473                ShiftOp->getOpcode() == Instruction::AShr);
7474         Instruction *Shift =
7475           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7476         InsertNewInstBefore(Shift, I);
7477         
7478         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7479         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7480       }
7481       
7482       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7483       if (I.getOpcode() == Instruction::LShr) {
7484         assert(ShiftOp->getOpcode() == Instruction::Shl);
7485         Instruction *Shift =
7486           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7487         InsertNewInstBefore(Shift, I);
7488         
7489         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7490         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7491       }
7492       
7493       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7494     } else {
7495       assert(ShiftAmt2 < ShiftAmt1);
7496       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7497
7498       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7499       if (I.getOpcode() == Instruction::Shl) {
7500         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7501                ShiftOp->getOpcode() == Instruction::AShr);
7502         Instruction *Shift =
7503           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7504                                  ConstantInt::get(Ty, ShiftDiff));
7505         InsertNewInstBefore(Shift, I);
7506         
7507         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7508         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7509       }
7510       
7511       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7512       if (I.getOpcode() == Instruction::LShr) {
7513         assert(ShiftOp->getOpcode() == Instruction::Shl);
7514         Instruction *Shift =
7515           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7516         InsertNewInstBefore(Shift, I);
7517         
7518         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7519         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7520       }
7521       
7522       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7523     }
7524   }
7525   return 0;
7526 }
7527
7528
7529 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7530 /// expression.  If so, decompose it, returning some value X, such that Val is
7531 /// X*Scale+Offset.
7532 ///
7533 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7534                                         int &Offset) {
7535   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7536   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7537     Offset = CI->getZExtValue();
7538     Scale  = 0;
7539     return ConstantInt::get(Type::Int32Ty, 0);
7540   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7541     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7542       if (I->getOpcode() == Instruction::Shl) {
7543         // This is a value scaled by '1 << the shift amt'.
7544         Scale = 1U << RHS->getZExtValue();
7545         Offset = 0;
7546         return I->getOperand(0);
7547       } else if (I->getOpcode() == Instruction::Mul) {
7548         // This value is scaled by 'RHS'.
7549         Scale = RHS->getZExtValue();
7550         Offset = 0;
7551         return I->getOperand(0);
7552       } else if (I->getOpcode() == Instruction::Add) {
7553         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7554         // where C1 is divisible by C2.
7555         unsigned SubScale;
7556         Value *SubVal = 
7557           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7558         Offset += RHS->getZExtValue();
7559         Scale = SubScale;
7560         return SubVal;
7561       }
7562     }
7563   }
7564
7565   // Otherwise, we can't look past this.
7566   Scale = 1;
7567   Offset = 0;
7568   return Val;
7569 }
7570
7571
7572 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7573 /// try to eliminate the cast by moving the type information into the alloc.
7574 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7575                                                    AllocationInst &AI) {
7576   const PointerType *PTy = cast<PointerType>(CI.getType());
7577   
7578   // Remove any uses of AI that are dead.
7579   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7580   
7581   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7582     Instruction *User = cast<Instruction>(*UI++);
7583     if (isInstructionTriviallyDead(User)) {
7584       while (UI != E && *UI == User)
7585         ++UI; // If this instruction uses AI more than once, don't break UI.
7586       
7587       ++NumDeadInst;
7588       DOUT << "IC: DCE: " << *User;
7589       EraseInstFromFunction(*User);
7590     }
7591   }
7592   
7593   // Get the type really allocated and the type casted to.
7594   const Type *AllocElTy = AI.getAllocatedType();
7595   const Type *CastElTy = PTy->getElementType();
7596   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7597
7598   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7599   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7600   if (CastElTyAlign < AllocElTyAlign) return 0;
7601
7602   // If the allocation has multiple uses, only promote it if we are strictly
7603   // increasing the alignment of the resultant allocation.  If we keep it the
7604   // same, we open the door to infinite loops of various kinds.  (A reference
7605   // from a dbg.declare doesn't count as a use for this purpose.)
7606   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7607       CastElTyAlign == AllocElTyAlign) return 0;
7608
7609   uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7610   uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
7611   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7612
7613   // See if we can satisfy the modulus by pulling a scale out of the array
7614   // size argument.
7615   unsigned ArraySizeScale;
7616   int ArrayOffset;
7617   Value *NumElements = // See if the array size is a decomposable linear expr.
7618     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7619  
7620   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7621   // do the xform.
7622   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7623       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7624
7625   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7626   Value *Amt = 0;
7627   if (Scale == 1) {
7628     Amt = NumElements;
7629   } else {
7630     // If the allocation size is constant, form a constant mul expression
7631     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7632     if (isa<ConstantInt>(NumElements))
7633       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7634     // otherwise multiply the amount and the number of elements
7635     else {
7636       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7637       Amt = InsertNewInstBefore(Tmp, AI);
7638     }
7639   }
7640   
7641   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7642     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7643     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7644     Amt = InsertNewInstBefore(Tmp, AI);
7645   }
7646   
7647   AllocationInst *New;
7648   if (isa<MallocInst>(AI))
7649     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7650   else
7651     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7652   InsertNewInstBefore(New, AI);
7653   New->takeName(&AI);
7654   
7655   // If the allocation has one real use plus a dbg.declare, just remove the
7656   // declare.
7657   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7658     EraseInstFromFunction(*DI);
7659   }
7660   // If the allocation has multiple real uses, insert a cast and change all
7661   // things that used it to use the new cast.  This will also hack on CI, but it
7662   // will die soon.
7663   else if (!AI.hasOneUse()) {
7664     AddUsesToWorkList(AI);
7665     // New is the allocation instruction, pointer typed. AI is the original
7666     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7667     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7668     InsertNewInstBefore(NewCast, AI);
7669     AI.replaceAllUsesWith(NewCast);
7670   }
7671   return ReplaceInstUsesWith(CI, New);
7672 }
7673
7674 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7675 /// and return it as type Ty without inserting any new casts and without
7676 /// changing the computed value.  This is used by code that tries to decide
7677 /// whether promoting or shrinking integer operations to wider or smaller types
7678 /// will allow us to eliminate a truncate or extend.
7679 ///
7680 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7681 /// extension operation if Ty is larger.
7682 ///
7683 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7684 /// should return true if trunc(V) can be computed by computing V in the smaller
7685 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7686 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7687 /// efficiently truncated.
7688 ///
7689 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7690 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7691 /// the final result.
7692 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7693                                               unsigned CastOpc,
7694                                               int &NumCastsRemoved){
7695   // We can always evaluate constants in another type.
7696   if (isa<ConstantInt>(V))
7697     return true;
7698   
7699   Instruction *I = dyn_cast<Instruction>(V);
7700   if (!I) return false;
7701   
7702   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7703   
7704   // If this is an extension or truncate, we can often eliminate it.
7705   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7706     // If this is a cast from the destination type, we can trivially eliminate
7707     // it, and this will remove a cast overall.
7708     if (I->getOperand(0)->getType() == Ty) {
7709       // If the first operand is itself a cast, and is eliminable, do not count
7710       // this as an eliminable cast.  We would prefer to eliminate those two
7711       // casts first.
7712       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7713         ++NumCastsRemoved;
7714       return true;
7715     }
7716   }
7717
7718   // We can't extend or shrink something that has multiple uses: doing so would
7719   // require duplicating the instruction in general, which isn't profitable.
7720   if (!I->hasOneUse()) return false;
7721
7722   unsigned Opc = I->getOpcode();
7723   switch (Opc) {
7724   case Instruction::Add:
7725   case Instruction::Sub:
7726   case Instruction::Mul:
7727   case Instruction::And:
7728   case Instruction::Or:
7729   case Instruction::Xor:
7730     // These operators can all arbitrarily be extended or truncated.
7731     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7732                                       NumCastsRemoved) &&
7733            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7734                                       NumCastsRemoved);
7735
7736   case Instruction::Shl:
7737     // If we are truncating the result of this SHL, and if it's a shift of a
7738     // constant amount, we can always perform a SHL in a smaller type.
7739     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7740       uint32_t BitWidth = Ty->getBitWidth();
7741       if (BitWidth < OrigTy->getBitWidth() && 
7742           CI->getLimitedValue(BitWidth) < BitWidth)
7743         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7744                                           NumCastsRemoved);
7745     }
7746     break;
7747   case Instruction::LShr:
7748     // If this is a truncate of a logical shr, we can truncate it to a smaller
7749     // lshr iff we know that the bits we would otherwise be shifting in are
7750     // already zeros.
7751     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7752       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7753       uint32_t BitWidth = Ty->getBitWidth();
7754       if (BitWidth < OrigBitWidth &&
7755           MaskedValueIsZero(I->getOperand(0),
7756             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7757           CI->getLimitedValue(BitWidth) < BitWidth) {
7758         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7759                                           NumCastsRemoved);
7760       }
7761     }
7762     break;
7763   case Instruction::ZExt:
7764   case Instruction::SExt:
7765   case Instruction::Trunc:
7766     // If this is the same kind of case as our original (e.g. zext+zext), we
7767     // can safely replace it.  Note that replacing it does not reduce the number
7768     // of casts in the input.
7769     if (Opc == CastOpc)
7770       return true;
7771
7772     // sext (zext ty1), ty2 -> zext ty2
7773     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7774       return true;
7775     break;
7776   case Instruction::Select: {
7777     SelectInst *SI = cast<SelectInst>(I);
7778     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7779                                       NumCastsRemoved) &&
7780            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7781                                       NumCastsRemoved);
7782   }
7783   case Instruction::PHI: {
7784     // We can change a phi if we can change all operands.
7785     PHINode *PN = cast<PHINode>(I);
7786     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7787       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7788                                       NumCastsRemoved))
7789         return false;
7790     return true;
7791   }
7792   default:
7793     // TODO: Can handle more cases here.
7794     break;
7795   }
7796   
7797   return false;
7798 }
7799
7800 /// EvaluateInDifferentType - Given an expression that 
7801 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7802 /// evaluate the expression.
7803 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7804                                              bool isSigned) {
7805   if (Constant *C = dyn_cast<Constant>(V))
7806     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7807
7808   // Otherwise, it must be an instruction.
7809   Instruction *I = cast<Instruction>(V);
7810   Instruction *Res = 0;
7811   unsigned Opc = I->getOpcode();
7812   switch (Opc) {
7813   case Instruction::Add:
7814   case Instruction::Sub:
7815   case Instruction::Mul:
7816   case Instruction::And:
7817   case Instruction::Or:
7818   case Instruction::Xor:
7819   case Instruction::AShr:
7820   case Instruction::LShr:
7821   case Instruction::Shl: {
7822     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7823     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7824     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7825     break;
7826   }    
7827   case Instruction::Trunc:
7828   case Instruction::ZExt:
7829   case Instruction::SExt:
7830     // If the source type of the cast is the type we're trying for then we can
7831     // just return the source.  There's no need to insert it because it is not
7832     // new.
7833     if (I->getOperand(0)->getType() == Ty)
7834       return I->getOperand(0);
7835     
7836     // Otherwise, must be the same type of cast, so just reinsert a new one.
7837     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7838                            Ty);
7839     break;
7840   case Instruction::Select: {
7841     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7842     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7843     Res = SelectInst::Create(I->getOperand(0), True, False);
7844     break;
7845   }
7846   case Instruction::PHI: {
7847     PHINode *OPN = cast<PHINode>(I);
7848     PHINode *NPN = PHINode::Create(Ty);
7849     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7850       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7851       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7852     }
7853     Res = NPN;
7854     break;
7855   }
7856   default: 
7857     // TODO: Can handle more cases here.
7858     assert(0 && "Unreachable!");
7859     break;
7860   }
7861   
7862   Res->takeName(I);
7863   return InsertNewInstBefore(Res, *I);
7864 }
7865
7866 /// @brief Implement the transforms common to all CastInst visitors.
7867 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7868   Value *Src = CI.getOperand(0);
7869
7870   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7871   // eliminate it now.
7872   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7873     if (Instruction::CastOps opc = 
7874         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7875       // The first cast (CSrc) is eliminable so we need to fix up or replace
7876       // the second cast (CI). CSrc will then have a good chance of being dead.
7877       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7878     }
7879   }
7880
7881   // If we are casting a select then fold the cast into the select
7882   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7883     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7884       return NV;
7885
7886   // If we are casting a PHI then fold the cast into the PHI
7887   if (isa<PHINode>(Src))
7888     if (Instruction *NV = FoldOpIntoPhi(CI))
7889       return NV;
7890   
7891   return 0;
7892 }
7893
7894 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7895 /// or not there is a sequence of GEP indices into the type that will land us at
7896 /// the specified offset.  If so, fill them into NewIndices and return the
7897 /// resultant element type, otherwise return null.
7898 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
7899                                        SmallVectorImpl<Value*> &NewIndices,
7900                                        const TargetData *TD) {
7901   if (!Ty->isSized()) return 0;
7902   
7903   // Start with the index over the outer type.  Note that the type size
7904   // might be zero (even if the offset isn't zero) if the indexed type
7905   // is something like [0 x {int, int}]
7906   const Type *IntPtrTy = TD->getIntPtrType();
7907   int64_t FirstIdx = 0;
7908   if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
7909     FirstIdx = Offset/TySize;
7910     Offset -= FirstIdx*TySize;
7911     
7912     // Handle hosts where % returns negative instead of values [0..TySize).
7913     if (Offset < 0) {
7914       --FirstIdx;
7915       Offset += TySize;
7916       assert(Offset >= 0);
7917     }
7918     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7919   }
7920   
7921   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7922     
7923   // Index into the types.  If we fail, set OrigBase to null.
7924   while (Offset) {
7925     // Indexing into tail padding between struct/array elements.
7926     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
7927       return 0;
7928     
7929     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7930       const StructLayout *SL = TD->getStructLayout(STy);
7931       assert(Offset < (int64_t)SL->getSizeInBytes() &&
7932              "Offset must stay within the indexed type");
7933       
7934       unsigned Elt = SL->getElementContainingOffset(Offset);
7935       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7936       
7937       Offset -= SL->getElementOffset(Elt);
7938       Ty = STy->getElementType(Elt);
7939     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
7940       uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
7941       assert(EltSize && "Cannot index into a zero-sized array");
7942       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7943       Offset %= EltSize;
7944       Ty = AT->getElementType();
7945     } else {
7946       // Otherwise, we can't index into the middle of this atomic type, bail.
7947       return 0;
7948     }
7949   }
7950   
7951   return Ty;
7952 }
7953
7954 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7955 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7956   Value *Src = CI.getOperand(0);
7957   
7958   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7959     // If casting the result of a getelementptr instruction with no offset, turn
7960     // this into a cast of the original pointer!
7961     if (GEP->hasAllZeroIndices()) {
7962       // Changing the cast operand is usually not a good idea but it is safe
7963       // here because the pointer operand is being replaced with another 
7964       // pointer operand so the opcode doesn't need to change.
7965       AddToWorkList(GEP);
7966       CI.setOperand(0, GEP->getOperand(0));
7967       return &CI;
7968     }
7969     
7970     // If the GEP has a single use, and the base pointer is a bitcast, and the
7971     // GEP computes a constant offset, see if we can convert these three
7972     // instructions into fewer.  This typically happens with unions and other
7973     // non-type-safe code.
7974     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7975       if (GEP->hasAllConstantIndices()) {
7976         // We are guaranteed to get a constant from EmitGEPOffset.
7977         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7978         int64_t Offset = OffsetV->getSExtValue();
7979         
7980         // Get the base pointer input of the bitcast, and the type it points to.
7981         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7982         const Type *GEPIdxTy =
7983           cast<PointerType>(OrigBase->getType())->getElementType();
7984         SmallVector<Value*, 8> NewIndices;
7985         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7986           // If we were able to index down into an element, create the GEP
7987           // and bitcast the result.  This eliminates one bitcast, potentially
7988           // two.
7989           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7990                                                         NewIndices.begin(),
7991                                                         NewIndices.end(), "");
7992           InsertNewInstBefore(NGEP, CI);
7993           NGEP->takeName(GEP);
7994           
7995           if (isa<BitCastInst>(CI))
7996             return new BitCastInst(NGEP, CI.getType());
7997           assert(isa<PtrToIntInst>(CI));
7998           return new PtrToIntInst(NGEP, CI.getType());
7999         }
8000       }      
8001     }
8002   }
8003     
8004   return commonCastTransforms(CI);
8005 }
8006
8007 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8008 /// type like i42.  We don't want to introduce operations on random non-legal
8009 /// integer types where they don't already exist in the code.  In the future,
8010 /// we should consider making this based off target-data, so that 32-bit targets
8011 /// won't get i64 operations etc.
8012 static bool isSafeIntegerType(const Type *Ty) {
8013   switch (Ty->getPrimitiveSizeInBits()) {
8014   case 8:
8015   case 16:
8016   case 32:
8017   case 64:
8018     return true;
8019   default: 
8020     return false;
8021   }
8022 }
8023
8024 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8025 /// integer types. This function implements the common transforms for all those
8026 /// cases.
8027 /// @brief Implement the transforms common to CastInst with integer operands
8028 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8029   if (Instruction *Result = commonCastTransforms(CI))
8030     return Result;
8031
8032   Value *Src = CI.getOperand(0);
8033   const Type *SrcTy = Src->getType();
8034   const Type *DestTy = CI.getType();
8035   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
8036   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
8037
8038   // See if we can simplify any instructions used by the LHS whose sole 
8039   // purpose is to compute bits we don't care about.
8040   if (SimplifyDemandedInstructionBits(CI))
8041     return &CI;
8042
8043   // If the source isn't an instruction or has more than one use then we
8044   // can't do anything more. 
8045   Instruction *SrcI = dyn_cast<Instruction>(Src);
8046   if (!SrcI || !Src->hasOneUse())
8047     return 0;
8048
8049   // Attempt to propagate the cast into the instruction for int->int casts.
8050   int NumCastsRemoved = 0;
8051   if (!isa<BitCastInst>(CI) &&
8052       // Only do this if the dest type is a simple type, don't convert the
8053       // expression tree to something weird like i93 unless the source is also
8054       // strange.
8055       (isSafeIntegerType(DestTy) || !isSafeIntegerType(SrcI->getType())) &&
8056       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
8057                                  CI.getOpcode(), NumCastsRemoved)) {
8058     // If this cast is a truncate, evaluting in a different type always
8059     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8060     // we need to do an AND to maintain the clear top-part of the computation,
8061     // so we require that the input have eliminated at least one cast.  If this
8062     // is a sign extension, we insert two new casts (to do the extension) so we
8063     // require that two casts have been eliminated.
8064     bool DoXForm = false;
8065     bool JustReplace = false;
8066     switch (CI.getOpcode()) {
8067     default:
8068       // All the others use floating point so we shouldn't actually 
8069       // get here because of the check above.
8070       assert(0 && "Unknown cast type");
8071     case Instruction::Trunc:
8072       DoXForm = true;
8073       break;
8074     case Instruction::ZExt: {
8075       DoXForm = NumCastsRemoved >= 1;
8076       if (!DoXForm && 0) {
8077         // If it's unnecessary to issue an AND to clear the high bits, it's
8078         // always profitable to do this xform.
8079         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8080         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8081         if (MaskedValueIsZero(TryRes, Mask))
8082           return ReplaceInstUsesWith(CI, TryRes);
8083         
8084         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8085           if (TryI->use_empty())
8086             EraseInstFromFunction(*TryI);
8087       }
8088       break;
8089     }
8090     case Instruction::SExt: {
8091       DoXForm = NumCastsRemoved >= 2;
8092       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8093         // If we do not have to emit the truncate + sext pair, then it's always
8094         // profitable to do this xform.
8095         //
8096         // It's not safe to eliminate the trunc + sext pair if one of the
8097         // eliminated cast is a truncate. e.g.
8098         // t2 = trunc i32 t1 to i16
8099         // t3 = sext i16 t2 to i32
8100         // !=
8101         // i32 t1
8102         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8103         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8104         if (NumSignBits > (DestBitSize - SrcBitSize))
8105           return ReplaceInstUsesWith(CI, TryRes);
8106         
8107         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8108           if (TryI->use_empty())
8109             EraseInstFromFunction(*TryI);
8110       }
8111       break;
8112     }
8113     }
8114     
8115     if (DoXForm) {
8116       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8117            << " cast: " << CI;
8118       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8119                                            CI.getOpcode() == Instruction::SExt);
8120       if (JustReplace)
8121         // Just replace this cast with the result.
8122         return ReplaceInstUsesWith(CI, Res);
8123
8124       assert(Res->getType() == DestTy);
8125       switch (CI.getOpcode()) {
8126       default: assert(0 && "Unknown cast type!");
8127       case Instruction::Trunc:
8128       case Instruction::BitCast:
8129         // Just replace this cast with the result.
8130         return ReplaceInstUsesWith(CI, Res);
8131       case Instruction::ZExt: {
8132         assert(SrcBitSize < DestBitSize && "Not a zext?");
8133
8134         // If the high bits are already zero, just replace this cast with the
8135         // result.
8136         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8137         if (MaskedValueIsZero(Res, Mask))
8138           return ReplaceInstUsesWith(CI, Res);
8139
8140         // We need to emit an AND to clear the high bits.
8141         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8142                                                             SrcBitSize));
8143         return BinaryOperator::CreateAnd(Res, C);
8144       }
8145       case Instruction::SExt: {
8146         // If the high bits are already filled with sign bit, just replace this
8147         // cast with the result.
8148         unsigned NumSignBits = ComputeNumSignBits(Res);
8149         if (NumSignBits > (DestBitSize - SrcBitSize))
8150           return ReplaceInstUsesWith(CI, Res);
8151
8152         // We need to emit a cast to truncate, then a cast to sext.
8153         return CastInst::Create(Instruction::SExt,
8154             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8155                              CI), DestTy);
8156       }
8157       }
8158     }
8159   }
8160   
8161   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8162   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8163
8164   switch (SrcI->getOpcode()) {
8165   case Instruction::Add:
8166   case Instruction::Mul:
8167   case Instruction::And:
8168   case Instruction::Or:
8169   case Instruction::Xor:
8170     // If we are discarding information, rewrite.
8171     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8172       // Don't insert two casts if they cannot be eliminated.  We allow 
8173       // two casts to be inserted if the sizes are the same.  This could 
8174       // only be converting signedness, which is a noop.
8175       if (DestBitSize == SrcBitSize || 
8176           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8177           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8178         Instruction::CastOps opcode = CI.getOpcode();
8179         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8180         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8181         return BinaryOperator::Create(
8182             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8183       }
8184     }
8185
8186     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8187     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8188         SrcI->getOpcode() == Instruction::Xor &&
8189         Op1 == ConstantInt::getTrue() &&
8190         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8191       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8192       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
8193     }
8194     break;
8195   case Instruction::SDiv:
8196   case Instruction::UDiv:
8197   case Instruction::SRem:
8198   case Instruction::URem:
8199     // If we are just changing the sign, rewrite.
8200     if (DestBitSize == SrcBitSize) {
8201       // Don't insert two casts if they cannot be eliminated.  We allow 
8202       // two casts to be inserted if the sizes are the same.  This could 
8203       // only be converting signedness, which is a noop.
8204       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
8205           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8206         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
8207                                        Op0, DestTy, *SrcI);
8208         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
8209                                        Op1, DestTy, *SrcI);
8210         return BinaryOperator::Create(
8211           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8212       }
8213     }
8214     break;
8215
8216   case Instruction::Shl:
8217     // Allow changing the sign of the source operand.  Do not allow 
8218     // changing the size of the shift, UNLESS the shift amount is a 
8219     // constant.  We must not change variable sized shifts to a smaller 
8220     // size, because it is undefined to shift more bits out than exist 
8221     // in the value.
8222     if (DestBitSize == SrcBitSize ||
8223         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8224       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8225           Instruction::BitCast : Instruction::Trunc);
8226       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8227       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8228       return BinaryOperator::CreateShl(Op0c, Op1c);
8229     }
8230     break;
8231   case Instruction::AShr:
8232     // If this is a signed shr, and if all bits shifted in are about to be
8233     // truncated off, turn it into an unsigned shr to allow greater
8234     // simplifications.
8235     if (DestBitSize < SrcBitSize &&
8236         isa<ConstantInt>(Op1)) {
8237       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8238       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8239         // Insert the new logical shift right.
8240         return BinaryOperator::CreateLShr(Op0, Op1);
8241       }
8242     }
8243     break;
8244   }
8245   return 0;
8246 }
8247
8248 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8249   if (Instruction *Result = commonIntCastTransforms(CI))
8250     return Result;
8251   
8252   Value *Src = CI.getOperand(0);
8253   const Type *Ty = CI.getType();
8254   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8255   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
8256
8257   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8258   if (DestBitWidth == 1) {
8259     Constant *One = ConstantInt::get(Src->getType(), 1);
8260     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8261     Value *Zero = Constant::getNullValue(Src->getType());
8262     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8263   }
8264   
8265   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8266   ConstantInt *ShAmtV = 0;
8267   Value *ShiftOp = 0;
8268   if (Src->hasOneUse() &&
8269       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8270     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8271     
8272     // Get a mask for the bits shifting in.
8273     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8274     if (MaskedValueIsZero(ShiftOp, Mask)) {
8275       if (ShAmt >= DestBitWidth)        // All zeros.
8276         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8277       
8278       // Okay, we can shrink this.  Truncate the input, then return a new
8279       // shift.
8280       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8281       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8282       return BinaryOperator::CreateLShr(V1, V2);
8283     }
8284   }
8285   
8286   return 0;
8287 }
8288
8289 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8290 /// in order to eliminate the icmp.
8291 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8292                                              bool DoXform) {
8293   // If we are just checking for a icmp eq of a single bit and zext'ing it
8294   // to an integer, then shift the bit to the appropriate place and then
8295   // cast to integer to avoid the comparison.
8296   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8297     const APInt &Op1CV = Op1C->getValue();
8298       
8299     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8300     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8301     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8302         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8303       if (!DoXform) return ICI;
8304
8305       Value *In = ICI->getOperand(0);
8306       Value *Sh = ConstantInt::get(In->getType(),
8307                                    In->getType()->getPrimitiveSizeInBits()-1);
8308       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8309                                                         In->getName()+".lobit"),
8310                                CI);
8311       if (In->getType() != CI.getType())
8312         In = CastInst::CreateIntegerCast(In, CI.getType(),
8313                                          false/*ZExt*/, "tmp", &CI);
8314
8315       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8316         Constant *One = ConstantInt::get(In->getType(), 1);
8317         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8318                                                          In->getName()+".not"),
8319                                  CI);
8320       }
8321
8322       return ReplaceInstUsesWith(CI, In);
8323     }
8324       
8325       
8326       
8327     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8328     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8329     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8330     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8331     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8332     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8333     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8334     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8335     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8336         // This only works for EQ and NE
8337         ICI->isEquality()) {
8338       // If Op1C some other power of two, convert:
8339       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8340       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8341       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8342       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8343         
8344       APInt KnownZeroMask(~KnownZero);
8345       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8346         if (!DoXform) return ICI;
8347
8348         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8349         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8350           // (X&4) == 2 --> false
8351           // (X&4) != 2 --> true
8352           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8353           Res = ConstantExpr::getZExt(Res, CI.getType());
8354           return ReplaceInstUsesWith(CI, Res);
8355         }
8356           
8357         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8358         Value *In = ICI->getOperand(0);
8359         if (ShiftAmt) {
8360           // Perform a logical shr by shiftamt.
8361           // Insert the shift to put the result in the low bit.
8362           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8363                                   ConstantInt::get(In->getType(), ShiftAmt),
8364                                                    In->getName()+".lobit"), CI);
8365         }
8366           
8367         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8368           Constant *One = ConstantInt::get(In->getType(), 1);
8369           In = BinaryOperator::CreateXor(In, One, "tmp");
8370           InsertNewInstBefore(cast<Instruction>(In), CI);
8371         }
8372           
8373         if (CI.getType() == In->getType())
8374           return ReplaceInstUsesWith(CI, In);
8375         else
8376           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8377       }
8378     }
8379   }
8380
8381   return 0;
8382 }
8383
8384 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8385   // If one of the common conversion will work ..
8386   if (Instruction *Result = commonIntCastTransforms(CI))
8387     return Result;
8388
8389   Value *Src = CI.getOperand(0);
8390
8391   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8392   // types and if the sizes are just right we can convert this into a logical
8393   // 'and' which will be much cheaper than the pair of casts.
8394   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8395     // Get the sizes of the types involved.  We know that the intermediate type
8396     // will be smaller than A or C, but don't know the relation between A and C.
8397     Value *A = CSrc->getOperand(0);
8398     unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
8399     unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8400     unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8401     // If we're actually extending zero bits, then if
8402     // SrcSize <  DstSize: zext(a & mask)
8403     // SrcSize == DstSize: a & mask
8404     // SrcSize  > DstSize: trunc(a) & mask
8405     if (SrcSize < DstSize) {
8406       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8407       Constant *AndConst = ConstantInt::get(AndValue);
8408       Instruction *And =
8409         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8410       InsertNewInstBefore(And, CI);
8411       return new ZExtInst(And, CI.getType());
8412     } else if (SrcSize == DstSize) {
8413       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8414       return BinaryOperator::CreateAnd(A, ConstantInt::get(AndValue));
8415     } else if (SrcSize > DstSize) {
8416       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8417       InsertNewInstBefore(Trunc, CI);
8418       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8419       return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(AndValue));
8420     }
8421   }
8422
8423   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8424     return transformZExtICmp(ICI, CI);
8425
8426   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8427   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8428     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8429     // of the (zext icmp) will be transformed.
8430     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8431     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8432     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8433         (transformZExtICmp(LHS, CI, false) ||
8434          transformZExtICmp(RHS, CI, false))) {
8435       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8436       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8437       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8438     }
8439   }
8440
8441   return 0;
8442 }
8443
8444 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8445   if (Instruction *I = commonIntCastTransforms(CI))
8446     return I;
8447   
8448   Value *Src = CI.getOperand(0);
8449   
8450   // Canonicalize sign-extend from i1 to a select.
8451   if (Src->getType() == Type::Int1Ty)
8452     return SelectInst::Create(Src,
8453                               ConstantInt::getAllOnesValue(CI.getType()),
8454                               Constant::getNullValue(CI.getType()));
8455
8456   // See if the value being truncated is already sign extended.  If so, just
8457   // eliminate the trunc/sext pair.
8458   if (getOpcode(Src) == Instruction::Trunc) {
8459     Value *Op = cast<User>(Src)->getOperand(0);
8460     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8461     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8462     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8463     unsigned NumSignBits = ComputeNumSignBits(Op);
8464
8465     if (OpBits == DestBits) {
8466       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8467       // bits, it is already ready.
8468       if (NumSignBits > DestBits-MidBits)
8469         return ReplaceInstUsesWith(CI, Op);
8470     } else if (OpBits < DestBits) {
8471       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8472       // bits, just sext from i32.
8473       if (NumSignBits > OpBits-MidBits)
8474         return new SExtInst(Op, CI.getType(), "tmp");
8475     } else {
8476       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8477       // bits, just truncate to i32.
8478       if (NumSignBits > OpBits-MidBits)
8479         return new TruncInst(Op, CI.getType(), "tmp");
8480     }
8481   }
8482
8483   // If the input is a shl/ashr pair of a same constant, then this is a sign
8484   // extension from a smaller value.  If we could trust arbitrary bitwidth
8485   // integers, we could turn this into a truncate to the smaller bit and then
8486   // use a sext for the whole extension.  Since we don't, look deeper and check
8487   // for a truncate.  If the source and dest are the same type, eliminate the
8488   // trunc and extend and just do shifts.  For example, turn:
8489   //   %a = trunc i32 %i to i8
8490   //   %b = shl i8 %a, 6
8491   //   %c = ashr i8 %b, 6
8492   //   %d = sext i8 %c to i32
8493   // into:
8494   //   %a = shl i32 %i, 30
8495   //   %d = ashr i32 %a, 30
8496   Value *A = 0;
8497   ConstantInt *BA = 0, *CA = 0;
8498   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8499                         m_ConstantInt(CA))) &&
8500       BA == CA && isa<TruncInst>(A)) {
8501     Value *I = cast<TruncInst>(A)->getOperand(0);
8502     if (I->getType() == CI.getType()) {
8503       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8504       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8505       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8506       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8507       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8508                                                         CI.getName()), CI);
8509       return BinaryOperator::CreateAShr(I, ShAmtV);
8510     }
8511   }
8512   
8513   return 0;
8514 }
8515
8516 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8517 /// in the specified FP type without changing its value.
8518 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8519   bool losesInfo;
8520   APFloat F = CFP->getValueAPF();
8521   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8522   if (!losesInfo)
8523     return ConstantFP::get(F);
8524   return 0;
8525 }
8526
8527 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8528 /// through it until we get the source value.
8529 static Value *LookThroughFPExtensions(Value *V) {
8530   if (Instruction *I = dyn_cast<Instruction>(V))
8531     if (I->getOpcode() == Instruction::FPExt)
8532       return LookThroughFPExtensions(I->getOperand(0));
8533   
8534   // If this value is a constant, return the constant in the smallest FP type
8535   // that can accurately represent it.  This allows us to turn
8536   // (float)((double)X+2.0) into x+2.0f.
8537   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8538     if (CFP->getType() == Type::PPC_FP128Ty)
8539       return V;  // No constant folding of this.
8540     // See if the value can be truncated to float and then reextended.
8541     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8542       return V;
8543     if (CFP->getType() == Type::DoubleTy)
8544       return V;  // Won't shrink.
8545     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8546       return V;
8547     // Don't try to shrink to various long double types.
8548   }
8549   
8550   return V;
8551 }
8552
8553 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8554   if (Instruction *I = commonCastTransforms(CI))
8555     return I;
8556   
8557   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8558   // smaller than the destination type, we can eliminate the truncate by doing
8559   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8560   // many builtins (sqrt, etc).
8561   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8562   if (OpI && OpI->hasOneUse()) {
8563     switch (OpI->getOpcode()) {
8564     default: break;
8565     case Instruction::Add:
8566     case Instruction::Sub:
8567     case Instruction::Mul:
8568     case Instruction::FDiv:
8569     case Instruction::FRem:
8570       const Type *SrcTy = OpI->getType();
8571       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8572       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8573       if (LHSTrunc->getType() != SrcTy && 
8574           RHSTrunc->getType() != SrcTy) {
8575         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8576         // If the source types were both smaller than the destination type of
8577         // the cast, do this xform.
8578         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8579             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8580           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8581                                       CI.getType(), CI);
8582           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8583                                       CI.getType(), CI);
8584           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8585         }
8586       }
8587       break;  
8588     }
8589   }
8590   return 0;
8591 }
8592
8593 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8594   return commonCastTransforms(CI);
8595 }
8596
8597 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8598   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8599   if (OpI == 0)
8600     return commonCastTransforms(FI);
8601
8602   // fptoui(uitofp(X)) --> X
8603   // fptoui(sitofp(X)) --> X
8604   // This is safe if the intermediate type has enough bits in its mantissa to
8605   // accurately represent all values of X.  For example, do not do this with
8606   // i64->float->i64.  This is also safe for sitofp case, because any negative
8607   // 'X' value would cause an undefined result for the fptoui. 
8608   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8609       OpI->getOperand(0)->getType() == FI.getType() &&
8610       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8611                     OpI->getType()->getFPMantissaWidth())
8612     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8613
8614   return commonCastTransforms(FI);
8615 }
8616
8617 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8618   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8619   if (OpI == 0)
8620     return commonCastTransforms(FI);
8621   
8622   // fptosi(sitofp(X)) --> X
8623   // fptosi(uitofp(X)) --> X
8624   // This is safe if the intermediate type has enough bits in its mantissa to
8625   // accurately represent all values of X.  For example, do not do this with
8626   // i64->float->i64.  This is also safe for sitofp case, because any negative
8627   // 'X' value would cause an undefined result for the fptoui. 
8628   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8629       OpI->getOperand(0)->getType() == FI.getType() &&
8630       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8631                     OpI->getType()->getFPMantissaWidth())
8632     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8633   
8634   return commonCastTransforms(FI);
8635 }
8636
8637 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8638   return commonCastTransforms(CI);
8639 }
8640
8641 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8642   return commonCastTransforms(CI);
8643 }
8644
8645 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8646   // If the destination integer type is smaller than the intptr_t type for
8647   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8648   // trunc to be exposed to other transforms.  Don't do this for extending
8649   // ptrtoint's, because we don't know if the target sign or zero extends its
8650   // pointers.
8651   if (CI.getType()->getPrimitiveSizeInBits() < TD->getPointerSizeInBits()) {
8652     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8653                                                     TD->getIntPtrType(),
8654                                                     "tmp"), CI);
8655     return new TruncInst(P, CI.getType());
8656   }
8657   
8658   return commonPointerCastTransforms(CI);
8659 }
8660
8661 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8662   // If the source integer type is larger than the intptr_t type for
8663   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8664   // allows the trunc to be exposed to other transforms.  Don't do this for
8665   // extending inttoptr's, because we don't know if the target sign or zero
8666   // extends to pointers.
8667   if (CI.getOperand(0)->getType()->getPrimitiveSizeInBits() >
8668       TD->getPointerSizeInBits()) {
8669     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8670                                                  TD->getIntPtrType(),
8671                                                  "tmp"), CI);
8672     return new IntToPtrInst(P, CI.getType());
8673   }
8674   
8675   if (Instruction *I = commonCastTransforms(CI))
8676     return I;
8677   
8678   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8679   if (!DestPointee->isSized()) return 0;
8680
8681   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8682   ConstantInt *Cst;
8683   Value *X;
8684   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8685                                     m_ConstantInt(Cst)))) {
8686     // If the source and destination operands have the same type, see if this
8687     // is a single-index GEP.
8688     if (X->getType() == CI.getType()) {
8689       // Get the size of the pointee type.
8690       uint64_t Size = TD->getTypePaddedSize(DestPointee);
8691
8692       // Convert the constant to intptr type.
8693       APInt Offset = Cst->getValue();
8694       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8695
8696       // If Offset is evenly divisible by Size, we can do this xform.
8697       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8698         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8699         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8700       }
8701     }
8702     // TODO: Could handle other cases, e.g. where add is indexing into field of
8703     // struct etc.
8704   } else if (CI.getOperand(0)->hasOneUse() &&
8705              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8706     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8707     // "inttoptr+GEP" instead of "add+intptr".
8708     
8709     // Get the size of the pointee type.
8710     uint64_t Size = TD->getTypePaddedSize(DestPointee);
8711     
8712     // Convert the constant to intptr type.
8713     APInt Offset = Cst->getValue();
8714     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8715     
8716     // If Offset is evenly divisible by Size, we can do this xform.
8717     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8718       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8719       
8720       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8721                                                             "tmp"), CI);
8722       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8723     }
8724   }
8725   return 0;
8726 }
8727
8728 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8729   // If the operands are integer typed then apply the integer transforms,
8730   // otherwise just apply the common ones.
8731   Value *Src = CI.getOperand(0);
8732   const Type *SrcTy = Src->getType();
8733   const Type *DestTy = CI.getType();
8734
8735   if (SrcTy->isInteger() && DestTy->isInteger()) {
8736     if (Instruction *Result = commonIntCastTransforms(CI))
8737       return Result;
8738   } else if (isa<PointerType>(SrcTy)) {
8739     if (Instruction *I = commonPointerCastTransforms(CI))
8740       return I;
8741   } else {
8742     if (Instruction *Result = commonCastTransforms(CI))
8743       return Result;
8744   }
8745
8746
8747   // Get rid of casts from one type to the same type. These are useless and can
8748   // be replaced by the operand.
8749   if (DestTy == Src->getType())
8750     return ReplaceInstUsesWith(CI, Src);
8751
8752   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8753     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8754     const Type *DstElTy = DstPTy->getElementType();
8755     const Type *SrcElTy = SrcPTy->getElementType();
8756     
8757     // If the address spaces don't match, don't eliminate the bitcast, which is
8758     // required for changing types.
8759     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8760       return 0;
8761     
8762     // If we are casting a malloc or alloca to a pointer to a type of the same
8763     // size, rewrite the allocation instruction to allocate the "right" type.
8764     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8765       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8766         return V;
8767     
8768     // If the source and destination are pointers, and this cast is equivalent
8769     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8770     // This can enhance SROA and other transforms that want type-safe pointers.
8771     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8772     unsigned NumZeros = 0;
8773     while (SrcElTy != DstElTy && 
8774            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8775            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8776       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8777       ++NumZeros;
8778     }
8779
8780     // If we found a path from the src to dest, create the getelementptr now.
8781     if (SrcElTy == DstElTy) {
8782       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8783       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8784                                        ((Instruction*) NULL));
8785     }
8786   }
8787
8788   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8789     if (SVI->hasOneUse()) {
8790       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8791       // a bitconvert to a vector with the same # elts.
8792       if (isa<VectorType>(DestTy) && 
8793           cast<VectorType>(DestTy)->getNumElements() ==
8794                 SVI->getType()->getNumElements() &&
8795           SVI->getType()->getNumElements() ==
8796             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8797         CastInst *Tmp;
8798         // If either of the operands is a cast from CI.getType(), then
8799         // evaluating the shuffle in the casted destination's type will allow
8800         // us to eliminate at least one cast.
8801         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8802              Tmp->getOperand(0)->getType() == DestTy) ||
8803             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8804              Tmp->getOperand(0)->getType() == DestTy)) {
8805           Value *LHS = InsertCastBefore(Instruction::BitCast,
8806                                         SVI->getOperand(0), DestTy, CI);
8807           Value *RHS = InsertCastBefore(Instruction::BitCast,
8808                                         SVI->getOperand(1), DestTy, CI);
8809           // Return a new shuffle vector.  Use the same element ID's, as we
8810           // know the vector types match #elts.
8811           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8812         }
8813       }
8814     }
8815   }
8816   return 0;
8817 }
8818
8819 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8820 ///   %C = or %A, %B
8821 ///   %D = select %cond, %C, %A
8822 /// into:
8823 ///   %C = select %cond, %B, 0
8824 ///   %D = or %A, %C
8825 ///
8826 /// Assuming that the specified instruction is an operand to the select, return
8827 /// a bitmask indicating which operands of this instruction are foldable if they
8828 /// equal the other incoming value of the select.
8829 ///
8830 static unsigned GetSelectFoldableOperands(Instruction *I) {
8831   switch (I->getOpcode()) {
8832   case Instruction::Add:
8833   case Instruction::Mul:
8834   case Instruction::And:
8835   case Instruction::Or:
8836   case Instruction::Xor:
8837     return 3;              // Can fold through either operand.
8838   case Instruction::Sub:   // Can only fold on the amount subtracted.
8839   case Instruction::Shl:   // Can only fold on the shift amount.
8840   case Instruction::LShr:
8841   case Instruction::AShr:
8842     return 1;
8843   default:
8844     return 0;              // Cannot fold
8845   }
8846 }
8847
8848 /// GetSelectFoldableConstant - For the same transformation as the previous
8849 /// function, return the identity constant that goes into the select.
8850 static Constant *GetSelectFoldableConstant(Instruction *I) {
8851   switch (I->getOpcode()) {
8852   default: assert(0 && "This cannot happen!"); abort();
8853   case Instruction::Add:
8854   case Instruction::Sub:
8855   case Instruction::Or:
8856   case Instruction::Xor:
8857   case Instruction::Shl:
8858   case Instruction::LShr:
8859   case Instruction::AShr:
8860     return Constant::getNullValue(I->getType());
8861   case Instruction::And:
8862     return Constant::getAllOnesValue(I->getType());
8863   case Instruction::Mul:
8864     return ConstantInt::get(I->getType(), 1);
8865   }
8866 }
8867
8868 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8869 /// have the same opcode and only one use each.  Try to simplify this.
8870 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8871                                           Instruction *FI) {
8872   if (TI->getNumOperands() == 1) {
8873     // If this is a non-volatile load or a cast from the same type,
8874     // merge.
8875     if (TI->isCast()) {
8876       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8877         return 0;
8878     } else {
8879       return 0;  // unknown unary op.
8880     }
8881
8882     // Fold this by inserting a select from the input values.
8883     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8884                                            FI->getOperand(0), SI.getName()+".v");
8885     InsertNewInstBefore(NewSI, SI);
8886     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8887                             TI->getType());
8888   }
8889
8890   // Only handle binary operators here.
8891   if (!isa<BinaryOperator>(TI))
8892     return 0;
8893
8894   // Figure out if the operations have any operands in common.
8895   Value *MatchOp, *OtherOpT, *OtherOpF;
8896   bool MatchIsOpZero;
8897   if (TI->getOperand(0) == FI->getOperand(0)) {
8898     MatchOp  = TI->getOperand(0);
8899     OtherOpT = TI->getOperand(1);
8900     OtherOpF = FI->getOperand(1);
8901     MatchIsOpZero = true;
8902   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8903     MatchOp  = TI->getOperand(1);
8904     OtherOpT = TI->getOperand(0);
8905     OtherOpF = FI->getOperand(0);
8906     MatchIsOpZero = false;
8907   } else if (!TI->isCommutative()) {
8908     return 0;
8909   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8910     MatchOp  = TI->getOperand(0);
8911     OtherOpT = TI->getOperand(1);
8912     OtherOpF = FI->getOperand(0);
8913     MatchIsOpZero = true;
8914   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8915     MatchOp  = TI->getOperand(1);
8916     OtherOpT = TI->getOperand(0);
8917     OtherOpF = FI->getOperand(1);
8918     MatchIsOpZero = true;
8919   } else {
8920     return 0;
8921   }
8922
8923   // If we reach here, they do have operations in common.
8924   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8925                                          OtherOpF, SI.getName()+".v");
8926   InsertNewInstBefore(NewSI, SI);
8927
8928   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8929     if (MatchIsOpZero)
8930       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8931     else
8932       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8933   }
8934   assert(0 && "Shouldn't get here");
8935   return 0;
8936 }
8937
8938 static bool isSelect01(Constant *C1, Constant *C2) {
8939   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
8940   if (!C1I)
8941     return false;
8942   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
8943   if (!C2I)
8944     return false;
8945   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
8946 }
8947
8948 /// FoldSelectIntoOp - Try fold the select into one of the operands to
8949 /// facilitate further optimization.
8950 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
8951                                             Value *FalseVal) {
8952   // See the comment above GetSelectFoldableOperands for a description of the
8953   // transformation we are doing here.
8954   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
8955     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8956         !isa<Constant>(FalseVal)) {
8957       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8958         unsigned OpToFold = 0;
8959         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8960           OpToFold = 1;
8961         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8962           OpToFold = 2;
8963         }
8964
8965         if (OpToFold) {
8966           Constant *C = GetSelectFoldableConstant(TVI);
8967           Value *OOp = TVI->getOperand(2-OpToFold);
8968           // Avoid creating select between 2 constants unless it's selecting
8969           // between 0 and 1.
8970           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
8971             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
8972             InsertNewInstBefore(NewSel, SI);
8973             NewSel->takeName(TVI);
8974             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8975               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8976             assert(0 && "Unknown instruction!!");
8977           }
8978         }
8979       }
8980     }
8981   }
8982
8983   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
8984     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8985         !isa<Constant>(TrueVal)) {
8986       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8987         unsigned OpToFold = 0;
8988         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8989           OpToFold = 1;
8990         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8991           OpToFold = 2;
8992         }
8993
8994         if (OpToFold) {
8995           Constant *C = GetSelectFoldableConstant(FVI);
8996           Value *OOp = FVI->getOperand(2-OpToFold);
8997           // Avoid creating select between 2 constants unless it's selecting
8998           // between 0 and 1.
8999           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9000             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9001             InsertNewInstBefore(NewSel, SI);
9002             NewSel->takeName(FVI);
9003             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9004               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9005             assert(0 && "Unknown instruction!!");
9006           }
9007         }
9008       }
9009     }
9010   }
9011
9012   return 0;
9013 }
9014
9015 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9016 /// ICmpInst as its first operand.
9017 ///
9018 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9019                                                    ICmpInst *ICI) {
9020   bool Changed = false;
9021   ICmpInst::Predicate Pred = ICI->getPredicate();
9022   Value *CmpLHS = ICI->getOperand(0);
9023   Value *CmpRHS = ICI->getOperand(1);
9024   Value *TrueVal = SI.getTrueValue();
9025   Value *FalseVal = SI.getFalseValue();
9026
9027   // Check cases where the comparison is with a constant that
9028   // can be adjusted to fit the min/max idiom. We may edit ICI in
9029   // place here, so make sure the select is the only user.
9030   if (ICI->hasOneUse())
9031     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9032       switch (Pred) {
9033       default: break;
9034       case ICmpInst::ICMP_ULT:
9035       case ICmpInst::ICMP_SLT: {
9036         // X < MIN ? T : F  -->  F
9037         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9038           return ReplaceInstUsesWith(SI, FalseVal);
9039         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9040         Constant *AdjustedRHS = SubOne(CI);
9041         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9042             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9043           Pred = ICmpInst::getSwappedPredicate(Pred);
9044           CmpRHS = AdjustedRHS;
9045           std::swap(FalseVal, TrueVal);
9046           ICI->setPredicate(Pred);
9047           ICI->setOperand(1, CmpRHS);
9048           SI.setOperand(1, TrueVal);
9049           SI.setOperand(2, FalseVal);
9050           Changed = true;
9051         }
9052         break;
9053       }
9054       case ICmpInst::ICMP_UGT:
9055       case ICmpInst::ICMP_SGT: {
9056         // X > MAX ? T : F  -->  F
9057         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9058           return ReplaceInstUsesWith(SI, FalseVal);
9059         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9060         Constant *AdjustedRHS = AddOne(CI);
9061         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9062             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9063           Pred = ICmpInst::getSwappedPredicate(Pred);
9064           CmpRHS = AdjustedRHS;
9065           std::swap(FalseVal, TrueVal);
9066           ICI->setPredicate(Pred);
9067           ICI->setOperand(1, CmpRHS);
9068           SI.setOperand(1, TrueVal);
9069           SI.setOperand(2, FalseVal);
9070           Changed = true;
9071         }
9072         break;
9073       }
9074       }
9075
9076       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9077       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9078       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9079       if (match(TrueVal, m_ConstantInt<-1>()) &&
9080           match(FalseVal, m_ConstantInt<0>()))
9081         Pred = ICI->getPredicate();
9082       else if (match(TrueVal, m_ConstantInt<0>()) &&
9083                match(FalseVal, m_ConstantInt<-1>()))
9084         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9085       
9086       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9087         // If we are just checking for a icmp eq of a single bit and zext'ing it
9088         // to an integer, then shift the bit to the appropriate place and then
9089         // cast to integer to avoid the comparison.
9090         const APInt &Op1CV = CI->getValue();
9091     
9092         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9093         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9094         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9095             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9096           Value *In = ICI->getOperand(0);
9097           Value *Sh = ConstantInt::get(In->getType(),
9098                                        In->getType()->getPrimitiveSizeInBits()-1);
9099           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9100                                                           In->getName()+".lobit"),
9101                                    *ICI);
9102           if (In->getType() != SI.getType())
9103             In = CastInst::CreateIntegerCast(In, SI.getType(),
9104                                              true/*SExt*/, "tmp", ICI);
9105     
9106           if (Pred == ICmpInst::ICMP_SGT)
9107             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9108                                        In->getName()+".not"), *ICI);
9109     
9110           return ReplaceInstUsesWith(SI, In);
9111         }
9112       }
9113     }
9114
9115   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9116     // Transform (X == Y) ? X : Y  -> Y
9117     if (Pred == ICmpInst::ICMP_EQ)
9118       return ReplaceInstUsesWith(SI, FalseVal);
9119     // Transform (X != Y) ? X : Y  -> X
9120     if (Pred == ICmpInst::ICMP_NE)
9121       return ReplaceInstUsesWith(SI, TrueVal);
9122     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9123
9124   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9125     // Transform (X == Y) ? Y : X  -> X
9126     if (Pred == ICmpInst::ICMP_EQ)
9127       return ReplaceInstUsesWith(SI, FalseVal);
9128     // Transform (X != Y) ? Y : X  -> Y
9129     if (Pred == ICmpInst::ICMP_NE)
9130       return ReplaceInstUsesWith(SI, TrueVal);
9131     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9132   }
9133
9134   /// NOTE: if we wanted to, this is where to detect integer ABS
9135
9136   return Changed ? &SI : 0;
9137 }
9138
9139 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9140   Value *CondVal = SI.getCondition();
9141   Value *TrueVal = SI.getTrueValue();
9142   Value *FalseVal = SI.getFalseValue();
9143
9144   // select true, X, Y  -> X
9145   // select false, X, Y -> Y
9146   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9147     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9148
9149   // select C, X, X -> X
9150   if (TrueVal == FalseVal)
9151     return ReplaceInstUsesWith(SI, TrueVal);
9152
9153   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9154     return ReplaceInstUsesWith(SI, FalseVal);
9155   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9156     return ReplaceInstUsesWith(SI, TrueVal);
9157   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9158     if (isa<Constant>(TrueVal))
9159       return ReplaceInstUsesWith(SI, TrueVal);
9160     else
9161       return ReplaceInstUsesWith(SI, FalseVal);
9162   }
9163
9164   if (SI.getType() == Type::Int1Ty) {
9165     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9166       if (C->getZExtValue()) {
9167         // Change: A = select B, true, C --> A = or B, C
9168         return BinaryOperator::CreateOr(CondVal, FalseVal);
9169       } else {
9170         // Change: A = select B, false, C --> A = and !B, C
9171         Value *NotCond =
9172           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9173                                              "not."+CondVal->getName()), SI);
9174         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9175       }
9176     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9177       if (C->getZExtValue() == false) {
9178         // Change: A = select B, C, false --> A = and B, C
9179         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9180       } else {
9181         // Change: A = select B, C, true --> A = or !B, C
9182         Value *NotCond =
9183           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9184                                              "not."+CondVal->getName()), SI);
9185         return BinaryOperator::CreateOr(NotCond, TrueVal);
9186       }
9187     }
9188     
9189     // select a, b, a  -> a&b
9190     // select a, a, b  -> a|b
9191     if (CondVal == TrueVal)
9192       return BinaryOperator::CreateOr(CondVal, FalseVal);
9193     else if (CondVal == FalseVal)
9194       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9195   }
9196
9197   // Selecting between two integer constants?
9198   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9199     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9200       // select C, 1, 0 -> zext C to int
9201       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9202         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9203       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9204         // select C, 0, 1 -> zext !C to int
9205         Value *NotCond =
9206           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9207                                                "not."+CondVal->getName()), SI);
9208         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9209       }
9210
9211       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9212
9213         // (x <s 0) ? -1 : 0 -> ashr x, 31
9214         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9215           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9216             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9217               // The comparison constant and the result are not neccessarily the
9218               // same width. Make an all-ones value by inserting a AShr.
9219               Value *X = IC->getOperand(0);
9220               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
9221               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
9222               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
9223                                                         ShAmt, "ones");
9224               InsertNewInstBefore(SRA, SI);
9225
9226               // Then cast to the appropriate width.
9227               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
9228             }
9229           }
9230
9231
9232         // If one of the constants is zero (we know they can't both be) and we
9233         // have an icmp instruction with zero, and we have an 'and' with the
9234         // non-constant value, eliminate this whole mess.  This corresponds to
9235         // cases like this: ((X & 27) ? 27 : 0)
9236         if (TrueValC->isZero() || FalseValC->isZero())
9237           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9238               cast<Constant>(IC->getOperand(1))->isNullValue())
9239             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9240               if (ICA->getOpcode() == Instruction::And &&
9241                   isa<ConstantInt>(ICA->getOperand(1)) &&
9242                   (ICA->getOperand(1) == TrueValC ||
9243                    ICA->getOperand(1) == FalseValC) &&
9244                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9245                 // Okay, now we know that everything is set up, we just don't
9246                 // know whether we have a icmp_ne or icmp_eq and whether the 
9247                 // true or false val is the zero.
9248                 bool ShouldNotVal = !TrueValC->isZero();
9249                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9250                 Value *V = ICA;
9251                 if (ShouldNotVal)
9252                   V = InsertNewInstBefore(BinaryOperator::Create(
9253                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9254                 return ReplaceInstUsesWith(SI, V);
9255               }
9256       }
9257     }
9258
9259   // See if we are selecting two values based on a comparison of the two values.
9260   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9261     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9262       // Transform (X == Y) ? X : Y  -> Y
9263       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9264         // This is not safe in general for floating point:  
9265         // consider X== -0, Y== +0.
9266         // It becomes safe if either operand is a nonzero constant.
9267         ConstantFP *CFPt, *CFPf;
9268         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9269               !CFPt->getValueAPF().isZero()) ||
9270             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9271              !CFPf->getValueAPF().isZero()))
9272         return ReplaceInstUsesWith(SI, FalseVal);
9273       }
9274       // Transform (X != Y) ? X : Y  -> X
9275       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9276         return ReplaceInstUsesWith(SI, TrueVal);
9277       // NOTE: if we wanted to, this is where to detect MIN/MAX
9278
9279     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9280       // Transform (X == Y) ? Y : X  -> X
9281       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9282         // This is not safe in general for floating point:  
9283         // consider X== -0, Y== +0.
9284         // It becomes safe if either operand is a nonzero constant.
9285         ConstantFP *CFPt, *CFPf;
9286         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9287               !CFPt->getValueAPF().isZero()) ||
9288             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9289              !CFPf->getValueAPF().isZero()))
9290           return ReplaceInstUsesWith(SI, FalseVal);
9291       }
9292       // Transform (X != Y) ? Y : X  -> Y
9293       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9294         return ReplaceInstUsesWith(SI, TrueVal);
9295       // NOTE: if we wanted to, this is where to detect MIN/MAX
9296     }
9297     // NOTE: if we wanted to, this is where to detect ABS
9298   }
9299
9300   // See if we are selecting two values based on a comparison of the two values.
9301   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9302     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9303       return Result;
9304
9305   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9306     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9307       if (TI->hasOneUse() && FI->hasOneUse()) {
9308         Instruction *AddOp = 0, *SubOp = 0;
9309
9310         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9311         if (TI->getOpcode() == FI->getOpcode())
9312           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9313             return IV;
9314
9315         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9316         // even legal for FP.
9317         if (TI->getOpcode() == Instruction::Sub &&
9318             FI->getOpcode() == Instruction::Add) {
9319           AddOp = FI; SubOp = TI;
9320         } else if (FI->getOpcode() == Instruction::Sub &&
9321                    TI->getOpcode() == Instruction::Add) {
9322           AddOp = TI; SubOp = FI;
9323         }
9324
9325         if (AddOp) {
9326           Value *OtherAddOp = 0;
9327           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9328             OtherAddOp = AddOp->getOperand(1);
9329           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9330             OtherAddOp = AddOp->getOperand(0);
9331           }
9332
9333           if (OtherAddOp) {
9334             // So at this point we know we have (Y -> OtherAddOp):
9335             //        select C, (add X, Y), (sub X, Z)
9336             Value *NegVal;  // Compute -Z
9337             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9338               NegVal = ConstantExpr::getNeg(C);
9339             } else {
9340               NegVal = InsertNewInstBefore(
9341                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9342             }
9343
9344             Value *NewTrueOp = OtherAddOp;
9345             Value *NewFalseOp = NegVal;
9346             if (AddOp != TI)
9347               std::swap(NewTrueOp, NewFalseOp);
9348             Instruction *NewSel =
9349               SelectInst::Create(CondVal, NewTrueOp,
9350                                  NewFalseOp, SI.getName() + ".p");
9351
9352             NewSel = InsertNewInstBefore(NewSel, SI);
9353             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9354           }
9355         }
9356       }
9357
9358   // See if we can fold the select into one of our operands.
9359   if (SI.getType()->isInteger()) {
9360     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9361     if (FoldI)
9362       return FoldI;
9363   }
9364
9365   if (BinaryOperator::isNot(CondVal)) {
9366     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9367     SI.setOperand(1, FalseVal);
9368     SI.setOperand(2, TrueVal);
9369     return &SI;
9370   }
9371
9372   return 0;
9373 }
9374
9375 /// EnforceKnownAlignment - If the specified pointer points to an object that
9376 /// we control, modify the object's alignment to PrefAlign. This isn't
9377 /// often possible though. If alignment is important, a more reliable approach
9378 /// is to simply align all global variables and allocation instructions to
9379 /// their preferred alignment from the beginning.
9380 ///
9381 static unsigned EnforceKnownAlignment(Value *V,
9382                                       unsigned Align, unsigned PrefAlign) {
9383
9384   User *U = dyn_cast<User>(V);
9385   if (!U) return Align;
9386
9387   switch (getOpcode(U)) {
9388   default: break;
9389   case Instruction::BitCast:
9390     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9391   case Instruction::GetElementPtr: {
9392     // If all indexes are zero, it is just the alignment of the base pointer.
9393     bool AllZeroOperands = true;
9394     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9395       if (!isa<Constant>(*i) ||
9396           !cast<Constant>(*i)->isNullValue()) {
9397         AllZeroOperands = false;
9398         break;
9399       }
9400
9401     if (AllZeroOperands) {
9402       // Treat this like a bitcast.
9403       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9404     }
9405     break;
9406   }
9407   }
9408
9409   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9410     // If there is a large requested alignment and we can, bump up the alignment
9411     // of the global.
9412     if (!GV->isDeclaration()) {
9413       if (GV->getAlignment() >= PrefAlign)
9414         Align = GV->getAlignment();
9415       else {
9416         GV->setAlignment(PrefAlign);
9417         Align = PrefAlign;
9418       }
9419     }
9420   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9421     // If there is a requested alignment and if this is an alloca, round up.  We
9422     // don't do this for malloc, because some systems can't respect the request.
9423     if (isa<AllocaInst>(AI)) {
9424       if (AI->getAlignment() >= PrefAlign)
9425         Align = AI->getAlignment();
9426       else {
9427         AI->setAlignment(PrefAlign);
9428         Align = PrefAlign;
9429       }
9430     }
9431   }
9432
9433   return Align;
9434 }
9435
9436 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9437 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9438 /// and it is more than the alignment of the ultimate object, see if we can
9439 /// increase the alignment of the ultimate object, making this check succeed.
9440 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9441                                                   unsigned PrefAlign) {
9442   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9443                       sizeof(PrefAlign) * CHAR_BIT;
9444   APInt Mask = APInt::getAllOnesValue(BitWidth);
9445   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9446   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9447   unsigned TrailZ = KnownZero.countTrailingOnes();
9448   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9449
9450   if (PrefAlign > Align)
9451     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9452   
9453     // We don't need to make any adjustment.
9454   return Align;
9455 }
9456
9457 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9458   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9459   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9460   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9461   unsigned CopyAlign = MI->getAlignment();
9462
9463   if (CopyAlign < MinAlign) {
9464     MI->setAlignment(MinAlign);
9465     return MI;
9466   }
9467   
9468   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9469   // load/store.
9470   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9471   if (MemOpLength == 0) return 0;
9472   
9473   // Source and destination pointer types are always "i8*" for intrinsic.  See
9474   // if the size is something we can handle with a single primitive load/store.
9475   // A single load+store correctly handles overlapping memory in the memmove
9476   // case.
9477   unsigned Size = MemOpLength->getZExtValue();
9478   if (Size == 0) return MI;  // Delete this mem transfer.
9479   
9480   if (Size > 8 || (Size&(Size-1)))
9481     return 0;  // If not 1/2/4/8 bytes, exit.
9482   
9483   // Use an integer load+store unless we can find something better.
9484   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9485   
9486   // Memcpy forces the use of i8* for the source and destination.  That means
9487   // that if you're using memcpy to move one double around, you'll get a cast
9488   // from double* to i8*.  We'd much rather use a double load+store rather than
9489   // an i64 load+store, here because this improves the odds that the source or
9490   // dest address will be promotable.  See if we can find a better type than the
9491   // integer datatype.
9492   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9493     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9494     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9495       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9496       // down through these levels if so.
9497       while (!SrcETy->isSingleValueType()) {
9498         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9499           if (STy->getNumElements() == 1)
9500             SrcETy = STy->getElementType(0);
9501           else
9502             break;
9503         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9504           if (ATy->getNumElements() == 1)
9505             SrcETy = ATy->getElementType();
9506           else
9507             break;
9508         } else
9509           break;
9510       }
9511       
9512       if (SrcETy->isSingleValueType())
9513         NewPtrTy = PointerType::getUnqual(SrcETy);
9514     }
9515   }
9516   
9517   
9518   // If the memcpy/memmove provides better alignment info than we can
9519   // infer, use it.
9520   SrcAlign = std::max(SrcAlign, CopyAlign);
9521   DstAlign = std::max(DstAlign, CopyAlign);
9522   
9523   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9524   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9525   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9526   InsertNewInstBefore(L, *MI);
9527   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9528
9529   // Set the size of the copy to 0, it will be deleted on the next iteration.
9530   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9531   return MI;
9532 }
9533
9534 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9535   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9536   if (MI->getAlignment() < Alignment) {
9537     MI->setAlignment(Alignment);
9538     return MI;
9539   }
9540   
9541   // Extract the length and alignment and fill if they are constant.
9542   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9543   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9544   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9545     return 0;
9546   uint64_t Len = LenC->getZExtValue();
9547   Alignment = MI->getAlignment();
9548   
9549   // If the length is zero, this is a no-op
9550   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9551   
9552   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9553   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9554     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9555     
9556     Value *Dest = MI->getDest();
9557     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9558
9559     // Alignment 0 is identity for alignment 1 for memset, but not store.
9560     if (Alignment == 0) Alignment = 1;
9561     
9562     // Extract the fill value and store.
9563     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9564     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9565                                       Alignment), *MI);
9566     
9567     // Set the size of the copy to 0, it will be deleted on the next iteration.
9568     MI->setLength(Constant::getNullValue(LenC->getType()));
9569     return MI;
9570   }
9571
9572   return 0;
9573 }
9574
9575
9576 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9577 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9578 /// the heavy lifting.
9579 ///
9580 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9581   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9582   if (!II) return visitCallSite(&CI);
9583   
9584   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9585   // visitCallSite.
9586   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9587     bool Changed = false;
9588
9589     // memmove/cpy/set of zero bytes is a noop.
9590     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9591       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9592
9593       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9594         if (CI->getZExtValue() == 1) {
9595           // Replace the instruction with just byte operations.  We would
9596           // transform other cases to loads/stores, but we don't know if
9597           // alignment is sufficient.
9598         }
9599     }
9600
9601     // If we have a memmove and the source operation is a constant global,
9602     // then the source and dest pointers can't alias, so we can change this
9603     // into a call to memcpy.
9604     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9605       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9606         if (GVSrc->isConstant()) {
9607           Module *M = CI.getParent()->getParent()->getParent();
9608           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9609           const Type *Tys[1];
9610           Tys[0] = CI.getOperand(3)->getType();
9611           CI.setOperand(0, 
9612                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9613           Changed = true;
9614         }
9615
9616       // memmove(x,x,size) -> noop.
9617       if (MMI->getSource() == MMI->getDest())
9618         return EraseInstFromFunction(CI);
9619     }
9620
9621     // If we can determine a pointer alignment that is bigger than currently
9622     // set, update the alignment.
9623     if (isa<MemTransferInst>(MI)) {
9624       if (Instruction *I = SimplifyMemTransfer(MI))
9625         return I;
9626     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9627       if (Instruction *I = SimplifyMemSet(MSI))
9628         return I;
9629     }
9630           
9631     if (Changed) return II;
9632   }
9633   
9634   switch (II->getIntrinsicID()) {
9635   default: break;
9636   case Intrinsic::bswap:
9637     // bswap(bswap(x)) -> x
9638     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9639       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9640         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9641     break;
9642   case Intrinsic::ppc_altivec_lvx:
9643   case Intrinsic::ppc_altivec_lvxl:
9644   case Intrinsic::x86_sse_loadu_ps:
9645   case Intrinsic::x86_sse2_loadu_pd:
9646   case Intrinsic::x86_sse2_loadu_dq:
9647     // Turn PPC lvx     -> load if the pointer is known aligned.
9648     // Turn X86 loadups -> load if the pointer is known aligned.
9649     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9650       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9651                                        PointerType::getUnqual(II->getType()),
9652                                        CI);
9653       return new LoadInst(Ptr);
9654     }
9655     break;
9656   case Intrinsic::ppc_altivec_stvx:
9657   case Intrinsic::ppc_altivec_stvxl:
9658     // Turn stvx -> store if the pointer is known aligned.
9659     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9660       const Type *OpPtrTy = 
9661         PointerType::getUnqual(II->getOperand(1)->getType());
9662       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9663       return new StoreInst(II->getOperand(1), Ptr);
9664     }
9665     break;
9666   case Intrinsic::x86_sse_storeu_ps:
9667   case Intrinsic::x86_sse2_storeu_pd:
9668   case Intrinsic::x86_sse2_storeu_dq:
9669     // Turn X86 storeu -> store if the pointer is known aligned.
9670     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9671       const Type *OpPtrTy = 
9672         PointerType::getUnqual(II->getOperand(2)->getType());
9673       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9674       return new StoreInst(II->getOperand(2), Ptr);
9675     }
9676     break;
9677     
9678   case Intrinsic::x86_sse_cvttss2si: {
9679     // These intrinsics only demands the 0th element of its input vector.  If
9680     // we can simplify the input based on that, do so now.
9681     unsigned VWidth =
9682       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9683     APInt DemandedElts(VWidth, 1);
9684     APInt UndefElts(VWidth, 0);
9685     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9686                                               UndefElts)) {
9687       II->setOperand(1, V);
9688       return II;
9689     }
9690     break;
9691   }
9692     
9693   case Intrinsic::ppc_altivec_vperm:
9694     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9695     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9696       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9697       
9698       // Check that all of the elements are integer constants or undefs.
9699       bool AllEltsOk = true;
9700       for (unsigned i = 0; i != 16; ++i) {
9701         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9702             !isa<UndefValue>(Mask->getOperand(i))) {
9703           AllEltsOk = false;
9704           break;
9705         }
9706       }
9707       
9708       if (AllEltsOk) {
9709         // Cast the input vectors to byte vectors.
9710         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9711         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9712         Value *Result = UndefValue::get(Op0->getType());
9713         
9714         // Only extract each element once.
9715         Value *ExtractedElts[32];
9716         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9717         
9718         for (unsigned i = 0; i != 16; ++i) {
9719           if (isa<UndefValue>(Mask->getOperand(i)))
9720             continue;
9721           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9722           Idx &= 31;  // Match the hardware behavior.
9723           
9724           if (ExtractedElts[Idx] == 0) {
9725             Instruction *Elt = 
9726               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9727             InsertNewInstBefore(Elt, CI);
9728             ExtractedElts[Idx] = Elt;
9729           }
9730         
9731           // Insert this value into the result vector.
9732           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9733                                              i, "tmp");
9734           InsertNewInstBefore(cast<Instruction>(Result), CI);
9735         }
9736         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9737       }
9738     }
9739     break;
9740
9741   case Intrinsic::stackrestore: {
9742     // If the save is right next to the restore, remove the restore.  This can
9743     // happen when variable allocas are DCE'd.
9744     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9745       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9746         BasicBlock::iterator BI = SS;
9747         if (&*++BI == II)
9748           return EraseInstFromFunction(CI);
9749       }
9750     }
9751     
9752     // Scan down this block to see if there is another stack restore in the
9753     // same block without an intervening call/alloca.
9754     BasicBlock::iterator BI = II;
9755     TerminatorInst *TI = II->getParent()->getTerminator();
9756     bool CannotRemove = false;
9757     for (++BI; &*BI != TI; ++BI) {
9758       if (isa<AllocaInst>(BI)) {
9759         CannotRemove = true;
9760         break;
9761       }
9762       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9763         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9764           // If there is a stackrestore below this one, remove this one.
9765           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9766             return EraseInstFromFunction(CI);
9767           // Otherwise, ignore the intrinsic.
9768         } else {
9769           // If we found a non-intrinsic call, we can't remove the stack
9770           // restore.
9771           CannotRemove = true;
9772           break;
9773         }
9774       }
9775     }
9776     
9777     // If the stack restore is in a return/unwind block and if there are no
9778     // allocas or calls between the restore and the return, nuke the restore.
9779     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9780       return EraseInstFromFunction(CI);
9781     break;
9782   }
9783   }
9784
9785   return visitCallSite(II);
9786 }
9787
9788 // InvokeInst simplification
9789 //
9790 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9791   return visitCallSite(&II);
9792 }
9793
9794 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9795 /// passed through the varargs area, we can eliminate the use of the cast.
9796 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9797                                          const CastInst * const CI,
9798                                          const TargetData * const TD,
9799                                          const int ix) {
9800   if (!CI->isLosslessCast())
9801     return false;
9802
9803   // The size of ByVal arguments is derived from the type, so we
9804   // can't change to a type with a different size.  If the size were
9805   // passed explicitly we could avoid this check.
9806   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9807     return true;
9808
9809   const Type* SrcTy = 
9810             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9811   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9812   if (!SrcTy->isSized() || !DstTy->isSized())
9813     return false;
9814   if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
9815     return false;
9816   return true;
9817 }
9818
9819 // visitCallSite - Improvements for call and invoke instructions.
9820 //
9821 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9822   bool Changed = false;
9823
9824   // If the callee is a constexpr cast of a function, attempt to move the cast
9825   // to the arguments of the call/invoke.
9826   if (transformConstExprCastCall(CS)) return 0;
9827
9828   Value *Callee = CS.getCalledValue();
9829
9830   if (Function *CalleeF = dyn_cast<Function>(Callee))
9831     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9832       Instruction *OldCall = CS.getInstruction();
9833       // If the call and callee calling conventions don't match, this call must
9834       // be unreachable, as the call is undefined.
9835       new StoreInst(ConstantInt::getTrue(),
9836                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9837                                     OldCall);
9838       if (!OldCall->use_empty())
9839         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9840       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9841         return EraseInstFromFunction(*OldCall);
9842       return 0;
9843     }
9844
9845   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9846     // This instruction is not reachable, just remove it.  We insert a store to
9847     // undef so that we know that this code is not reachable, despite the fact
9848     // that we can't modify the CFG here.
9849     new StoreInst(ConstantInt::getTrue(),
9850                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9851                   CS.getInstruction());
9852
9853     if (!CS.getInstruction()->use_empty())
9854       CS.getInstruction()->
9855         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9856
9857     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9858       // Don't break the CFG, insert a dummy cond branch.
9859       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9860                          ConstantInt::getTrue(), II);
9861     }
9862     return EraseInstFromFunction(*CS.getInstruction());
9863   }
9864
9865   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9866     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9867       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9868         return transformCallThroughTrampoline(CS);
9869
9870   const PointerType *PTy = cast<PointerType>(Callee->getType());
9871   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9872   if (FTy->isVarArg()) {
9873     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9874     // See if we can optimize any arguments passed through the varargs area of
9875     // the call.
9876     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9877            E = CS.arg_end(); I != E; ++I, ++ix) {
9878       CastInst *CI = dyn_cast<CastInst>(*I);
9879       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9880         *I = CI->getOperand(0);
9881         Changed = true;
9882       }
9883     }
9884   }
9885
9886   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9887     // Inline asm calls cannot throw - mark them 'nounwind'.
9888     CS.setDoesNotThrow();
9889     Changed = true;
9890   }
9891
9892   return Changed ? CS.getInstruction() : 0;
9893 }
9894
9895 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9896 // attempt to move the cast to the arguments of the call/invoke.
9897 //
9898 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9899   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9900   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9901   if (CE->getOpcode() != Instruction::BitCast || 
9902       !isa<Function>(CE->getOperand(0)))
9903     return false;
9904   Function *Callee = cast<Function>(CE->getOperand(0));
9905   Instruction *Caller = CS.getInstruction();
9906   const AttrListPtr &CallerPAL = CS.getAttributes();
9907
9908   // Okay, this is a cast from a function to a different type.  Unless doing so
9909   // would cause a type conversion of one of our arguments, change this call to
9910   // be a direct call with arguments casted to the appropriate types.
9911   //
9912   const FunctionType *FT = Callee->getFunctionType();
9913   const Type *OldRetTy = Caller->getType();
9914   const Type *NewRetTy = FT->getReturnType();
9915
9916   if (isa<StructType>(NewRetTy))
9917     return false; // TODO: Handle multiple return values.
9918
9919   // Check to see if we are changing the return type...
9920   if (OldRetTy != NewRetTy) {
9921     if (Callee->isDeclaration() &&
9922         // Conversion is ok if changing from one pointer type to another or from
9923         // a pointer to an integer of the same size.
9924         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9925           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9926       return false;   // Cannot transform this return value.
9927
9928     if (!Caller->use_empty() &&
9929         // void -> non-void is handled specially
9930         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9931       return false;   // Cannot transform this return value.
9932
9933     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9934       Attributes RAttrs = CallerPAL.getRetAttributes();
9935       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9936         return false;   // Attribute not compatible with transformed value.
9937     }
9938
9939     // If the callsite is an invoke instruction, and the return value is used by
9940     // a PHI node in a successor, we cannot change the return type of the call
9941     // because there is no place to put the cast instruction (without breaking
9942     // the critical edge).  Bail out in this case.
9943     if (!Caller->use_empty())
9944       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9945         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9946              UI != E; ++UI)
9947           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9948             if (PN->getParent() == II->getNormalDest() ||
9949                 PN->getParent() == II->getUnwindDest())
9950               return false;
9951   }
9952
9953   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9954   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9955
9956   CallSite::arg_iterator AI = CS.arg_begin();
9957   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9958     const Type *ParamTy = FT->getParamType(i);
9959     const Type *ActTy = (*AI)->getType();
9960
9961     if (!CastInst::isCastable(ActTy, ParamTy))
9962       return false;   // Cannot transform this parameter value.
9963
9964     if (CallerPAL.getParamAttributes(i + 1) 
9965         & Attribute::typeIncompatible(ParamTy))
9966       return false;   // Attribute not compatible with transformed value.
9967
9968     // Converting from one pointer type to another or between a pointer and an
9969     // integer of the same size is safe even if we do not have a body.
9970     bool isConvertible = ActTy == ParamTy ||
9971       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9972        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9973     if (Callee->isDeclaration() && !isConvertible) return false;
9974   }
9975
9976   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9977       Callee->isDeclaration())
9978     return false;   // Do not delete arguments unless we have a function body.
9979
9980   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9981       !CallerPAL.isEmpty())
9982     // In this case we have more arguments than the new function type, but we
9983     // won't be dropping them.  Check that these extra arguments have attributes
9984     // that are compatible with being a vararg call argument.
9985     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9986       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9987         break;
9988       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9989       if (PAttrs & Attribute::VarArgsIncompatible)
9990         return false;
9991     }
9992
9993   // Okay, we decided that this is a safe thing to do: go ahead and start
9994   // inserting cast instructions as necessary...
9995   std::vector<Value*> Args;
9996   Args.reserve(NumActualArgs);
9997   SmallVector<AttributeWithIndex, 8> attrVec;
9998   attrVec.reserve(NumCommonArgs);
9999
10000   // Get any return attributes.
10001   Attributes RAttrs = CallerPAL.getRetAttributes();
10002
10003   // If the return value is not being used, the type may not be compatible
10004   // with the existing attributes.  Wipe out any problematic attributes.
10005   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10006
10007   // Add the new return attributes.
10008   if (RAttrs)
10009     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10010
10011   AI = CS.arg_begin();
10012   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10013     const Type *ParamTy = FT->getParamType(i);
10014     if ((*AI)->getType() == ParamTy) {
10015       Args.push_back(*AI);
10016     } else {
10017       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10018           false, ParamTy, false);
10019       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10020       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10021     }
10022
10023     // Add any parameter attributes.
10024     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10025       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10026   }
10027
10028   // If the function takes more arguments than the call was taking, add them
10029   // now...
10030   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10031     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10032
10033   // If we are removing arguments to the function, emit an obnoxious warning...
10034   if (FT->getNumParams() < NumActualArgs) {
10035     if (!FT->isVarArg()) {
10036       cerr << "WARNING: While resolving call to function '"
10037            << Callee->getName() << "' arguments were dropped!\n";
10038     } else {
10039       // Add all of the arguments in their promoted form to the arg list...
10040       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10041         const Type *PTy = getPromotedType((*AI)->getType());
10042         if (PTy != (*AI)->getType()) {
10043           // Must promote to pass through va_arg area!
10044           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10045                                                                 PTy, false);
10046           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10047           InsertNewInstBefore(Cast, *Caller);
10048           Args.push_back(Cast);
10049         } else {
10050           Args.push_back(*AI);
10051         }
10052
10053         // Add any parameter attributes.
10054         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10055           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10056       }
10057     }
10058   }
10059
10060   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10061     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10062
10063   if (NewRetTy == Type::VoidTy)
10064     Caller->setName("");   // Void type should not have a name.
10065
10066   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10067
10068   Instruction *NC;
10069   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10070     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10071                             Args.begin(), Args.end(),
10072                             Caller->getName(), Caller);
10073     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10074     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10075   } else {
10076     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10077                           Caller->getName(), Caller);
10078     CallInst *CI = cast<CallInst>(Caller);
10079     if (CI->isTailCall())
10080       cast<CallInst>(NC)->setTailCall();
10081     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10082     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10083   }
10084
10085   // Insert a cast of the return type as necessary.
10086   Value *NV = NC;
10087   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10088     if (NV->getType() != Type::VoidTy) {
10089       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10090                                                             OldRetTy, false);
10091       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10092
10093       // If this is an invoke instruction, we should insert it after the first
10094       // non-phi, instruction in the normal successor block.
10095       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10096         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10097         InsertNewInstBefore(NC, *I);
10098       } else {
10099         // Otherwise, it's a call, just insert cast right after the call instr
10100         InsertNewInstBefore(NC, *Caller);
10101       }
10102       AddUsersToWorkList(*Caller);
10103     } else {
10104       NV = UndefValue::get(Caller->getType());
10105     }
10106   }
10107
10108   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10109     Caller->replaceAllUsesWith(NV);
10110   Caller->eraseFromParent();
10111   RemoveFromWorkList(Caller);
10112   return true;
10113 }
10114
10115 // transformCallThroughTrampoline - Turn a call to a function created by the
10116 // init_trampoline intrinsic into a direct call to the underlying function.
10117 //
10118 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10119   Value *Callee = CS.getCalledValue();
10120   const PointerType *PTy = cast<PointerType>(Callee->getType());
10121   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10122   const AttrListPtr &Attrs = CS.getAttributes();
10123
10124   // If the call already has the 'nest' attribute somewhere then give up -
10125   // otherwise 'nest' would occur twice after splicing in the chain.
10126   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10127     return 0;
10128
10129   IntrinsicInst *Tramp =
10130     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10131
10132   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10133   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10134   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10135
10136   const AttrListPtr &NestAttrs = NestF->getAttributes();
10137   if (!NestAttrs.isEmpty()) {
10138     unsigned NestIdx = 1;
10139     const Type *NestTy = 0;
10140     Attributes NestAttr = Attribute::None;
10141
10142     // Look for a parameter marked with the 'nest' attribute.
10143     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10144          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10145       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10146         // Record the parameter type and any other attributes.
10147         NestTy = *I;
10148         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10149         break;
10150       }
10151
10152     if (NestTy) {
10153       Instruction *Caller = CS.getInstruction();
10154       std::vector<Value*> NewArgs;
10155       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10156
10157       SmallVector<AttributeWithIndex, 8> NewAttrs;
10158       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10159
10160       // Insert the nest argument into the call argument list, which may
10161       // mean appending it.  Likewise for attributes.
10162
10163       // Add any result attributes.
10164       if (Attributes Attr = Attrs.getRetAttributes())
10165         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10166
10167       {
10168         unsigned Idx = 1;
10169         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10170         do {
10171           if (Idx == NestIdx) {
10172             // Add the chain argument and attributes.
10173             Value *NestVal = Tramp->getOperand(3);
10174             if (NestVal->getType() != NestTy)
10175               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10176             NewArgs.push_back(NestVal);
10177             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10178           }
10179
10180           if (I == E)
10181             break;
10182
10183           // Add the original argument and attributes.
10184           NewArgs.push_back(*I);
10185           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10186             NewAttrs.push_back
10187               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10188
10189           ++Idx, ++I;
10190         } while (1);
10191       }
10192
10193       // Add any function attributes.
10194       if (Attributes Attr = Attrs.getFnAttributes())
10195         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10196
10197       // The trampoline may have been bitcast to a bogus type (FTy).
10198       // Handle this by synthesizing a new function type, equal to FTy
10199       // with the chain parameter inserted.
10200
10201       std::vector<const Type*> NewTypes;
10202       NewTypes.reserve(FTy->getNumParams()+1);
10203
10204       // Insert the chain's type into the list of parameter types, which may
10205       // mean appending it.
10206       {
10207         unsigned Idx = 1;
10208         FunctionType::param_iterator I = FTy->param_begin(),
10209           E = FTy->param_end();
10210
10211         do {
10212           if (Idx == NestIdx)
10213             // Add the chain's type.
10214             NewTypes.push_back(NestTy);
10215
10216           if (I == E)
10217             break;
10218
10219           // Add the original type.
10220           NewTypes.push_back(*I);
10221
10222           ++Idx, ++I;
10223         } while (1);
10224       }
10225
10226       // Replace the trampoline call with a direct call.  Let the generic
10227       // code sort out any function type mismatches.
10228       FunctionType *NewFTy =
10229         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
10230       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10231         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
10232       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10233
10234       Instruction *NewCaller;
10235       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10236         NewCaller = InvokeInst::Create(NewCallee,
10237                                        II->getNormalDest(), II->getUnwindDest(),
10238                                        NewArgs.begin(), NewArgs.end(),
10239                                        Caller->getName(), Caller);
10240         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10241         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10242       } else {
10243         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10244                                      Caller->getName(), Caller);
10245         if (cast<CallInst>(Caller)->isTailCall())
10246           cast<CallInst>(NewCaller)->setTailCall();
10247         cast<CallInst>(NewCaller)->
10248           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10249         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10250       }
10251       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10252         Caller->replaceAllUsesWith(NewCaller);
10253       Caller->eraseFromParent();
10254       RemoveFromWorkList(Caller);
10255       return 0;
10256     }
10257   }
10258
10259   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10260   // parameter, there is no need to adjust the argument list.  Let the generic
10261   // code sort out any function type mismatches.
10262   Constant *NewCallee =
10263     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10264   CS.setCalledFunction(NewCallee);
10265   return CS.getInstruction();
10266 }
10267
10268 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10269 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10270 /// and a single binop.
10271 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10272   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10273   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10274   unsigned Opc = FirstInst->getOpcode();
10275   Value *LHSVal = FirstInst->getOperand(0);
10276   Value *RHSVal = FirstInst->getOperand(1);
10277     
10278   const Type *LHSType = LHSVal->getType();
10279   const Type *RHSType = RHSVal->getType();
10280   
10281   // Scan to see if all operands are the same opcode, all have one use, and all
10282   // kill their operands (i.e. the operands have one use).
10283   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10284     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10285     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10286         // Verify type of the LHS matches so we don't fold cmp's of different
10287         // types or GEP's with different index types.
10288         I->getOperand(0)->getType() != LHSType ||
10289         I->getOperand(1)->getType() != RHSType)
10290       return 0;
10291
10292     // If they are CmpInst instructions, check their predicates
10293     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10294       if (cast<CmpInst>(I)->getPredicate() !=
10295           cast<CmpInst>(FirstInst)->getPredicate())
10296         return 0;
10297     
10298     // Keep track of which operand needs a phi node.
10299     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10300     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10301   }
10302   
10303   // Otherwise, this is safe to transform!
10304   
10305   Value *InLHS = FirstInst->getOperand(0);
10306   Value *InRHS = FirstInst->getOperand(1);
10307   PHINode *NewLHS = 0, *NewRHS = 0;
10308   if (LHSVal == 0) {
10309     NewLHS = PHINode::Create(LHSType,
10310                              FirstInst->getOperand(0)->getName() + ".pn");
10311     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10312     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10313     InsertNewInstBefore(NewLHS, PN);
10314     LHSVal = NewLHS;
10315   }
10316   
10317   if (RHSVal == 0) {
10318     NewRHS = PHINode::Create(RHSType,
10319                              FirstInst->getOperand(1)->getName() + ".pn");
10320     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10321     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10322     InsertNewInstBefore(NewRHS, PN);
10323     RHSVal = NewRHS;
10324   }
10325   
10326   // Add all operands to the new PHIs.
10327   if (NewLHS || NewRHS) {
10328     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10329       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10330       if (NewLHS) {
10331         Value *NewInLHS = InInst->getOperand(0);
10332         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10333       }
10334       if (NewRHS) {
10335         Value *NewInRHS = InInst->getOperand(1);
10336         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10337       }
10338     }
10339   }
10340     
10341   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10342     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10343   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10344   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10345                          RHSVal);
10346 }
10347
10348 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10349   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10350   
10351   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10352                                         FirstInst->op_end());
10353   // This is true if all GEP bases are allocas and if all indices into them are
10354   // constants.
10355   bool AllBasePointersAreAllocas = true;
10356   
10357   // Scan to see if all operands are the same opcode, all have one use, and all
10358   // kill their operands (i.e. the operands have one use).
10359   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10360     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10361     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10362       GEP->getNumOperands() != FirstInst->getNumOperands())
10363       return 0;
10364
10365     // Keep track of whether or not all GEPs are of alloca pointers.
10366     if (AllBasePointersAreAllocas &&
10367         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10368          !GEP->hasAllConstantIndices()))
10369       AllBasePointersAreAllocas = false;
10370     
10371     // Compare the operand lists.
10372     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10373       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10374         continue;
10375       
10376       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10377       // if one of the PHIs has a constant for the index.  The index may be
10378       // substantially cheaper to compute for the constants, so making it a
10379       // variable index could pessimize the path.  This also handles the case
10380       // for struct indices, which must always be constant.
10381       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10382           isa<ConstantInt>(GEP->getOperand(op)))
10383         return 0;
10384       
10385       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10386         return 0;
10387       FixedOperands[op] = 0;  // Needs a PHI.
10388     }
10389   }
10390   
10391   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10392   // bother doing this transformation.  At best, this will just save a bit of
10393   // offset calculation, but all the predecessors will have to materialize the
10394   // stack address into a register anyway.  We'd actually rather *clone* the
10395   // load up into the predecessors so that we have a load of a gep of an alloca,
10396   // which can usually all be folded into the load.
10397   if (AllBasePointersAreAllocas)
10398     return 0;
10399   
10400   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10401   // that is variable.
10402   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10403   
10404   bool HasAnyPHIs = false;
10405   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10406     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10407     Value *FirstOp = FirstInst->getOperand(i);
10408     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10409                                      FirstOp->getName()+".pn");
10410     InsertNewInstBefore(NewPN, PN);
10411     
10412     NewPN->reserveOperandSpace(e);
10413     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10414     OperandPhis[i] = NewPN;
10415     FixedOperands[i] = NewPN;
10416     HasAnyPHIs = true;
10417   }
10418
10419   
10420   // Add all operands to the new PHIs.
10421   if (HasAnyPHIs) {
10422     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10423       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10424       BasicBlock *InBB = PN.getIncomingBlock(i);
10425       
10426       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10427         if (PHINode *OpPhi = OperandPhis[op])
10428           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10429     }
10430   }
10431   
10432   Value *Base = FixedOperands[0];
10433   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10434                                    FixedOperands.end());
10435 }
10436
10437
10438 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10439 /// sink the load out of the block that defines it.  This means that it must be
10440 /// obvious the value of the load is not changed from the point of the load to
10441 /// the end of the block it is in.
10442 ///
10443 /// Finally, it is safe, but not profitable, to sink a load targetting a
10444 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10445 /// to a register.
10446 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10447   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10448   
10449   for (++BBI; BBI != E; ++BBI)
10450     if (BBI->mayWriteToMemory())
10451       return false;
10452   
10453   // Check for non-address taken alloca.  If not address-taken already, it isn't
10454   // profitable to do this xform.
10455   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10456     bool isAddressTaken = false;
10457     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10458          UI != E; ++UI) {
10459       if (isa<LoadInst>(UI)) continue;
10460       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10461         // If storing TO the alloca, then the address isn't taken.
10462         if (SI->getOperand(1) == AI) continue;
10463       }
10464       isAddressTaken = true;
10465       break;
10466     }
10467     
10468     if (!isAddressTaken && AI->isStaticAlloca())
10469       return false;
10470   }
10471   
10472   // If this load is a load from a GEP with a constant offset from an alloca,
10473   // then we don't want to sink it.  In its present form, it will be
10474   // load [constant stack offset].  Sinking it will cause us to have to
10475   // materialize the stack addresses in each predecessor in a register only to
10476   // do a shared load from register in the successor.
10477   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10478     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10479       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10480         return false;
10481   
10482   return true;
10483 }
10484
10485
10486 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10487 // operator and they all are only used by the PHI, PHI together their
10488 // inputs, and do the operation once, to the result of the PHI.
10489 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10490   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10491
10492   // Scan the instruction, looking for input operations that can be folded away.
10493   // If all input operands to the phi are the same instruction (e.g. a cast from
10494   // the same type or "+42") we can pull the operation through the PHI, reducing
10495   // code size and simplifying code.
10496   Constant *ConstantOp = 0;
10497   const Type *CastSrcTy = 0;
10498   bool isVolatile = false;
10499   if (isa<CastInst>(FirstInst)) {
10500     CastSrcTy = FirstInst->getOperand(0)->getType();
10501   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10502     // Can fold binop, compare or shift here if the RHS is a constant, 
10503     // otherwise call FoldPHIArgBinOpIntoPHI.
10504     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10505     if (ConstantOp == 0)
10506       return FoldPHIArgBinOpIntoPHI(PN);
10507   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10508     isVolatile = LI->isVolatile();
10509     // We can't sink the load if the loaded value could be modified between the
10510     // load and the PHI.
10511     if (LI->getParent() != PN.getIncomingBlock(0) ||
10512         !isSafeAndProfitableToSinkLoad(LI))
10513       return 0;
10514     
10515     // If the PHI is of volatile loads and the load block has multiple
10516     // successors, sinking it would remove a load of the volatile value from
10517     // the path through the other successor.
10518     if (isVolatile &&
10519         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10520       return 0;
10521     
10522   } else if (isa<GetElementPtrInst>(FirstInst)) {
10523     return FoldPHIArgGEPIntoPHI(PN);
10524   } else {
10525     return 0;  // Cannot fold this operation.
10526   }
10527
10528   // Check to see if all arguments are the same operation.
10529   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10530     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10531     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10532     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10533       return 0;
10534     if (CastSrcTy) {
10535       if (I->getOperand(0)->getType() != CastSrcTy)
10536         return 0;  // Cast operation must match.
10537     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10538       // We can't sink the load if the loaded value could be modified between 
10539       // the load and the PHI.
10540       if (LI->isVolatile() != isVolatile ||
10541           LI->getParent() != PN.getIncomingBlock(i) ||
10542           !isSafeAndProfitableToSinkLoad(LI))
10543         return 0;
10544       
10545       // If the PHI is of volatile loads and the load block has multiple
10546       // successors, sinking it would remove a load of the volatile value from
10547       // the path through the other successor.
10548       if (isVolatile &&
10549           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10550         return 0;
10551       
10552     } else if (I->getOperand(1) != ConstantOp) {
10553       return 0;
10554     }
10555   }
10556
10557   // Okay, they are all the same operation.  Create a new PHI node of the
10558   // correct type, and PHI together all of the LHS's of the instructions.
10559   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10560                                    PN.getName()+".in");
10561   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10562
10563   Value *InVal = FirstInst->getOperand(0);
10564   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10565
10566   // Add all operands to the new PHI.
10567   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10568     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10569     if (NewInVal != InVal)
10570       InVal = 0;
10571     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10572   }
10573
10574   Value *PhiVal;
10575   if (InVal) {
10576     // The new PHI unions all of the same values together.  This is really
10577     // common, so we handle it intelligently here for compile-time speed.
10578     PhiVal = InVal;
10579     delete NewPN;
10580   } else {
10581     InsertNewInstBefore(NewPN, PN);
10582     PhiVal = NewPN;
10583   }
10584
10585   // Insert and return the new operation.
10586   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10587     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10588   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10589     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10590   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10591     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10592                            PhiVal, ConstantOp);
10593   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10594   
10595   // If this was a volatile load that we are merging, make sure to loop through
10596   // and mark all the input loads as non-volatile.  If we don't do this, we will
10597   // insert a new volatile load and the old ones will not be deletable.
10598   if (isVolatile)
10599     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10600       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10601   
10602   return new LoadInst(PhiVal, "", isVolatile);
10603 }
10604
10605 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10606 /// that is dead.
10607 static bool DeadPHICycle(PHINode *PN,
10608                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10609   if (PN->use_empty()) return true;
10610   if (!PN->hasOneUse()) return false;
10611
10612   // Remember this node, and if we find the cycle, return.
10613   if (!PotentiallyDeadPHIs.insert(PN))
10614     return true;
10615   
10616   // Don't scan crazily complex things.
10617   if (PotentiallyDeadPHIs.size() == 16)
10618     return false;
10619
10620   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10621     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10622
10623   return false;
10624 }
10625
10626 /// PHIsEqualValue - Return true if this phi node is always equal to
10627 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10628 ///   z = some value; x = phi (y, z); y = phi (x, z)
10629 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10630                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10631   // See if we already saw this PHI node.
10632   if (!ValueEqualPHIs.insert(PN))
10633     return true;
10634   
10635   // Don't scan crazily complex things.
10636   if (ValueEqualPHIs.size() == 16)
10637     return false;
10638  
10639   // Scan the operands to see if they are either phi nodes or are equal to
10640   // the value.
10641   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10642     Value *Op = PN->getIncomingValue(i);
10643     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10644       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10645         return false;
10646     } else if (Op != NonPhiInVal)
10647       return false;
10648   }
10649   
10650   return true;
10651 }
10652
10653
10654 // PHINode simplification
10655 //
10656 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10657   // If LCSSA is around, don't mess with Phi nodes
10658   if (MustPreserveLCSSA) return 0;
10659   
10660   if (Value *V = PN.hasConstantValue())
10661     return ReplaceInstUsesWith(PN, V);
10662
10663   // If all PHI operands are the same operation, pull them through the PHI,
10664   // reducing code size.
10665   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10666       isa<Instruction>(PN.getIncomingValue(1)) &&
10667       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10668       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10669       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10670       // than themselves more than once.
10671       PN.getIncomingValue(0)->hasOneUse())
10672     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10673       return Result;
10674
10675   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10676   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10677   // PHI)... break the cycle.
10678   if (PN.hasOneUse()) {
10679     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10680     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10681       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10682       PotentiallyDeadPHIs.insert(&PN);
10683       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10684         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10685     }
10686    
10687     // If this phi has a single use, and if that use just computes a value for
10688     // the next iteration of a loop, delete the phi.  This occurs with unused
10689     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10690     // common case here is good because the only other things that catch this
10691     // are induction variable analysis (sometimes) and ADCE, which is only run
10692     // late.
10693     if (PHIUser->hasOneUse() &&
10694         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10695         PHIUser->use_back() == &PN) {
10696       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10697     }
10698   }
10699
10700   // We sometimes end up with phi cycles that non-obviously end up being the
10701   // same value, for example:
10702   //   z = some value; x = phi (y, z); y = phi (x, z)
10703   // where the phi nodes don't necessarily need to be in the same block.  Do a
10704   // quick check to see if the PHI node only contains a single non-phi value, if
10705   // so, scan to see if the phi cycle is actually equal to that value.
10706   {
10707     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10708     // Scan for the first non-phi operand.
10709     while (InValNo != NumOperandVals && 
10710            isa<PHINode>(PN.getIncomingValue(InValNo)))
10711       ++InValNo;
10712
10713     if (InValNo != NumOperandVals) {
10714       Value *NonPhiInVal = PN.getOperand(InValNo);
10715       
10716       // Scan the rest of the operands to see if there are any conflicts, if so
10717       // there is no need to recursively scan other phis.
10718       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10719         Value *OpVal = PN.getIncomingValue(InValNo);
10720         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10721           break;
10722       }
10723       
10724       // If we scanned over all operands, then we have one unique value plus
10725       // phi values.  Scan PHI nodes to see if they all merge in each other or
10726       // the value.
10727       if (InValNo == NumOperandVals) {
10728         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10729         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10730           return ReplaceInstUsesWith(PN, NonPhiInVal);
10731       }
10732     }
10733   }
10734   return 0;
10735 }
10736
10737 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10738                                    Instruction *InsertPoint,
10739                                    InstCombiner *IC) {
10740   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10741   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10742   // We must cast correctly to the pointer type. Ensure that we
10743   // sign extend the integer value if it is smaller as this is
10744   // used for address computation.
10745   Instruction::CastOps opcode = 
10746      (VTySize < PtrSize ? Instruction::SExt :
10747       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10748   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10749 }
10750
10751
10752 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10753   Value *PtrOp = GEP.getOperand(0);
10754   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10755   // If so, eliminate the noop.
10756   if (GEP.getNumOperands() == 1)
10757     return ReplaceInstUsesWith(GEP, PtrOp);
10758
10759   if (isa<UndefValue>(GEP.getOperand(0)))
10760     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10761
10762   bool HasZeroPointerIndex = false;
10763   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10764     HasZeroPointerIndex = C->isNullValue();
10765
10766   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10767     return ReplaceInstUsesWith(GEP, PtrOp);
10768
10769   // Eliminate unneeded casts for indices.
10770   bool MadeChange = false;
10771   
10772   gep_type_iterator GTI = gep_type_begin(GEP);
10773   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10774        i != e; ++i, ++GTI) {
10775     if (isa<SequentialType>(*GTI)) {
10776       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10777         if (CI->getOpcode() == Instruction::ZExt ||
10778             CI->getOpcode() == Instruction::SExt) {
10779           const Type *SrcTy = CI->getOperand(0)->getType();
10780           // We can eliminate a cast from i32 to i64 iff the target 
10781           // is a 32-bit pointer target.
10782           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10783             MadeChange = true;
10784             *i = CI->getOperand(0);
10785           }
10786         }
10787       }
10788       // If we are using a wider index than needed for this platform, shrink it
10789       // to what we need.  If narrower, sign-extend it to what we need.
10790       // If the incoming value needs a cast instruction,
10791       // insert it.  This explicit cast can make subsequent optimizations more
10792       // obvious.
10793       Value *Op = *i;
10794       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10795         if (Constant *C = dyn_cast<Constant>(Op)) {
10796           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10797           MadeChange = true;
10798         } else {
10799           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10800                                 GEP);
10801           *i = Op;
10802           MadeChange = true;
10803         }
10804       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10805         if (Constant *C = dyn_cast<Constant>(Op)) {
10806           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10807           MadeChange = true;
10808         } else {
10809           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10810                                 GEP);
10811           *i = Op;
10812           MadeChange = true;
10813         }
10814       }
10815     }
10816   }
10817   if (MadeChange) return &GEP;
10818
10819   // Combine Indices - If the source pointer to this getelementptr instruction
10820   // is a getelementptr instruction, combine the indices of the two
10821   // getelementptr instructions into a single instruction.
10822   //
10823   SmallVector<Value*, 8> SrcGEPOperands;
10824   if (User *Src = dyn_castGetElementPtr(PtrOp))
10825     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10826
10827   if (!SrcGEPOperands.empty()) {
10828     // Note that if our source is a gep chain itself that we wait for that
10829     // chain to be resolved before we perform this transformation.  This
10830     // avoids us creating a TON of code in some cases.
10831     //
10832     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10833         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10834       return 0;   // Wait until our source is folded to completion.
10835
10836     SmallVector<Value*, 8> Indices;
10837
10838     // Find out whether the last index in the source GEP is a sequential idx.
10839     bool EndsWithSequential = false;
10840     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10841            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10842       EndsWithSequential = !isa<StructType>(*I);
10843
10844     // Can we combine the two pointer arithmetics offsets?
10845     if (EndsWithSequential) {
10846       // Replace: gep (gep %P, long B), long A, ...
10847       // With:    T = long A+B; gep %P, T, ...
10848       //
10849       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10850       if (SO1 == Constant::getNullValue(SO1->getType())) {
10851         Sum = GO1;
10852       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10853         Sum = SO1;
10854       } else {
10855         // If they aren't the same type, convert both to an integer of the
10856         // target's pointer size.
10857         if (SO1->getType() != GO1->getType()) {
10858           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10859             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10860           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10861             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10862           } else {
10863             unsigned PS = TD->getPointerSizeInBits();
10864             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10865               // Convert GO1 to SO1's type.
10866               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10867
10868             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10869               // Convert SO1 to GO1's type.
10870               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10871             } else {
10872               const Type *PT = TD->getIntPtrType();
10873               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10874               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10875             }
10876           }
10877         }
10878         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10879           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10880         else {
10881           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10882           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10883         }
10884       }
10885
10886       // Recycle the GEP we already have if possible.
10887       if (SrcGEPOperands.size() == 2) {
10888         GEP.setOperand(0, SrcGEPOperands[0]);
10889         GEP.setOperand(1, Sum);
10890         return &GEP;
10891       } else {
10892         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10893                        SrcGEPOperands.end()-1);
10894         Indices.push_back(Sum);
10895         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10896       }
10897     } else if (isa<Constant>(*GEP.idx_begin()) &&
10898                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10899                SrcGEPOperands.size() != 1) {
10900       // Otherwise we can do the fold if the first index of the GEP is a zero
10901       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10902                      SrcGEPOperands.end());
10903       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10904     }
10905
10906     if (!Indices.empty())
10907       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10908                                        Indices.end(), GEP.getName());
10909
10910   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10911     // GEP of global variable.  If all of the indices for this GEP are
10912     // constants, we can promote this to a constexpr instead of an instruction.
10913
10914     // Scan for nonconstants...
10915     SmallVector<Constant*, 8> Indices;
10916     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10917     for (; I != E && isa<Constant>(*I); ++I)
10918       Indices.push_back(cast<Constant>(*I));
10919
10920     if (I == E) {  // If they are all constants...
10921       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10922                                                     &Indices[0],Indices.size());
10923
10924       // Replace all uses of the GEP with the new constexpr...
10925       return ReplaceInstUsesWith(GEP, CE);
10926     }
10927   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10928     if (!isa<PointerType>(X->getType())) {
10929       // Not interesting.  Source pointer must be a cast from pointer.
10930     } else if (HasZeroPointerIndex) {
10931       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10932       // into     : GEP [10 x i8]* X, i32 0, ...
10933       //
10934       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10935       //           into     : GEP i8* X, ...
10936       // 
10937       // This occurs when the program declares an array extern like "int X[];"
10938       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10939       const PointerType *XTy = cast<PointerType>(X->getType());
10940       if (const ArrayType *CATy =
10941           dyn_cast<ArrayType>(CPTy->getElementType())) {
10942         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10943         if (CATy->getElementType() == XTy->getElementType()) {
10944           // -> GEP i8* X, ...
10945           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10946           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10947                                            GEP.getName());
10948         } else if (const ArrayType *XATy =
10949                  dyn_cast<ArrayType>(XTy->getElementType())) {
10950           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
10951           if (CATy->getElementType() == XATy->getElementType()) {
10952             // -> GEP [10 x i8]* X, i32 0, ...
10953             // At this point, we know that the cast source type is a pointer
10954             // to an array of the same type as the destination pointer
10955             // array.  Because the array type is never stepped over (there
10956             // is a leading zero) we can fold the cast into this GEP.
10957             GEP.setOperand(0, X);
10958             return &GEP;
10959           }
10960         }
10961       }
10962     } else if (GEP.getNumOperands() == 2) {
10963       // Transform things like:
10964       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10965       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10966       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10967       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10968       if (isa<ArrayType>(SrcElTy) &&
10969           TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10970           TD->getTypePaddedSize(ResElTy)) {
10971         Value *Idx[2];
10972         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10973         Idx[1] = GEP.getOperand(1);
10974         Value *V = InsertNewInstBefore(
10975                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10976         // V and GEP are both pointer types --> BitCast
10977         return new BitCastInst(V, GEP.getType());
10978       }
10979       
10980       // Transform things like:
10981       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10982       //   (where tmp = 8*tmp2) into:
10983       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10984       
10985       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10986         uint64_t ArrayEltSize =
10987             TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
10988         
10989         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10990         // allow either a mul, shift, or constant here.
10991         Value *NewIdx = 0;
10992         ConstantInt *Scale = 0;
10993         if (ArrayEltSize == 1) {
10994           NewIdx = GEP.getOperand(1);
10995           Scale = ConstantInt::get(NewIdx->getType(), 1);
10996         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10997           NewIdx = ConstantInt::get(CI->getType(), 1);
10998           Scale = CI;
10999         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11000           if (Inst->getOpcode() == Instruction::Shl &&
11001               isa<ConstantInt>(Inst->getOperand(1))) {
11002             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11003             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11004             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
11005             NewIdx = Inst->getOperand(0);
11006           } else if (Inst->getOpcode() == Instruction::Mul &&
11007                      isa<ConstantInt>(Inst->getOperand(1))) {
11008             Scale = cast<ConstantInt>(Inst->getOperand(1));
11009             NewIdx = Inst->getOperand(0);
11010           }
11011         }
11012         
11013         // If the index will be to exactly the right offset with the scale taken
11014         // out, perform the transformation. Note, we don't know whether Scale is
11015         // signed or not. We'll use unsigned version of division/modulo
11016         // operation after making sure Scale doesn't have the sign bit set.
11017         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11018             Scale->getZExtValue() % ArrayEltSize == 0) {
11019           Scale = ConstantInt::get(Scale->getType(),
11020                                    Scale->getZExtValue() / ArrayEltSize);
11021           if (Scale->getZExtValue() != 1) {
11022             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11023                                                        false /*ZExt*/);
11024             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11025             NewIdx = InsertNewInstBefore(Sc, GEP);
11026           }
11027
11028           // Insert the new GEP instruction.
11029           Value *Idx[2];
11030           Idx[0] = Constant::getNullValue(Type::Int32Ty);
11031           Idx[1] = NewIdx;
11032           Instruction *NewGEP =
11033             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11034           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11035           // The NewGEP must be pointer typed, so must the old one -> BitCast
11036           return new BitCastInst(NewGEP, GEP.getType());
11037         }
11038       }
11039     }
11040   }
11041   
11042   /// See if we can simplify:
11043   ///   X = bitcast A to B*
11044   ///   Y = gep X, <...constant indices...>
11045   /// into a gep of the original struct.  This is important for SROA and alias
11046   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11047   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11048     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11049       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11050       // a constant back from EmitGEPOffset.
11051       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11052       int64_t Offset = OffsetV->getSExtValue();
11053       
11054       // If this GEP instruction doesn't move the pointer, just replace the GEP
11055       // with a bitcast of the real input to the dest type.
11056       if (Offset == 0) {
11057         // If the bitcast is of an allocation, and the allocation will be
11058         // converted to match the type of the cast, don't touch this.
11059         if (isa<AllocationInst>(BCI->getOperand(0))) {
11060           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11061           if (Instruction *I = visitBitCast(*BCI)) {
11062             if (I != BCI) {
11063               I->takeName(BCI);
11064               BCI->getParent()->getInstList().insert(BCI, I);
11065               ReplaceInstUsesWith(*BCI, I);
11066             }
11067             return &GEP;
11068           }
11069         }
11070         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11071       }
11072       
11073       // Otherwise, if the offset is non-zero, we need to find out if there is a
11074       // field at Offset in 'A's type.  If so, we can pull the cast through the
11075       // GEP.
11076       SmallVector<Value*, 8> NewIndices;
11077       const Type *InTy =
11078         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11079       if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
11080         Instruction *NGEP =
11081            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11082                                      NewIndices.end());
11083         if (NGEP->getType() == GEP.getType()) return NGEP;
11084         InsertNewInstBefore(NGEP, GEP);
11085         NGEP->takeName(&GEP);
11086         return new BitCastInst(NGEP, GEP.getType());
11087       }
11088     }
11089   }    
11090     
11091   return 0;
11092 }
11093
11094 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11095   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11096   if (AI.isArrayAllocation()) {  // Check C != 1
11097     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11098       const Type *NewTy = 
11099         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11100       AllocationInst *New = 0;
11101
11102       // Create and insert the replacement instruction...
11103       if (isa<MallocInst>(AI))
11104         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11105       else {
11106         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11107         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11108       }
11109
11110       InsertNewInstBefore(New, AI);
11111
11112       // Scan to the end of the allocation instructions, to skip over a block of
11113       // allocas if possible...also skip interleaved debug info
11114       //
11115       BasicBlock::iterator It = New;
11116       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11117
11118       // Now that I is pointing to the first non-allocation-inst in the block,
11119       // insert our getelementptr instruction...
11120       //
11121       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
11122       Value *Idx[2];
11123       Idx[0] = NullIdx;
11124       Idx[1] = NullIdx;
11125       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11126                                            New->getName()+".sub", It);
11127
11128       // Now make everything use the getelementptr instead of the original
11129       // allocation.
11130       return ReplaceInstUsesWith(AI, V);
11131     } else if (isa<UndefValue>(AI.getArraySize())) {
11132       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11133     }
11134   }
11135
11136   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11137     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11138     // Note that we only do this for alloca's, because malloc should allocate
11139     // and return a unique pointer, even for a zero byte allocation.
11140     if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
11141       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11142
11143     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11144     if (AI.getAlignment() == 0)
11145       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11146   }
11147
11148   return 0;
11149 }
11150
11151 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11152   Value *Op = FI.getOperand(0);
11153
11154   // free undef -> unreachable.
11155   if (isa<UndefValue>(Op)) {
11156     // Insert a new store to null because we cannot modify the CFG here.
11157     new StoreInst(ConstantInt::getTrue(),
11158                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
11159     return EraseInstFromFunction(FI);
11160   }
11161   
11162   // If we have 'free null' delete the instruction.  This can happen in stl code
11163   // when lots of inlining happens.
11164   if (isa<ConstantPointerNull>(Op))
11165     return EraseInstFromFunction(FI);
11166   
11167   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11168   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11169     FI.setOperand(0, CI->getOperand(0));
11170     return &FI;
11171   }
11172   
11173   // Change free (gep X, 0,0,0,0) into free(X)
11174   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11175     if (GEPI->hasAllZeroIndices()) {
11176       AddToWorkList(GEPI);
11177       FI.setOperand(0, GEPI->getOperand(0));
11178       return &FI;
11179     }
11180   }
11181   
11182   // Change free(malloc) into nothing, if the malloc has a single use.
11183   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11184     if (MI->hasOneUse()) {
11185       EraseInstFromFunction(FI);
11186       return EraseInstFromFunction(*MI);
11187     }
11188
11189   return 0;
11190 }
11191
11192
11193 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11194 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11195                                         const TargetData *TD) {
11196   User *CI = cast<User>(LI.getOperand(0));
11197   Value *CastOp = CI->getOperand(0);
11198
11199   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11200     // Instead of loading constant c string, use corresponding integer value
11201     // directly if string length is small enough.
11202     std::string Str;
11203     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11204       unsigned len = Str.length();
11205       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11206       unsigned numBits = Ty->getPrimitiveSizeInBits();
11207       // Replace LI with immediate integer store.
11208       if ((numBits >> 3) == len + 1) {
11209         APInt StrVal(numBits, 0);
11210         APInt SingleChar(numBits, 0);
11211         if (TD->isLittleEndian()) {
11212           for (signed i = len-1; i >= 0; i--) {
11213             SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11214             StrVal = (StrVal << 8) | SingleChar;
11215           }
11216         } else {
11217           for (unsigned i = 0; i < len; i++) {
11218             SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11219             StrVal = (StrVal << 8) | SingleChar;
11220           }
11221           // Append NULL at the end.
11222           SingleChar = 0;
11223           StrVal = (StrVal << 8) | SingleChar;
11224         }
11225         Value *NL = ConstantInt::get(StrVal);
11226         return IC.ReplaceInstUsesWith(LI, NL);
11227       }
11228     }
11229   }
11230
11231   const PointerType *DestTy = cast<PointerType>(CI->getType());
11232   const Type *DestPTy = DestTy->getElementType();
11233   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11234
11235     // If the address spaces don't match, don't eliminate the cast.
11236     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11237       return 0;
11238
11239     const Type *SrcPTy = SrcTy->getElementType();
11240
11241     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11242          isa<VectorType>(DestPTy)) {
11243       // If the source is an array, the code below will not succeed.  Check to
11244       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11245       // constants.
11246       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11247         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11248           if (ASrcTy->getNumElements() != 0) {
11249             Value *Idxs[2];
11250             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11251             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11252             SrcTy = cast<PointerType>(CastOp->getType());
11253             SrcPTy = SrcTy->getElementType();
11254           }
11255
11256       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11257             isa<VectorType>(SrcPTy)) &&
11258           // Do not allow turning this into a load of an integer, which is then
11259           // casted to a pointer, this pessimizes pointer analysis a lot.
11260           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11261           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11262                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11263
11264         // Okay, we are casting from one integer or pointer type to another of
11265         // the same size.  Instead of casting the pointer before the load, cast
11266         // the result of the loaded value.
11267         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11268                                                              CI->getName(),
11269                                                          LI.isVolatile()),LI);
11270         // Now cast the result of the load.
11271         return new BitCastInst(NewLoad, LI.getType());
11272       }
11273     }
11274   }
11275   return 0;
11276 }
11277
11278 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
11279 /// from this value cannot trap.  If it is not obviously safe to load from the
11280 /// specified pointer, we do a quick local scan of the basic block containing
11281 /// ScanFrom, to determine if the address is already accessed.
11282 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
11283   // If it is an alloca it is always safe to load from.
11284   if (isa<AllocaInst>(V)) return true;
11285
11286   // If it is a global variable it is mostly safe to load from.
11287   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
11288     // Don't try to evaluate aliases.  External weak GV can be null.
11289     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
11290
11291   // Otherwise, be a little bit agressive by scanning the local block where we
11292   // want to check to see if the pointer is already being loaded or stored
11293   // from/to.  If so, the previous load or store would have already trapped,
11294   // so there is no harm doing an extra load (also, CSE will later eliminate
11295   // the load entirely).
11296   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11297
11298   while (BBI != E) {
11299     --BBI;
11300
11301     // If we see a free or a call (which might do a free) the pointer could be
11302     // marked invalid.
11303     if (isa<FreeInst>(BBI) || 
11304         (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)))
11305       return false;
11306     
11307     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11308       if (LI->getOperand(0) == V) return true;
11309     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
11310       if (SI->getOperand(1) == V) return true;
11311     }
11312
11313   }
11314   return false;
11315 }
11316
11317 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11318   Value *Op = LI.getOperand(0);
11319
11320   // Attempt to improve the alignment.
11321   unsigned KnownAlign =
11322     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11323   if (KnownAlign >
11324       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11325                                 LI.getAlignment()))
11326     LI.setAlignment(KnownAlign);
11327
11328   // load (cast X) --> cast (load X) iff safe
11329   if (isa<CastInst>(Op))
11330     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11331       return Res;
11332
11333   // None of the following transforms are legal for volatile loads.
11334   if (LI.isVolatile()) return 0;
11335   
11336   // Do really simple store-to-load forwarding and load CSE, to catch cases
11337   // where there are several consequtive memory accesses to the same location,
11338   // separated by a few arithmetic operations.
11339   BasicBlock::iterator BBI = &LI;
11340   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11341     return ReplaceInstUsesWith(LI, AvailableVal);
11342
11343   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11344     const Value *GEPI0 = GEPI->getOperand(0);
11345     // TODO: Consider a target hook for valid address spaces for this xform.
11346     if (isa<ConstantPointerNull>(GEPI0) &&
11347         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11348       // Insert a new store to null instruction before the load to indicate
11349       // that this code is not reachable.  We do this instead of inserting
11350       // an unreachable instruction directly because we cannot modify the
11351       // CFG.
11352       new StoreInst(UndefValue::get(LI.getType()),
11353                     Constant::getNullValue(Op->getType()), &LI);
11354       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11355     }
11356   } 
11357
11358   if (Constant *C = dyn_cast<Constant>(Op)) {
11359     // load null/undef -> undef
11360     // TODO: Consider a target hook for valid address spaces for this xform.
11361     if (isa<UndefValue>(C) || (C->isNullValue() && 
11362         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11363       // Insert a new store to null instruction before the load to indicate that
11364       // this code is not reachable.  We do this instead of inserting an
11365       // unreachable instruction directly because we cannot modify the CFG.
11366       new StoreInst(UndefValue::get(LI.getType()),
11367                     Constant::getNullValue(Op->getType()), &LI);
11368       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11369     }
11370
11371     // Instcombine load (constant global) into the value loaded.
11372     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11373       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11374         return ReplaceInstUsesWith(LI, GV->getInitializer());
11375
11376     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11377     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11378       if (CE->getOpcode() == Instruction::GetElementPtr) {
11379         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11380           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11381             if (Constant *V = 
11382                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11383               return ReplaceInstUsesWith(LI, V);
11384         if (CE->getOperand(0)->isNullValue()) {
11385           // Insert a new store to null instruction before the load to indicate
11386           // that this code is not reachable.  We do this instead of inserting
11387           // an unreachable instruction directly because we cannot modify the
11388           // CFG.
11389           new StoreInst(UndefValue::get(LI.getType()),
11390                         Constant::getNullValue(Op->getType()), &LI);
11391           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11392         }
11393
11394       } else if (CE->isCast()) {
11395         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11396           return Res;
11397       }
11398     }
11399   }
11400     
11401   // If this load comes from anywhere in a constant global, and if the global
11402   // is all undef or zero, we know what it loads.
11403   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11404     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11405       if (GV->getInitializer()->isNullValue())
11406         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11407       else if (isa<UndefValue>(GV->getInitializer()))
11408         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11409     }
11410   }
11411
11412   if (Op->hasOneUse()) {
11413     // Change select and PHI nodes to select values instead of addresses: this
11414     // helps alias analysis out a lot, allows many others simplifications, and
11415     // exposes redundancy in the code.
11416     //
11417     // Note that we cannot do the transformation unless we know that the
11418     // introduced loads cannot trap!  Something like this is valid as long as
11419     // the condition is always false: load (select bool %C, int* null, int* %G),
11420     // but it would not be valid if we transformed it to load from null
11421     // unconditionally.
11422     //
11423     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11424       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11425       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11426           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11427         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11428                                      SI->getOperand(1)->getName()+".val"), LI);
11429         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11430                                      SI->getOperand(2)->getName()+".val"), LI);
11431         return SelectInst::Create(SI->getCondition(), V1, V2);
11432       }
11433
11434       // load (select (cond, null, P)) -> load P
11435       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11436         if (C->isNullValue()) {
11437           LI.setOperand(0, SI->getOperand(2));
11438           return &LI;
11439         }
11440
11441       // load (select (cond, P, null)) -> load P
11442       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11443         if (C->isNullValue()) {
11444           LI.setOperand(0, SI->getOperand(1));
11445           return &LI;
11446         }
11447     }
11448   }
11449   return 0;
11450 }
11451
11452 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11453 /// when possible.  This makes it generally easy to do alias analysis and/or
11454 /// SROA/mem2reg of the memory object.
11455 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11456   User *CI = cast<User>(SI.getOperand(1));
11457   Value *CastOp = CI->getOperand(0);
11458
11459   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11460   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11461   if (SrcTy == 0) return 0;
11462   
11463   const Type *SrcPTy = SrcTy->getElementType();
11464
11465   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11466     return 0;
11467   
11468   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11469   /// to its first element.  This allows us to handle things like:
11470   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11471   /// on 32-bit hosts.
11472   SmallVector<Value*, 4> NewGEPIndices;
11473   
11474   // If the source is an array, the code below will not succeed.  Check to
11475   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11476   // constants.
11477   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11478     // Index through pointer.
11479     Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11480     NewGEPIndices.push_back(Zero);
11481     
11482     while (1) {
11483       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11484         if (!STy->getNumElements()) /* Struct can be empty {} */
11485           break;
11486         NewGEPIndices.push_back(Zero);
11487         SrcPTy = STy->getElementType(0);
11488       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11489         NewGEPIndices.push_back(Zero);
11490         SrcPTy = ATy->getElementType();
11491       } else {
11492         break;
11493       }
11494     }
11495     
11496     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11497   }
11498
11499   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11500     return 0;
11501   
11502   // If the pointers point into different address spaces or if they point to
11503   // values with different sizes, we can't do the transformation.
11504   if (SrcTy->getAddressSpace() != 
11505         cast<PointerType>(CI->getType())->getAddressSpace() ||
11506       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11507       IC.getTargetData().getTypeSizeInBits(DestPTy))
11508     return 0;
11509
11510   // Okay, we are casting from one integer or pointer type to another of
11511   // the same size.  Instead of casting the pointer before 
11512   // the store, cast the value to be stored.
11513   Value *NewCast;
11514   Value *SIOp0 = SI.getOperand(0);
11515   Instruction::CastOps opcode = Instruction::BitCast;
11516   const Type* CastSrcTy = SIOp0->getType();
11517   const Type* CastDstTy = SrcPTy;
11518   if (isa<PointerType>(CastDstTy)) {
11519     if (CastSrcTy->isInteger())
11520       opcode = Instruction::IntToPtr;
11521   } else if (isa<IntegerType>(CastDstTy)) {
11522     if (isa<PointerType>(SIOp0->getType()))
11523       opcode = Instruction::PtrToInt;
11524   }
11525   
11526   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11527   // emit a GEP to index into its first field.
11528   if (!NewGEPIndices.empty()) {
11529     if (Constant *C = dyn_cast<Constant>(CastOp))
11530       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11531                                               NewGEPIndices.size());
11532     else
11533       CastOp = IC.InsertNewInstBefore(
11534               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11535                                         NewGEPIndices.end()), SI);
11536   }
11537   
11538   if (Constant *C = dyn_cast<Constant>(SIOp0))
11539     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11540   else
11541     NewCast = IC.InsertNewInstBefore(
11542       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11543       SI);
11544   return new StoreInst(NewCast, CastOp);
11545 }
11546
11547 /// equivalentAddressValues - Test if A and B will obviously have the same
11548 /// value. This includes recognizing that %t0 and %t1 will have the same
11549 /// value in code like this:
11550 ///   %t0 = getelementptr \@a, 0, 3
11551 ///   store i32 0, i32* %t0
11552 ///   %t1 = getelementptr \@a, 0, 3
11553 ///   %t2 = load i32* %t1
11554 ///
11555 static bool equivalentAddressValues(Value *A, Value *B) {
11556   // Test if the values are trivially equivalent.
11557   if (A == B) return true;
11558   
11559   // Test if the values come form identical arithmetic instructions.
11560   if (isa<BinaryOperator>(A) ||
11561       isa<CastInst>(A) ||
11562       isa<PHINode>(A) ||
11563       isa<GetElementPtrInst>(A))
11564     if (Instruction *BI = dyn_cast<Instruction>(B))
11565       if (cast<Instruction>(A)->isIdenticalTo(BI))
11566         return true;
11567   
11568   // Otherwise they may not be equivalent.
11569   return false;
11570 }
11571
11572 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11573 // return the llvm.dbg.declare.
11574 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11575   if (!V->hasNUses(2))
11576     return 0;
11577   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11578        UI != E; ++UI) {
11579     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11580       return DI;
11581     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11582       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11583         return DI;
11584       }
11585   }
11586   return 0;
11587 }
11588
11589 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11590   Value *Val = SI.getOperand(0);
11591   Value *Ptr = SI.getOperand(1);
11592
11593   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11594     EraseInstFromFunction(SI);
11595     ++NumCombined;
11596     return 0;
11597   }
11598   
11599   // If the RHS is an alloca with a single use, zapify the store, making the
11600   // alloca dead.
11601   // If the RHS is an alloca with a two uses, the other one being a 
11602   // llvm.dbg.declare, zapify the store and the declare, making the
11603   // alloca dead.  We must do this to prevent declare's from affecting
11604   // codegen.
11605   if (!SI.isVolatile()) {
11606     if (Ptr->hasOneUse()) {
11607       if (isa<AllocaInst>(Ptr)) {
11608         EraseInstFromFunction(SI);
11609         ++NumCombined;
11610         return 0;
11611       }
11612       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11613         if (isa<AllocaInst>(GEP->getOperand(0))) {
11614           if (GEP->getOperand(0)->hasOneUse()) {
11615             EraseInstFromFunction(SI);
11616             ++NumCombined;
11617             return 0;
11618           }
11619           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11620             EraseInstFromFunction(*DI);
11621             EraseInstFromFunction(SI);
11622             ++NumCombined;
11623             return 0;
11624           }
11625         }
11626       }
11627     }
11628     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11629       EraseInstFromFunction(*DI);
11630       EraseInstFromFunction(SI);
11631       ++NumCombined;
11632       return 0;
11633     }
11634   }
11635
11636   // Attempt to improve the alignment.
11637   unsigned KnownAlign =
11638     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11639   if (KnownAlign >
11640       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11641                                 SI.getAlignment()))
11642     SI.setAlignment(KnownAlign);
11643
11644   // Do really simple DSE, to catch cases where there are several consecutive
11645   // stores to the same location, separated by a few arithmetic operations. This
11646   // situation often occurs with bitfield accesses.
11647   BasicBlock::iterator BBI = &SI;
11648   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11649        --ScanInsts) {
11650     --BBI;
11651     // Don't count debug info directives, lest they affect codegen,
11652     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11653     // It is necessary for correctness to skip those that feed into a
11654     // llvm.dbg.declare, as these are not present when debugging is off.
11655     if (isa<DbgInfoIntrinsic>(BBI) ||
11656         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11657       ScanInsts++;
11658       continue;
11659     }    
11660     
11661     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11662       // Prev store isn't volatile, and stores to the same location?
11663       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11664                                                           SI.getOperand(1))) {
11665         ++NumDeadStore;
11666         ++BBI;
11667         EraseInstFromFunction(*PrevSI);
11668         continue;
11669       }
11670       break;
11671     }
11672     
11673     // If this is a load, we have to stop.  However, if the loaded value is from
11674     // the pointer we're loading and is producing the pointer we're storing,
11675     // then *this* store is dead (X = load P; store X -> P).
11676     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11677       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11678           !SI.isVolatile()) {
11679         EraseInstFromFunction(SI);
11680         ++NumCombined;
11681         return 0;
11682       }
11683       // Otherwise, this is a load from some other location.  Stores before it
11684       // may not be dead.
11685       break;
11686     }
11687     
11688     // Don't skip over loads or things that can modify memory.
11689     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11690       break;
11691   }
11692   
11693   
11694   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11695
11696   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11697   if (isa<ConstantPointerNull>(Ptr)) {
11698     if (!isa<UndefValue>(Val)) {
11699       SI.setOperand(0, UndefValue::get(Val->getType()));
11700       if (Instruction *U = dyn_cast<Instruction>(Val))
11701         AddToWorkList(U);  // Dropped a use.
11702       ++NumCombined;
11703     }
11704     return 0;  // Do not modify these!
11705   }
11706
11707   // store undef, Ptr -> noop
11708   if (isa<UndefValue>(Val)) {
11709     EraseInstFromFunction(SI);
11710     ++NumCombined;
11711     return 0;
11712   }
11713
11714   // If the pointer destination is a cast, see if we can fold the cast into the
11715   // source instead.
11716   if (isa<CastInst>(Ptr))
11717     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11718       return Res;
11719   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11720     if (CE->isCast())
11721       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11722         return Res;
11723
11724   
11725   // If this store is the last instruction in the basic block (possibly
11726   // excepting debug info instructions and the pointer bitcasts that feed
11727   // into them), and if the block ends with an unconditional branch, try
11728   // to move it to the successor block.
11729   BBI = &SI; 
11730   do {
11731     ++BBI;
11732   } while (isa<DbgInfoIntrinsic>(BBI) ||
11733            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11734   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11735     if (BI->isUnconditional())
11736       if (SimplifyStoreAtEndOfBlock(SI))
11737         return 0;  // xform done!
11738   
11739   return 0;
11740 }
11741
11742 /// SimplifyStoreAtEndOfBlock - Turn things like:
11743 ///   if () { *P = v1; } else { *P = v2 }
11744 /// into a phi node with a store in the successor.
11745 ///
11746 /// Simplify things like:
11747 ///   *P = v1; if () { *P = v2; }
11748 /// into a phi node with a store in the successor.
11749 ///
11750 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11751   BasicBlock *StoreBB = SI.getParent();
11752   
11753   // Check to see if the successor block has exactly two incoming edges.  If
11754   // so, see if the other predecessor contains a store to the same location.
11755   // if so, insert a PHI node (if needed) and move the stores down.
11756   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11757   
11758   // Determine whether Dest has exactly two predecessors and, if so, compute
11759   // the other predecessor.
11760   pred_iterator PI = pred_begin(DestBB);
11761   BasicBlock *OtherBB = 0;
11762   if (*PI != StoreBB)
11763     OtherBB = *PI;
11764   ++PI;
11765   if (PI == pred_end(DestBB))
11766     return false;
11767   
11768   if (*PI != StoreBB) {
11769     if (OtherBB)
11770       return false;
11771     OtherBB = *PI;
11772   }
11773   if (++PI != pred_end(DestBB))
11774     return false;
11775
11776   // Bail out if all the relevant blocks aren't distinct (this can happen,
11777   // for example, if SI is in an infinite loop)
11778   if (StoreBB == DestBB || OtherBB == DestBB)
11779     return false;
11780
11781   // Verify that the other block ends in a branch and is not otherwise empty.
11782   BasicBlock::iterator BBI = OtherBB->getTerminator();
11783   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11784   if (!OtherBr || BBI == OtherBB->begin())
11785     return false;
11786   
11787   // If the other block ends in an unconditional branch, check for the 'if then
11788   // else' case.  there is an instruction before the branch.
11789   StoreInst *OtherStore = 0;
11790   if (OtherBr->isUnconditional()) {
11791     --BBI;
11792     // Skip over debugging info.
11793     while (isa<DbgInfoIntrinsic>(BBI) ||
11794            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11795       if (BBI==OtherBB->begin())
11796         return false;
11797       --BBI;
11798     }
11799     // If this isn't a store, or isn't a store to the same location, bail out.
11800     OtherStore = dyn_cast<StoreInst>(BBI);
11801     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11802       return false;
11803   } else {
11804     // Otherwise, the other block ended with a conditional branch. If one of the
11805     // destinations is StoreBB, then we have the if/then case.
11806     if (OtherBr->getSuccessor(0) != StoreBB && 
11807         OtherBr->getSuccessor(1) != StoreBB)
11808       return false;
11809     
11810     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11811     // if/then triangle.  See if there is a store to the same ptr as SI that
11812     // lives in OtherBB.
11813     for (;; --BBI) {
11814       // Check to see if we find the matching store.
11815       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11816         if (OtherStore->getOperand(1) != SI.getOperand(1))
11817           return false;
11818         break;
11819       }
11820       // If we find something that may be using or overwriting the stored
11821       // value, or if we run out of instructions, we can't do the xform.
11822       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11823           BBI == OtherBB->begin())
11824         return false;
11825     }
11826     
11827     // In order to eliminate the store in OtherBr, we have to
11828     // make sure nothing reads or overwrites the stored value in
11829     // StoreBB.
11830     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11831       // FIXME: This should really be AA driven.
11832       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11833         return false;
11834     }
11835   }
11836   
11837   // Insert a PHI node now if we need it.
11838   Value *MergedVal = OtherStore->getOperand(0);
11839   if (MergedVal != SI.getOperand(0)) {
11840     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11841     PN->reserveOperandSpace(2);
11842     PN->addIncoming(SI.getOperand(0), SI.getParent());
11843     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11844     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11845   }
11846   
11847   // Advance to a place where it is safe to insert the new store and
11848   // insert it.
11849   BBI = DestBB->getFirstNonPHI();
11850   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11851                                     OtherStore->isVolatile()), *BBI);
11852   
11853   // Nuke the old stores.
11854   EraseInstFromFunction(SI);
11855   EraseInstFromFunction(*OtherStore);
11856   ++NumCombined;
11857   return true;
11858 }
11859
11860
11861 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11862   // Change br (not X), label True, label False to: br X, label False, True
11863   Value *X = 0;
11864   BasicBlock *TrueDest;
11865   BasicBlock *FalseDest;
11866   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11867       !isa<Constant>(X)) {
11868     // Swap Destinations and condition...
11869     BI.setCondition(X);
11870     BI.setSuccessor(0, FalseDest);
11871     BI.setSuccessor(1, TrueDest);
11872     return &BI;
11873   }
11874
11875   // Cannonicalize fcmp_one -> fcmp_oeq
11876   FCmpInst::Predicate FPred; Value *Y;
11877   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11878                              TrueDest, FalseDest)))
11879     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11880          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11881       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11882       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11883       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11884       NewSCC->takeName(I);
11885       // Swap Destinations and condition...
11886       BI.setCondition(NewSCC);
11887       BI.setSuccessor(0, FalseDest);
11888       BI.setSuccessor(1, TrueDest);
11889       RemoveFromWorkList(I);
11890       I->eraseFromParent();
11891       AddToWorkList(NewSCC);
11892       return &BI;
11893     }
11894
11895   // Cannonicalize icmp_ne -> icmp_eq
11896   ICmpInst::Predicate IPred;
11897   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11898                       TrueDest, FalseDest)))
11899     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11900          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11901          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11902       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11903       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11904       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11905       NewSCC->takeName(I);
11906       // Swap Destinations and condition...
11907       BI.setCondition(NewSCC);
11908       BI.setSuccessor(0, FalseDest);
11909       BI.setSuccessor(1, TrueDest);
11910       RemoveFromWorkList(I);
11911       I->eraseFromParent();;
11912       AddToWorkList(NewSCC);
11913       return &BI;
11914     }
11915
11916   return 0;
11917 }
11918
11919 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11920   Value *Cond = SI.getCondition();
11921   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11922     if (I->getOpcode() == Instruction::Add)
11923       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11924         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11925         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11926           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11927                                                 AddRHS));
11928         SI.setOperand(0, I->getOperand(0));
11929         AddToWorkList(I);
11930         return &SI;
11931       }
11932   }
11933   return 0;
11934 }
11935
11936 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11937   Value *Agg = EV.getAggregateOperand();
11938
11939   if (!EV.hasIndices())
11940     return ReplaceInstUsesWith(EV, Agg);
11941
11942   if (Constant *C = dyn_cast<Constant>(Agg)) {
11943     if (isa<UndefValue>(C))
11944       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11945       
11946     if (isa<ConstantAggregateZero>(C))
11947       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11948
11949     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11950       // Extract the element indexed by the first index out of the constant
11951       Value *V = C->getOperand(*EV.idx_begin());
11952       if (EV.getNumIndices() > 1)
11953         // Extract the remaining indices out of the constant indexed by the
11954         // first index
11955         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11956       else
11957         return ReplaceInstUsesWith(EV, V);
11958     }
11959     return 0; // Can't handle other constants
11960   } 
11961   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11962     // We're extracting from an insertvalue instruction, compare the indices
11963     const unsigned *exti, *exte, *insi, *inse;
11964     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11965          exte = EV.idx_end(), inse = IV->idx_end();
11966          exti != exte && insi != inse;
11967          ++exti, ++insi) {
11968       if (*insi != *exti)
11969         // The insert and extract both reference distinctly different elements.
11970         // This means the extract is not influenced by the insert, and we can
11971         // replace the aggregate operand of the extract with the aggregate
11972         // operand of the insert. i.e., replace
11973         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11974         // %E = extractvalue { i32, { i32 } } %I, 0
11975         // with
11976         // %E = extractvalue { i32, { i32 } } %A, 0
11977         return ExtractValueInst::Create(IV->getAggregateOperand(),
11978                                         EV.idx_begin(), EV.idx_end());
11979     }
11980     if (exti == exte && insi == inse)
11981       // Both iterators are at the end: Index lists are identical. Replace
11982       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11983       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11984       // with "i32 42"
11985       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11986     if (exti == exte) {
11987       // The extract list is a prefix of the insert list. i.e. replace
11988       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11989       // %E = extractvalue { i32, { i32 } } %I, 1
11990       // with
11991       // %X = extractvalue { i32, { i32 } } %A, 1
11992       // %E = insertvalue { i32 } %X, i32 42, 0
11993       // by switching the order of the insert and extract (though the
11994       // insertvalue should be left in, since it may have other uses).
11995       Value *NewEV = InsertNewInstBefore(
11996         ExtractValueInst::Create(IV->getAggregateOperand(),
11997                                  EV.idx_begin(), EV.idx_end()),
11998         EV);
11999       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12000                                      insi, inse);
12001     }
12002     if (insi == inse)
12003       // The insert list is a prefix of the extract list
12004       // We can simply remove the common indices from the extract and make it
12005       // operate on the inserted value instead of the insertvalue result.
12006       // i.e., replace
12007       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12008       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12009       // with
12010       // %E extractvalue { i32 } { i32 42 }, 0
12011       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12012                                       exti, exte);
12013   }
12014   // Can't simplify extracts from other values. Note that nested extracts are
12015   // already simplified implicitely by the above (extract ( extract (insert) )
12016   // will be translated into extract ( insert ( extract ) ) first and then just
12017   // the value inserted, if appropriate).
12018   return 0;
12019 }
12020
12021 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12022 /// is to leave as a vector operation.
12023 static bool CheapToScalarize(Value *V, bool isConstant) {
12024   if (isa<ConstantAggregateZero>(V)) 
12025     return true;
12026   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12027     if (isConstant) return true;
12028     // If all elts are the same, we can extract.
12029     Constant *Op0 = C->getOperand(0);
12030     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12031       if (C->getOperand(i) != Op0)
12032         return false;
12033     return true;
12034   }
12035   Instruction *I = dyn_cast<Instruction>(V);
12036   if (!I) return false;
12037   
12038   // Insert element gets simplified to the inserted element or is deleted if
12039   // this is constant idx extract element and its a constant idx insertelt.
12040   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12041       isa<ConstantInt>(I->getOperand(2)))
12042     return true;
12043   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12044     return true;
12045   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12046     if (BO->hasOneUse() &&
12047         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12048          CheapToScalarize(BO->getOperand(1), isConstant)))
12049       return true;
12050   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12051     if (CI->hasOneUse() &&
12052         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12053          CheapToScalarize(CI->getOperand(1), isConstant)))
12054       return true;
12055   
12056   return false;
12057 }
12058
12059 /// Read and decode a shufflevector mask.
12060 ///
12061 /// It turns undef elements into values that are larger than the number of
12062 /// elements in the input.
12063 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12064   unsigned NElts = SVI->getType()->getNumElements();
12065   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12066     return std::vector<unsigned>(NElts, 0);
12067   if (isa<UndefValue>(SVI->getOperand(2)))
12068     return std::vector<unsigned>(NElts, 2*NElts);
12069
12070   std::vector<unsigned> Result;
12071   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12072   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12073     if (isa<UndefValue>(*i))
12074       Result.push_back(NElts*2);  // undef -> 8
12075     else
12076       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12077   return Result;
12078 }
12079
12080 /// FindScalarElement - Given a vector and an element number, see if the scalar
12081 /// value is already around as a register, for example if it were inserted then
12082 /// extracted from the vector.
12083 static Value *FindScalarElement(Value *V, unsigned EltNo) {
12084   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12085   const VectorType *PTy = cast<VectorType>(V->getType());
12086   unsigned Width = PTy->getNumElements();
12087   if (EltNo >= Width)  // Out of range access.
12088     return UndefValue::get(PTy->getElementType());
12089   
12090   if (isa<UndefValue>(V))
12091     return UndefValue::get(PTy->getElementType());
12092   else if (isa<ConstantAggregateZero>(V))
12093     return Constant::getNullValue(PTy->getElementType());
12094   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12095     return CP->getOperand(EltNo);
12096   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12097     // If this is an insert to a variable element, we don't know what it is.
12098     if (!isa<ConstantInt>(III->getOperand(2))) 
12099       return 0;
12100     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12101     
12102     // If this is an insert to the element we are looking for, return the
12103     // inserted value.
12104     if (EltNo == IIElt) 
12105       return III->getOperand(1);
12106     
12107     // Otherwise, the insertelement doesn't modify the value, recurse on its
12108     // vector input.
12109     return FindScalarElement(III->getOperand(0), EltNo);
12110   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12111     unsigned LHSWidth =
12112       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12113     unsigned InEl = getShuffleMask(SVI)[EltNo];
12114     if (InEl < LHSWidth)
12115       return FindScalarElement(SVI->getOperand(0), InEl);
12116     else if (InEl < LHSWidth*2)
12117       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
12118     else
12119       return UndefValue::get(PTy->getElementType());
12120   }
12121   
12122   // Otherwise, we don't know.
12123   return 0;
12124 }
12125
12126 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12127   // If vector val is undef, replace extract with scalar undef.
12128   if (isa<UndefValue>(EI.getOperand(0)))
12129     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12130
12131   // If vector val is constant 0, replace extract with scalar 0.
12132   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12133     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12134   
12135   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12136     // If vector val is constant with all elements the same, replace EI with
12137     // that element. When the elements are not identical, we cannot replace yet
12138     // (we do that below, but only when the index is constant).
12139     Constant *op0 = C->getOperand(0);
12140     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12141       if (C->getOperand(i) != op0) {
12142         op0 = 0; 
12143         break;
12144       }
12145     if (op0)
12146       return ReplaceInstUsesWith(EI, op0);
12147   }
12148   
12149   // If extracting a specified index from the vector, see if we can recursively
12150   // find a previously computed scalar that was inserted into the vector.
12151   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12152     unsigned IndexVal = IdxC->getZExtValue();
12153     unsigned VectorWidth = 
12154       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12155       
12156     // If this is extracting an invalid index, turn this into undef, to avoid
12157     // crashing the code below.
12158     if (IndexVal >= VectorWidth)
12159       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12160     
12161     // This instruction only demands the single element from the input vector.
12162     // If the input vector has a single use, simplify it based on this use
12163     // property.
12164     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12165       APInt UndefElts(VectorWidth, 0);
12166       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12167       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12168                                                 DemandedMask, UndefElts)) {
12169         EI.setOperand(0, V);
12170         return &EI;
12171       }
12172     }
12173     
12174     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
12175       return ReplaceInstUsesWith(EI, Elt);
12176     
12177     // If the this extractelement is directly using a bitcast from a vector of
12178     // the same number of elements, see if we can find the source element from
12179     // it.  In this case, we will end up needing to bitcast the scalars.
12180     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12181       if (const VectorType *VT = 
12182               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12183         if (VT->getNumElements() == VectorWidth)
12184           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12185             return new BitCastInst(Elt, EI.getType());
12186     }
12187   }
12188   
12189   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12190     if (I->hasOneUse()) {
12191       // Push extractelement into predecessor operation if legal and
12192       // profitable to do so
12193       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12194         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12195         if (CheapToScalarize(BO, isConstantElt)) {
12196           ExtractElementInst *newEI0 = 
12197             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12198                                    EI.getName()+".lhs");
12199           ExtractElementInst *newEI1 =
12200             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12201                                    EI.getName()+".rhs");
12202           InsertNewInstBefore(newEI0, EI);
12203           InsertNewInstBefore(newEI1, EI);
12204           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12205         }
12206       } else if (isa<LoadInst>(I)) {
12207         unsigned AS = 
12208           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12209         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12210                                          PointerType::get(EI.getType(), AS),EI);
12211         GetElementPtrInst *GEP =
12212           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12213         InsertNewInstBefore(GEP, EI);
12214         return new LoadInst(GEP);
12215       }
12216     }
12217     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12218       // Extracting the inserted element?
12219       if (IE->getOperand(2) == EI.getOperand(1))
12220         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12221       // If the inserted and extracted elements are constants, they must not
12222       // be the same value, extract from the pre-inserted value instead.
12223       if (isa<Constant>(IE->getOperand(2)) &&
12224           isa<Constant>(EI.getOperand(1))) {
12225         AddUsesToWorkList(EI);
12226         EI.setOperand(0, IE->getOperand(0));
12227         return &EI;
12228       }
12229     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12230       // If this is extracting an element from a shufflevector, figure out where
12231       // it came from and extract from the appropriate input element instead.
12232       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12233         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12234         Value *Src;
12235         unsigned LHSWidth =
12236           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12237
12238         if (SrcIdx < LHSWidth)
12239           Src = SVI->getOperand(0);
12240         else if (SrcIdx < LHSWidth*2) {
12241           SrcIdx -= LHSWidth;
12242           Src = SVI->getOperand(1);
12243         } else {
12244           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12245         }
12246         return new ExtractElementInst(Src, SrcIdx);
12247       }
12248     }
12249   }
12250   return 0;
12251 }
12252
12253 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12254 /// elements from either LHS or RHS, return the shuffle mask and true. 
12255 /// Otherwise, return false.
12256 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12257                                          std::vector<Constant*> &Mask) {
12258   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12259          "Invalid CollectSingleShuffleElements");
12260   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12261
12262   if (isa<UndefValue>(V)) {
12263     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12264     return true;
12265   } else if (V == LHS) {
12266     for (unsigned i = 0; i != NumElts; ++i)
12267       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12268     return true;
12269   } else if (V == RHS) {
12270     for (unsigned i = 0; i != NumElts; ++i)
12271       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12272     return true;
12273   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12274     // If this is an insert of an extract from some other vector, include it.
12275     Value *VecOp    = IEI->getOperand(0);
12276     Value *ScalarOp = IEI->getOperand(1);
12277     Value *IdxOp    = IEI->getOperand(2);
12278     
12279     if (!isa<ConstantInt>(IdxOp))
12280       return false;
12281     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12282     
12283     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12284       // Okay, we can handle this if the vector we are insertinting into is
12285       // transitively ok.
12286       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12287         // If so, update the mask to reflect the inserted undef.
12288         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12289         return true;
12290       }      
12291     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12292       if (isa<ConstantInt>(EI->getOperand(1)) &&
12293           EI->getOperand(0)->getType() == V->getType()) {
12294         unsigned ExtractedIdx =
12295           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12296         
12297         // This must be extracting from either LHS or RHS.
12298         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12299           // Okay, we can handle this if the vector we are insertinting into is
12300           // transitively ok.
12301           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12302             // If so, update the mask to reflect the inserted value.
12303             if (EI->getOperand(0) == LHS) {
12304               Mask[InsertedIdx % NumElts] = 
12305                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12306             } else {
12307               assert(EI->getOperand(0) == RHS);
12308               Mask[InsertedIdx % NumElts] = 
12309                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12310               
12311             }
12312             return true;
12313           }
12314         }
12315       }
12316     }
12317   }
12318   // TODO: Handle shufflevector here!
12319   
12320   return false;
12321 }
12322
12323 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12324 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12325 /// that computes V and the LHS value of the shuffle.
12326 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12327                                      Value *&RHS) {
12328   assert(isa<VectorType>(V->getType()) && 
12329          (RHS == 0 || V->getType() == RHS->getType()) &&
12330          "Invalid shuffle!");
12331   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12332
12333   if (isa<UndefValue>(V)) {
12334     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12335     return V;
12336   } else if (isa<ConstantAggregateZero>(V)) {
12337     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12338     return V;
12339   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12340     // If this is an insert of an extract from some other vector, include it.
12341     Value *VecOp    = IEI->getOperand(0);
12342     Value *ScalarOp = IEI->getOperand(1);
12343     Value *IdxOp    = IEI->getOperand(2);
12344     
12345     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12346       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12347           EI->getOperand(0)->getType() == V->getType()) {
12348         unsigned ExtractedIdx =
12349           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12350         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12351         
12352         // Either the extracted from or inserted into vector must be RHSVec,
12353         // otherwise we'd end up with a shuffle of three inputs.
12354         if (EI->getOperand(0) == RHS || RHS == 0) {
12355           RHS = EI->getOperand(0);
12356           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
12357           Mask[InsertedIdx % NumElts] = 
12358             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12359           return V;
12360         }
12361         
12362         if (VecOp == RHS) {
12363           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
12364           // Everything but the extracted element is replaced with the RHS.
12365           for (unsigned i = 0; i != NumElts; ++i) {
12366             if (i != InsertedIdx)
12367               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12368           }
12369           return V;
12370         }
12371         
12372         // If this insertelement is a chain that comes from exactly these two
12373         // vectors, return the vector and the effective shuffle.
12374         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12375           return EI->getOperand(0);
12376         
12377       }
12378     }
12379   }
12380   // TODO: Handle shufflevector here!
12381   
12382   // Otherwise, can't do anything fancy.  Return an identity vector.
12383   for (unsigned i = 0; i != NumElts; ++i)
12384     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12385   return V;
12386 }
12387
12388 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12389   Value *VecOp    = IE.getOperand(0);
12390   Value *ScalarOp = IE.getOperand(1);
12391   Value *IdxOp    = IE.getOperand(2);
12392   
12393   // Inserting an undef or into an undefined place, remove this.
12394   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12395     ReplaceInstUsesWith(IE, VecOp);
12396   
12397   // If the inserted element was extracted from some other vector, and if the 
12398   // indexes are constant, try to turn this into a shufflevector operation.
12399   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12400     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12401         EI->getOperand(0)->getType() == IE.getType()) {
12402       unsigned NumVectorElts = IE.getType()->getNumElements();
12403       unsigned ExtractedIdx =
12404         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12405       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12406       
12407       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12408         return ReplaceInstUsesWith(IE, VecOp);
12409       
12410       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12411         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12412       
12413       // If we are extracting a value from a vector, then inserting it right
12414       // back into the same place, just use the input vector.
12415       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12416         return ReplaceInstUsesWith(IE, VecOp);      
12417       
12418       // We could theoretically do this for ANY input.  However, doing so could
12419       // turn chains of insertelement instructions into a chain of shufflevector
12420       // instructions, and right now we do not merge shufflevectors.  As such,
12421       // only do this in a situation where it is clear that there is benefit.
12422       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12423         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12424         // the values of VecOp, except then one read from EIOp0.
12425         // Build a new shuffle mask.
12426         std::vector<Constant*> Mask;
12427         if (isa<UndefValue>(VecOp))
12428           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12429         else {
12430           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12431           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12432                                                        NumVectorElts));
12433         } 
12434         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12435         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12436                                      ConstantVector::get(Mask));
12437       }
12438       
12439       // If this insertelement isn't used by some other insertelement, turn it
12440       // (and any insertelements it points to), into one big shuffle.
12441       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12442         std::vector<Constant*> Mask;
12443         Value *RHS = 0;
12444         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12445         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12446         // We now have a shuffle of LHS, RHS, Mask.
12447         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12448       }
12449     }
12450   }
12451
12452   return 0;
12453 }
12454
12455
12456 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12457   Value *LHS = SVI.getOperand(0);
12458   Value *RHS = SVI.getOperand(1);
12459   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12460
12461   bool MadeChange = false;
12462
12463   // Undefined shuffle mask -> undefined value.
12464   if (isa<UndefValue>(SVI.getOperand(2)))
12465     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12466
12467   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12468
12469   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12470     return 0;
12471
12472   APInt UndefElts(VWidth, 0);
12473   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12474   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12475     LHS = SVI.getOperand(0);
12476     RHS = SVI.getOperand(1);
12477     MadeChange = true;
12478   }
12479   
12480   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12481   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12482   if (LHS == RHS || isa<UndefValue>(LHS)) {
12483     if (isa<UndefValue>(LHS) && LHS == RHS) {
12484       // shuffle(undef,undef,mask) -> undef.
12485       return ReplaceInstUsesWith(SVI, LHS);
12486     }
12487     
12488     // Remap any references to RHS to use LHS.
12489     std::vector<Constant*> Elts;
12490     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12491       if (Mask[i] >= 2*e)
12492         Elts.push_back(UndefValue::get(Type::Int32Ty));
12493       else {
12494         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12495             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12496           Mask[i] = 2*e;     // Turn into undef.
12497           Elts.push_back(UndefValue::get(Type::Int32Ty));
12498         } else {
12499           Mask[i] = Mask[i] % e;  // Force to LHS.
12500           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12501         }
12502       }
12503     }
12504     SVI.setOperand(0, SVI.getOperand(1));
12505     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12506     SVI.setOperand(2, ConstantVector::get(Elts));
12507     LHS = SVI.getOperand(0);
12508     RHS = SVI.getOperand(1);
12509     MadeChange = true;
12510   }
12511   
12512   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12513   bool isLHSID = true, isRHSID = true;
12514     
12515   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12516     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12517     // Is this an identity shuffle of the LHS value?
12518     isLHSID &= (Mask[i] == i);
12519       
12520     // Is this an identity shuffle of the RHS value?
12521     isRHSID &= (Mask[i]-e == i);
12522   }
12523
12524   // Eliminate identity shuffles.
12525   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12526   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12527   
12528   // If the LHS is a shufflevector itself, see if we can combine it with this
12529   // one without producing an unusual shuffle.  Here we are really conservative:
12530   // we are absolutely afraid of producing a shuffle mask not in the input
12531   // program, because the code gen may not be smart enough to turn a merged
12532   // shuffle into two specific shuffles: it may produce worse code.  As such,
12533   // we only merge two shuffles if the result is one of the two input shuffle
12534   // masks.  In this case, merging the shuffles just removes one instruction,
12535   // which we know is safe.  This is good for things like turning:
12536   // (splat(splat)) -> splat.
12537   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12538     if (isa<UndefValue>(RHS)) {
12539       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12540
12541       std::vector<unsigned> NewMask;
12542       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12543         if (Mask[i] >= 2*e)
12544           NewMask.push_back(2*e);
12545         else
12546           NewMask.push_back(LHSMask[Mask[i]]);
12547       
12548       // If the result mask is equal to the src shuffle or this shuffle mask, do
12549       // the replacement.
12550       if (NewMask == LHSMask || NewMask == Mask) {
12551         unsigned LHSInNElts =
12552           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12553         std::vector<Constant*> Elts;
12554         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12555           if (NewMask[i] >= LHSInNElts*2) {
12556             Elts.push_back(UndefValue::get(Type::Int32Ty));
12557           } else {
12558             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12559           }
12560         }
12561         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12562                                      LHSSVI->getOperand(1),
12563                                      ConstantVector::get(Elts));
12564       }
12565     }
12566   }
12567
12568   return MadeChange ? &SVI : 0;
12569 }
12570
12571
12572
12573
12574 /// TryToSinkInstruction - Try to move the specified instruction from its
12575 /// current block into the beginning of DestBlock, which can only happen if it's
12576 /// safe to move the instruction past all of the instructions between it and the
12577 /// end of its block.
12578 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12579   assert(I->hasOneUse() && "Invariants didn't hold!");
12580
12581   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12582   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12583     return false;
12584
12585   // Do not sink alloca instructions out of the entry block.
12586   if (isa<AllocaInst>(I) && I->getParent() ==
12587         &DestBlock->getParent()->getEntryBlock())
12588     return false;
12589
12590   // We can only sink load instructions if there is nothing between the load and
12591   // the end of block that could change the value.
12592   if (I->mayReadFromMemory()) {
12593     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12594          Scan != E; ++Scan)
12595       if (Scan->mayWriteToMemory())
12596         return false;
12597   }
12598
12599   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12600
12601   CopyPrecedingStopPoint(I, InsertPos);
12602   I->moveBefore(InsertPos);
12603   ++NumSunkInst;
12604   return true;
12605 }
12606
12607
12608 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12609 /// all reachable code to the worklist.
12610 ///
12611 /// This has a couple of tricks to make the code faster and more powerful.  In
12612 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12613 /// them to the worklist (this significantly speeds up instcombine on code where
12614 /// many instructions are dead or constant).  Additionally, if we find a branch
12615 /// whose condition is a known constant, we only visit the reachable successors.
12616 ///
12617 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12618                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12619                                        InstCombiner &IC,
12620                                        const TargetData *TD) {
12621   SmallVector<BasicBlock*, 256> Worklist;
12622   Worklist.push_back(BB);
12623
12624   while (!Worklist.empty()) {
12625     BB = Worklist.back();
12626     Worklist.pop_back();
12627     
12628     // We have now visited this block!  If we've already been here, ignore it.
12629     if (!Visited.insert(BB)) continue;
12630
12631     DbgInfoIntrinsic *DBI_Prev = NULL;
12632     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12633       Instruction *Inst = BBI++;
12634       
12635       // DCE instruction if trivially dead.
12636       if (isInstructionTriviallyDead(Inst)) {
12637         ++NumDeadInst;
12638         DOUT << "IC: DCE: " << *Inst;
12639         Inst->eraseFromParent();
12640         continue;
12641       }
12642       
12643       // ConstantProp instruction if trivially constant.
12644       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12645         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12646         Inst->replaceAllUsesWith(C);
12647         ++NumConstProp;
12648         Inst->eraseFromParent();
12649         continue;
12650       }
12651      
12652       // If there are two consecutive llvm.dbg.stoppoint calls then
12653       // it is likely that the optimizer deleted code in between these
12654       // two intrinsics. 
12655       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12656       if (DBI_Next) {
12657         if (DBI_Prev
12658             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12659             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12660           IC.RemoveFromWorkList(DBI_Prev);
12661           DBI_Prev->eraseFromParent();
12662         }
12663         DBI_Prev = DBI_Next;
12664       } else {
12665         DBI_Prev = 0;
12666       }
12667
12668       IC.AddToWorkList(Inst);
12669     }
12670
12671     // Recursively visit successors.  If this is a branch or switch on a
12672     // constant, only visit the reachable successor.
12673     TerminatorInst *TI = BB->getTerminator();
12674     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12675       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12676         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12677         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12678         Worklist.push_back(ReachableBB);
12679         continue;
12680       }
12681     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12682       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12683         // See if this is an explicit destination.
12684         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12685           if (SI->getCaseValue(i) == Cond) {
12686             BasicBlock *ReachableBB = SI->getSuccessor(i);
12687             Worklist.push_back(ReachableBB);
12688             continue;
12689           }
12690         
12691         // Otherwise it is the default destination.
12692         Worklist.push_back(SI->getSuccessor(0));
12693         continue;
12694       }
12695     }
12696     
12697     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12698       Worklist.push_back(TI->getSuccessor(i));
12699   }
12700 }
12701
12702 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12703   bool Changed = false;
12704   TD = &getAnalysis<TargetData>();
12705   
12706   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12707              << F.getNameStr() << "\n");
12708
12709   {
12710     // Do a depth-first traversal of the function, populate the worklist with
12711     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12712     // track of which blocks we visit.
12713     SmallPtrSet<BasicBlock*, 64> Visited;
12714     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12715
12716     // Do a quick scan over the function.  If we find any blocks that are
12717     // unreachable, remove any instructions inside of them.  This prevents
12718     // the instcombine code from having to deal with some bad special cases.
12719     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12720       if (!Visited.count(BB)) {
12721         Instruction *Term = BB->getTerminator();
12722         while (Term != BB->begin()) {   // Remove instrs bottom-up
12723           BasicBlock::iterator I = Term; --I;
12724
12725           DOUT << "IC: DCE: " << *I;
12726           // A debug intrinsic shouldn't force another iteration if we weren't
12727           // going to do one without it.
12728           if (!isa<DbgInfoIntrinsic>(I)) {
12729             ++NumDeadInst;
12730             Changed = true;
12731           }
12732           if (!I->use_empty())
12733             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12734           I->eraseFromParent();
12735         }
12736       }
12737   }
12738
12739   while (!Worklist.empty()) {
12740     Instruction *I = RemoveOneFromWorkList();
12741     if (I == 0) continue;  // skip null values.
12742
12743     // Check to see if we can DCE the instruction.
12744     if (isInstructionTriviallyDead(I)) {
12745       // Add operands to the worklist.
12746       if (I->getNumOperands() < 4)
12747         AddUsesToWorkList(*I);
12748       ++NumDeadInst;
12749
12750       DOUT << "IC: DCE: " << *I;
12751
12752       I->eraseFromParent();
12753       RemoveFromWorkList(I);
12754       Changed = true;
12755       continue;
12756     }
12757
12758     // Instruction isn't dead, see if we can constant propagate it.
12759     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12760       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12761
12762       // Add operands to the worklist.
12763       AddUsesToWorkList(*I);
12764       ReplaceInstUsesWith(*I, C);
12765
12766       ++NumConstProp;
12767       I->eraseFromParent();
12768       RemoveFromWorkList(I);
12769       Changed = true;
12770       continue;
12771     }
12772
12773     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12774       // See if we can constant fold its operands.
12775       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12776         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12777           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12778             if (NewC != CE) {
12779               i->set(NewC);
12780               Changed = true;
12781             }
12782     }
12783
12784     // See if we can trivially sink this instruction to a successor basic block.
12785     if (I->hasOneUse()) {
12786       BasicBlock *BB = I->getParent();
12787       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12788       if (UserParent != BB) {
12789         bool UserIsSuccessor = false;
12790         // See if the user is one of our successors.
12791         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12792           if (*SI == UserParent) {
12793             UserIsSuccessor = true;
12794             break;
12795           }
12796
12797         // If the user is one of our immediate successors, and if that successor
12798         // only has us as a predecessors (we'd have to split the critical edge
12799         // otherwise), we can keep going.
12800         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12801             next(pred_begin(UserParent)) == pred_end(UserParent))
12802           // Okay, the CFG is simple enough, try to sink this instruction.
12803           Changed |= TryToSinkInstruction(I, UserParent);
12804       }
12805     }
12806
12807     // Now that we have an instruction, try combining it to simplify it...
12808 #ifndef NDEBUG
12809     std::string OrigI;
12810 #endif
12811     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12812     if (Instruction *Result = visit(*I)) {
12813       ++NumCombined;
12814       // Should we replace the old instruction with a new one?
12815       if (Result != I) {
12816         DOUT << "IC: Old = " << *I
12817              << "    New = " << *Result;
12818
12819         // Everything uses the new instruction now.
12820         I->replaceAllUsesWith(Result);
12821
12822         // Push the new instruction and any users onto the worklist.
12823         AddToWorkList(Result);
12824         AddUsersToWorkList(*Result);
12825
12826         // Move the name to the new instruction first.
12827         Result->takeName(I);
12828
12829         // Insert the new instruction into the basic block...
12830         BasicBlock *InstParent = I->getParent();
12831         BasicBlock::iterator InsertPos = I;
12832
12833         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12834           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12835             ++InsertPos;
12836
12837         InstParent->getInstList().insert(InsertPos, Result);
12838
12839         // Make sure that we reprocess all operands now that we reduced their
12840         // use counts.
12841         AddUsesToWorkList(*I);
12842
12843         // Instructions can end up on the worklist more than once.  Make sure
12844         // we do not process an instruction that has been deleted.
12845         RemoveFromWorkList(I);
12846
12847         // Erase the old instruction.
12848         InstParent->getInstList().erase(I);
12849       } else {
12850 #ifndef NDEBUG
12851         DOUT << "IC: Mod = " << OrigI
12852              << "    New = " << *I;
12853 #endif
12854
12855         // If the instruction was modified, it's possible that it is now dead.
12856         // if so, remove it.
12857         if (isInstructionTriviallyDead(I)) {
12858           // Make sure we process all operands now that we are reducing their
12859           // use counts.
12860           AddUsesToWorkList(*I);
12861
12862           // Instructions may end up in the worklist more than once.  Erase all
12863           // occurrences of this instruction.
12864           RemoveFromWorkList(I);
12865           I->eraseFromParent();
12866         } else {
12867           AddToWorkList(I);
12868           AddUsersToWorkList(*I);
12869         }
12870       }
12871       Changed = true;
12872     }
12873   }
12874
12875   assert(WorklistMap.empty() && "Worklist empty, but map not?");
12876     
12877   // Do an explicit clear, this shrinks the map if needed.
12878   WorklistMap.clear();
12879   return Changed;
12880 }
12881
12882
12883 bool InstCombiner::runOnFunction(Function &F) {
12884   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12885   
12886   bool EverMadeChange = false;
12887
12888   // Iterate while there is work to do.
12889   unsigned Iteration = 0;
12890   while (DoOneIteration(F, Iteration++))
12891     EverMadeChange = true;
12892   return EverMadeChange;
12893 }
12894
12895 FunctionPass *llvm::createInstructionCombiningPass() {
12896   return new InstCombiner();
12897 }