Make special cases (0 inf nan) work for frem.
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include <algorithm>
61 #include <climits>
62 #include <sstream>
63 using namespace llvm;
64 using namespace llvm::PatternMatch;
65
66 STATISTIC(NumCombined , "Number of insts combined");
67 STATISTIC(NumConstProp, "Number of constant folds");
68 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72 namespace {
73   class VISIBILITY_HIDDEN InstCombiner
74     : public FunctionPass,
75       public InstVisitor<InstCombiner, Instruction*> {
76     // Worklist of all of the instructions that need to be simplified.
77     SmallVector<Instruction*, 256> Worklist;
78     DenseMap<Instruction*, unsigned> WorklistMap;
79     TargetData *TD;
80     bool MustPreserveLCSSA;
81   public:
82     static char ID; // Pass identification, replacement for typeid
83     InstCombiner() : FunctionPass(&ID) {}
84
85     /// AddToWorkList - Add the specified instruction to the worklist if it
86     /// isn't already in it.
87     void AddToWorkList(Instruction *I) {
88       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
89         Worklist.push_back(I);
90     }
91     
92     // RemoveFromWorkList - remove I from the worklist if it exists.
93     void RemoveFromWorkList(Instruction *I) {
94       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95       if (It == WorklistMap.end()) return; // Not in worklist.
96       
97       // Don't bother moving everything down, just null out the slot.
98       Worklist[It->second] = 0;
99       
100       WorklistMap.erase(It);
101     }
102     
103     Instruction *RemoveOneFromWorkList() {
104       Instruction *I = Worklist.back();
105       Worklist.pop_back();
106       WorklistMap.erase(I);
107       return I;
108     }
109
110     
111     /// AddUsersToWorkList - When an instruction is simplified, add all users of
112     /// the instruction to the work lists because they might get more simplified
113     /// now.
114     ///
115     void AddUsersToWorkList(Value &I) {
116       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117            UI != UE; ++UI)
118         AddToWorkList(cast<Instruction>(*UI));
119     }
120
121     /// AddUsesToWorkList - When an instruction is simplified, add operands to
122     /// the work lists because they might get more simplified now.
123     ///
124     void AddUsesToWorkList(Instruction &I) {
125       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126         if (Instruction *Op = dyn_cast<Instruction>(*i))
127           AddToWorkList(Op);
128     }
129     
130     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131     /// dead.  Add all of its operands to the worklist, turning them into
132     /// undef's to reduce the number of uses of those instructions.
133     ///
134     /// Return the specified operand before it is turned into an undef.
135     ///
136     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137       Value *R = I.getOperand(op);
138       
139       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
141           AddToWorkList(Op);
142           // Set the operand to undef to drop the use.
143           *i = UndefValue::get(Op->getType());
144         }
145       
146       return R;
147     }
148
149   public:
150     virtual bool runOnFunction(Function &F);
151     
152     bool DoOneIteration(Function &F, unsigned ItNum);
153
154     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155       AU.addRequired<TargetData>();
156       AU.addPreservedID(LCSSAID);
157       AU.setPreservesCFG();
158     }
159
160     TargetData &getTargetData() const { return *TD; }
161
162     // Visitation implementation - Implement instruction combining for different
163     // instruction types.  The semantics are as follows:
164     // Return Value:
165     //    null        - No change was made
166     //     I          - Change was made, I is still valid, I may be dead though
167     //   otherwise    - Change was made, replace I with returned instruction
168     //
169     Instruction *visitAdd(BinaryOperator &I);
170     Instruction *visitSub(BinaryOperator &I);
171     Instruction *visitMul(BinaryOperator &I);
172     Instruction *visitURem(BinaryOperator &I);
173     Instruction *visitSRem(BinaryOperator &I);
174     Instruction *visitFRem(BinaryOperator &I);
175     bool SimplifyDivRemOfSelect(BinaryOperator &I);
176     Instruction *commonRemTransforms(BinaryOperator &I);
177     Instruction *commonIRemTransforms(BinaryOperator &I);
178     Instruction *commonDivTransforms(BinaryOperator &I);
179     Instruction *commonIDivTransforms(BinaryOperator &I);
180     Instruction *visitUDiv(BinaryOperator &I);
181     Instruction *visitSDiv(BinaryOperator &I);
182     Instruction *visitFDiv(BinaryOperator &I);
183     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
184     Instruction *visitAnd(BinaryOperator &I);
185     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
186     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
187                                      Value *A, Value *B, Value *C);
188     Instruction *visitOr (BinaryOperator &I);
189     Instruction *visitXor(BinaryOperator &I);
190     Instruction *visitShl(BinaryOperator &I);
191     Instruction *visitAShr(BinaryOperator &I);
192     Instruction *visitLShr(BinaryOperator &I);
193     Instruction *commonShiftTransforms(BinaryOperator &I);
194     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
195                                       Constant *RHSC);
196     Instruction *visitFCmpInst(FCmpInst &I);
197     Instruction *visitICmpInst(ICmpInst &I);
198     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
199     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
200                                                 Instruction *LHS,
201                                                 ConstantInt *RHS);
202     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
203                                 ConstantInt *DivRHS);
204
205     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
206                              ICmpInst::Predicate Cond, Instruction &I);
207     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
208                                      BinaryOperator &I);
209     Instruction *commonCastTransforms(CastInst &CI);
210     Instruction *commonIntCastTransforms(CastInst &CI);
211     Instruction *commonPointerCastTransforms(CastInst &CI);
212     Instruction *visitTrunc(TruncInst &CI);
213     Instruction *visitZExt(ZExtInst &CI);
214     Instruction *visitSExt(SExtInst &CI);
215     Instruction *visitFPTrunc(FPTruncInst &CI);
216     Instruction *visitFPExt(CastInst &CI);
217     Instruction *visitFPToUI(FPToUIInst &FI);
218     Instruction *visitFPToSI(FPToSIInst &FI);
219     Instruction *visitUIToFP(CastInst &CI);
220     Instruction *visitSIToFP(CastInst &CI);
221     Instruction *visitPtrToInt(CastInst &CI);
222     Instruction *visitIntToPtr(IntToPtrInst &CI);
223     Instruction *visitBitCast(BitCastInst &CI);
224     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
225                                 Instruction *FI);
226     Instruction *visitSelectInst(SelectInst &SI);
227     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
228     Instruction *visitCallInst(CallInst &CI);
229     Instruction *visitInvokeInst(InvokeInst &II);
230     Instruction *visitPHINode(PHINode &PN);
231     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
232     Instruction *visitAllocationInst(AllocationInst &AI);
233     Instruction *visitFreeInst(FreeInst &FI);
234     Instruction *visitLoadInst(LoadInst &LI);
235     Instruction *visitStoreInst(StoreInst &SI);
236     Instruction *visitBranchInst(BranchInst &BI);
237     Instruction *visitSwitchInst(SwitchInst &SI);
238     Instruction *visitInsertElementInst(InsertElementInst &IE);
239     Instruction *visitExtractElementInst(ExtractElementInst &EI);
240     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
241     Instruction *visitExtractValueInst(ExtractValueInst &EV);
242
243     // visitInstruction - Specify what to return for unhandled instructions...
244     Instruction *visitInstruction(Instruction &I) { return 0; }
245
246   private:
247     Instruction *visitCallSite(CallSite CS);
248     bool transformConstExprCastCall(CallSite CS);
249     Instruction *transformCallThroughTrampoline(CallSite CS);
250     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
251                                    bool DoXform = true);
252     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
253
254   public:
255     // InsertNewInstBefore - insert an instruction New before instruction Old
256     // in the program.  Add the new instruction to the worklist.
257     //
258     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
259       assert(New && New->getParent() == 0 &&
260              "New instruction already inserted into a basic block!");
261       BasicBlock *BB = Old.getParent();
262       BB->getInstList().insert(&Old, New);  // Insert inst
263       AddToWorkList(New);
264       return New;
265     }
266
267     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
268     /// This also adds the cast to the worklist.  Finally, this returns the
269     /// cast.
270     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
271                             Instruction &Pos) {
272       if (V->getType() == Ty) return V;
273
274       if (Constant *CV = dyn_cast<Constant>(V))
275         return ConstantExpr::getCast(opc, CV, Ty);
276       
277       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
278       AddToWorkList(C);
279       return C;
280     }
281         
282     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
283       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
284     }
285
286
287     // ReplaceInstUsesWith - This method is to be used when an instruction is
288     // found to be dead, replacable with another preexisting expression.  Here
289     // we add all uses of I to the worklist, replace all uses of I with the new
290     // value, then return I, so that the inst combiner will know that I was
291     // modified.
292     //
293     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
294       AddUsersToWorkList(I);         // Add all modified instrs to worklist
295       if (&I != V) {
296         I.replaceAllUsesWith(V);
297         return &I;
298       } else {
299         // If we are replacing the instruction with itself, this must be in a
300         // segment of unreachable code, so just clobber the instruction.
301         I.replaceAllUsesWith(UndefValue::get(I.getType()));
302         return &I;
303       }
304     }
305
306     // UpdateValueUsesWith - This method is to be used when an value is
307     // found to be replacable with another preexisting expression or was
308     // updated.  Here we add all uses of I to the worklist, replace all uses of
309     // I with the new value (unless the instruction was just updated), then
310     // return true, so that the inst combiner will know that I was modified.
311     //
312     bool UpdateValueUsesWith(Value *Old, Value *New) {
313       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
314       if (Old != New)
315         Old->replaceAllUsesWith(New);
316       if (Instruction *I = dyn_cast<Instruction>(Old))
317         AddToWorkList(I);
318       if (Instruction *I = dyn_cast<Instruction>(New))
319         AddToWorkList(I);
320       return true;
321     }
322     
323     // EraseInstFromFunction - When dealing with an instruction that has side
324     // effects or produces a void value, we can't rely on DCE to delete the
325     // instruction.  Instead, visit methods should return the value returned by
326     // this function.
327     Instruction *EraseInstFromFunction(Instruction &I) {
328       assert(I.use_empty() && "Cannot erase instruction that is used!");
329       AddUsesToWorkList(I);
330       RemoveFromWorkList(&I);
331       I.eraseFromParent();
332       return 0;  // Don't do anything with FI
333     }
334         
335     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
336                            APInt &KnownOne, unsigned Depth = 0) const {
337       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
338     }
339     
340     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
341                            unsigned Depth = 0) const {
342       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
343     }
344     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
345       return llvm::ComputeNumSignBits(Op, TD, Depth);
346     }
347
348   private:
349
350     /// SimplifyCommutative - This performs a few simplifications for 
351     /// commutative operators.
352     bool SimplifyCommutative(BinaryOperator &I);
353
354     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
355     /// most-complex to least-complex order.
356     bool SimplifyCompare(CmpInst &I);
357
358     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
359     /// on the demanded bits.
360     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
361                               APInt& KnownZero, APInt& KnownOne,
362                               unsigned Depth = 0);
363
364     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
365                                       uint64_t &UndefElts, unsigned Depth = 0);
366       
367     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
368     // PHI node as operand #0, see if we can fold the instruction into the PHI
369     // (which is only possible if all operands to the PHI are constants).
370     Instruction *FoldOpIntoPhi(Instruction &I);
371
372     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
373     // operator and they all are only used by the PHI, PHI together their
374     // inputs, and do the operation once, to the result of the PHI.
375     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
376     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
377     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
378
379     
380     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
382     
383     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
384                               bool isSub, Instruction &I);
385     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
386                                  bool isSigned, bool Inside, Instruction &IB);
387     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
388     Instruction *MatchBSwap(BinaryOperator &I);
389     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
390     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
391     Instruction *SimplifyMemSet(MemSetInst *MI);
392
393
394     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
395
396     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
397                                     unsigned CastOpc, int &NumCastsRemoved);
398     unsigned GetOrEnforceKnownAlignment(Value *V,
399                                         unsigned PrefAlign = 0);
400
401   };
402 }
403
404 char InstCombiner::ID = 0;
405 static RegisterPass<InstCombiner>
406 X("instcombine", "Combine redundant instructions");
407
408 // getComplexity:  Assign a complexity or rank value to LLVM Values...
409 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
410 static unsigned getComplexity(Value *V) {
411   if (isa<Instruction>(V)) {
412     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
413       return 3;
414     return 4;
415   }
416   if (isa<Argument>(V)) return 3;
417   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
418 }
419
420 // isOnlyUse - Return true if this instruction will be deleted if we stop using
421 // it.
422 static bool isOnlyUse(Value *V) {
423   return V->hasOneUse() || isa<Constant>(V);
424 }
425
426 // getPromotedType - Return the specified type promoted as it would be to pass
427 // though a va_arg area...
428 static const Type *getPromotedType(const Type *Ty) {
429   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
430     if (ITy->getBitWidth() < 32)
431       return Type::Int32Ty;
432   }
433   return Ty;
434 }
435
436 /// getBitCastOperand - If the specified operand is a CastInst, a constant
437 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
438 /// operand value, otherwise return null.
439 static Value *getBitCastOperand(Value *V) {
440   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
441     // BitCastInst?
442     return I->getOperand(0);
443   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
444     // GetElementPtrInst?
445     if (GEP->hasAllZeroIndices())
446       return GEP->getOperand(0);
447   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
448     if (CE->getOpcode() == Instruction::BitCast)
449       // BitCast ConstantExp?
450       return CE->getOperand(0);
451     else if (CE->getOpcode() == Instruction::GetElementPtr) {
452       // GetElementPtr ConstantExp?
453       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
454            I != E; ++I) {
455         ConstantInt *CI = dyn_cast<ConstantInt>(I);
456         if (!CI || !CI->isZero())
457           // Any non-zero indices? Not cast-like.
458           return 0;
459       }
460       // All-zero indices? This is just like casting.
461       return CE->getOperand(0);
462     }
463   }
464   return 0;
465 }
466
467 /// This function is a wrapper around CastInst::isEliminableCastPair. It
468 /// simply extracts arguments and returns what that function returns.
469 static Instruction::CastOps 
470 isEliminableCastPair(
471   const CastInst *CI, ///< The first cast instruction
472   unsigned opcode,       ///< The opcode of the second cast instruction
473   const Type *DstTy,     ///< The target type for the second cast instruction
474   TargetData *TD         ///< The target data for pointer size
475 ) {
476   
477   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
478   const Type *MidTy = CI->getType();                  // B from above
479
480   // Get the opcodes of the two Cast instructions
481   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
482   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
483
484   return Instruction::CastOps(
485       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
486                                      DstTy, TD->getIntPtrType()));
487 }
488
489 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
490 /// in any code being generated.  It does not require codegen if V is simple
491 /// enough or if the cast can be folded into other casts.
492 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
493                               const Type *Ty, TargetData *TD) {
494   if (V->getType() == Ty || isa<Constant>(V)) return false;
495   
496   // If this is another cast that can be eliminated, it isn't codegen either.
497   if (const CastInst *CI = dyn_cast<CastInst>(V))
498     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
499       return false;
500   return true;
501 }
502
503 // SimplifyCommutative - This performs a few simplifications for commutative
504 // operators:
505 //
506 //  1. Order operands such that they are listed from right (least complex) to
507 //     left (most complex).  This puts constants before unary operators before
508 //     binary operators.
509 //
510 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
511 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
512 //
513 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
514   bool Changed = false;
515   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
516     Changed = !I.swapOperands();
517
518   if (!I.isAssociative()) return Changed;
519   Instruction::BinaryOps Opcode = I.getOpcode();
520   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
521     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
522       if (isa<Constant>(I.getOperand(1))) {
523         Constant *Folded = ConstantExpr::get(I.getOpcode(),
524                                              cast<Constant>(I.getOperand(1)),
525                                              cast<Constant>(Op->getOperand(1)));
526         I.setOperand(0, Op->getOperand(0));
527         I.setOperand(1, Folded);
528         return true;
529       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
530         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
531             isOnlyUse(Op) && isOnlyUse(Op1)) {
532           Constant *C1 = cast<Constant>(Op->getOperand(1));
533           Constant *C2 = cast<Constant>(Op1->getOperand(1));
534
535           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
536           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
537           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
538                                                     Op1->getOperand(0),
539                                                     Op1->getName(), &I);
540           AddToWorkList(New);
541           I.setOperand(0, New);
542           I.setOperand(1, Folded);
543           return true;
544         }
545     }
546   return Changed;
547 }
548
549 /// SimplifyCompare - For a CmpInst this function just orders the operands
550 /// so that theyare listed from right (least complex) to left (most complex).
551 /// This puts constants before unary operators before binary operators.
552 bool InstCombiner::SimplifyCompare(CmpInst &I) {
553   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
554     return false;
555   I.swapOperands();
556   // Compare instructions are not associative so there's nothing else we can do.
557   return true;
558 }
559
560 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
561 // if the LHS is a constant zero (which is the 'negate' form).
562 //
563 static inline Value *dyn_castNegVal(Value *V) {
564   if (BinaryOperator::isNeg(V))
565     return BinaryOperator::getNegArgument(V);
566
567   // Constants can be considered to be negated values if they can be folded.
568   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
569     return ConstantExpr::getNeg(C);
570
571   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572     if (C->getType()->getElementType()->isInteger())
573       return ConstantExpr::getNeg(C);
574
575   return 0;
576 }
577
578 static inline Value *dyn_castNotVal(Value *V) {
579   if (BinaryOperator::isNot(V))
580     return BinaryOperator::getNotArgument(V);
581
582   // Constants can be considered to be not'ed values...
583   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
584     return ConstantInt::get(~C->getValue());
585   return 0;
586 }
587
588 // dyn_castFoldableMul - If this value is a multiply that can be folded into
589 // other computations (because it has a constant operand), return the
590 // non-constant operand of the multiply, and set CST to point to the multiplier.
591 // Otherwise, return null.
592 //
593 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
594   if (V->hasOneUse() && V->getType()->isInteger())
595     if (Instruction *I = dyn_cast<Instruction>(V)) {
596       if (I->getOpcode() == Instruction::Mul)
597         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
598           return I->getOperand(0);
599       if (I->getOpcode() == Instruction::Shl)
600         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
601           // The multiplier is really 1 << CST.
602           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
603           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
604           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
605           return I->getOperand(0);
606         }
607     }
608   return 0;
609 }
610
611 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
612 /// expression, return it.
613 static User *dyn_castGetElementPtr(Value *V) {
614   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
615   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
616     if (CE->getOpcode() == Instruction::GetElementPtr)
617       return cast<User>(V);
618   return false;
619 }
620
621 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
622 /// opcode value. Otherwise return UserOp1.
623 static unsigned getOpcode(const Value *V) {
624   if (const Instruction *I = dyn_cast<Instruction>(V))
625     return I->getOpcode();
626   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
627     return CE->getOpcode();
628   // Use UserOp1 to mean there's no opcode.
629   return Instruction::UserOp1;
630 }
631
632 /// AddOne - Add one to a ConstantInt
633 static ConstantInt *AddOne(ConstantInt *C) {
634   APInt Val(C->getValue());
635   return ConstantInt::get(++Val);
636 }
637 /// SubOne - Subtract one from a ConstantInt
638 static ConstantInt *SubOne(ConstantInt *C) {
639   APInt Val(C->getValue());
640   return ConstantInt::get(--Val);
641 }
642 /// Add - Add two ConstantInts together
643 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
644   return ConstantInt::get(C1->getValue() + C2->getValue());
645 }
646 /// And - Bitwise AND two ConstantInts together
647 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
648   return ConstantInt::get(C1->getValue() & C2->getValue());
649 }
650 /// Subtract - Subtract one ConstantInt from another
651 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
652   return ConstantInt::get(C1->getValue() - C2->getValue());
653 }
654 /// Multiply - Multiply two ConstantInts together
655 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
656   return ConstantInt::get(C1->getValue() * C2->getValue());
657 }
658 /// MultiplyOverflows - True if the multiply can not be expressed in an int
659 /// this size.
660 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
661   uint32_t W = C1->getBitWidth();
662   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
663   if (sign) {
664     LHSExt.sext(W * 2);
665     RHSExt.sext(W * 2);
666   } else {
667     LHSExt.zext(W * 2);
668     RHSExt.zext(W * 2);
669   }
670
671   APInt MulExt = LHSExt * RHSExt;
672
673   if (sign) {
674     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
675     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
676     return MulExt.slt(Min) || MulExt.sgt(Max);
677   } else 
678     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
679 }
680
681
682 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
683 /// specified instruction is a constant integer.  If so, check to see if there
684 /// are any bits set in the constant that are not demanded.  If so, shrink the
685 /// constant and return true.
686 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
687                                    APInt Demanded) {
688   assert(I && "No instruction?");
689   assert(OpNo < I->getNumOperands() && "Operand index too large");
690
691   // If the operand is not a constant integer, nothing to do.
692   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
693   if (!OpC) return false;
694
695   // If there are no bits set that aren't demanded, nothing to do.
696   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
697   if ((~Demanded & OpC->getValue()) == 0)
698     return false;
699
700   // This instruction is producing bits that are not demanded. Shrink the RHS.
701   Demanded &= OpC->getValue();
702   I->setOperand(OpNo, ConstantInt::get(Demanded));
703   return true;
704 }
705
706 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
707 // set of known zero and one bits, compute the maximum and minimum values that
708 // could have the specified known zero and known one bits, returning them in
709 // min/max.
710 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
711                                                    const APInt& KnownZero,
712                                                    const APInt& KnownOne,
713                                                    APInt& Min, APInt& Max) {
714   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
715   assert(KnownZero.getBitWidth() == BitWidth && 
716          KnownOne.getBitWidth() == BitWidth &&
717          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
718          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
719   APInt UnknownBits = ~(KnownZero|KnownOne);
720
721   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
722   // bit if it is unknown.
723   Min = KnownOne;
724   Max = KnownOne|UnknownBits;
725   
726   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
727     Min.set(BitWidth-1);
728     Max.clear(BitWidth-1);
729   }
730 }
731
732 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
733 // a set of known zero and one bits, compute the maximum and minimum values that
734 // could have the specified known zero and known one bits, returning them in
735 // min/max.
736 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
737                                                      const APInt &KnownZero,
738                                                      const APInt &KnownOne,
739                                                      APInt &Min, APInt &Max) {
740   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
741   assert(KnownZero.getBitWidth() == BitWidth && 
742          KnownOne.getBitWidth() == BitWidth &&
743          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
744          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
745   APInt UnknownBits = ~(KnownZero|KnownOne);
746   
747   // The minimum value is when the unknown bits are all zeros.
748   Min = KnownOne;
749   // The maximum value is when the unknown bits are all ones.
750   Max = KnownOne|UnknownBits;
751 }
752
753 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
754 /// value based on the demanded bits. When this function is called, it is known
755 /// that only the bits set in DemandedMask of the result of V are ever used
756 /// downstream. Consequently, depending on the mask and V, it may be possible
757 /// to replace V with a constant or one of its operands. In such cases, this
758 /// function does the replacement and returns true. In all other cases, it
759 /// returns false after analyzing the expression and setting KnownOne and known
760 /// to be one in the expression. KnownZero contains all the bits that are known
761 /// to be zero in the expression. These are provided to potentially allow the
762 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
763 /// the expression. KnownOne and KnownZero always follow the invariant that 
764 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
765 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
766 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
767 /// and KnownOne must all be the same.
768 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
769                                         APInt& KnownZero, APInt& KnownOne,
770                                         unsigned Depth) {
771   assert(V != 0 && "Null pointer of Value???");
772   assert(Depth <= 6 && "Limit Search Depth");
773   uint32_t BitWidth = DemandedMask.getBitWidth();
774   const IntegerType *VTy = cast<IntegerType>(V->getType());
775   assert(VTy->getBitWidth() == BitWidth && 
776          KnownZero.getBitWidth() == BitWidth && 
777          KnownOne.getBitWidth() == BitWidth &&
778          "Value *V, DemandedMask, KnownZero and KnownOne \
779           must have same BitWidth");
780   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
781     // We know all of the bits for a constant!
782     KnownOne = CI->getValue() & DemandedMask;
783     KnownZero = ~KnownOne & DemandedMask;
784     return false;
785   }
786   
787   KnownZero.clear(); 
788   KnownOne.clear();
789   if (!V->hasOneUse()) {    // Other users may use these bits.
790     if (Depth != 0) {       // Not at the root.
791       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
792       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
793       return false;
794     }
795     // If this is the root being simplified, allow it to have multiple uses,
796     // just set the DemandedMask to all bits.
797     DemandedMask = APInt::getAllOnesValue(BitWidth);
798   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
799     if (V != UndefValue::get(VTy))
800       return UpdateValueUsesWith(V, UndefValue::get(VTy));
801     return false;
802   } else if (Depth == 6) {        // Limit search depth.
803     return false;
804   }
805   
806   Instruction *I = dyn_cast<Instruction>(V);
807   if (!I) return false;        // Only analyze instructions.
808
809   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
810   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
811   switch (I->getOpcode()) {
812   default:
813     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
814     break;
815   case Instruction::And:
816     // If either the LHS or the RHS are Zero, the result is zero.
817     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
818                              RHSKnownZero, RHSKnownOne, Depth+1))
819       return true;
820     assert((RHSKnownZero & RHSKnownOne) == 0 && 
821            "Bits known to be one AND zero?"); 
822
823     // If something is known zero on the RHS, the bits aren't demanded on the
824     // LHS.
825     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
826                              LHSKnownZero, LHSKnownOne, Depth+1))
827       return true;
828     assert((LHSKnownZero & LHSKnownOne) == 0 && 
829            "Bits known to be one AND zero?"); 
830
831     // If all of the demanded bits are known 1 on one side, return the other.
832     // These bits cannot contribute to the result of the 'and'.
833     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
834         (DemandedMask & ~LHSKnownZero))
835       return UpdateValueUsesWith(I, I->getOperand(0));
836     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
837         (DemandedMask & ~RHSKnownZero))
838       return UpdateValueUsesWith(I, I->getOperand(1));
839     
840     // If all of the demanded bits in the inputs are known zeros, return zero.
841     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
842       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
843       
844     // If the RHS is a constant, see if we can simplify it.
845     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
846       return UpdateValueUsesWith(I, I);
847       
848     // Output known-1 bits are only known if set in both the LHS & RHS.
849     RHSKnownOne &= LHSKnownOne;
850     // Output known-0 are known to be clear if zero in either the LHS | RHS.
851     RHSKnownZero |= LHSKnownZero;
852     break;
853   case Instruction::Or:
854     // If either the LHS or the RHS are One, the result is One.
855     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
856                              RHSKnownZero, RHSKnownOne, Depth+1))
857       return true;
858     assert((RHSKnownZero & RHSKnownOne) == 0 && 
859            "Bits known to be one AND zero?"); 
860     // If something is known one on the RHS, the bits aren't demanded on the
861     // LHS.
862     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
863                              LHSKnownZero, LHSKnownOne, Depth+1))
864       return true;
865     assert((LHSKnownZero & LHSKnownOne) == 0 && 
866            "Bits known to be one AND zero?"); 
867     
868     // If all of the demanded bits are known zero on one side, return the other.
869     // These bits cannot contribute to the result of the 'or'.
870     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
871         (DemandedMask & ~LHSKnownOne))
872       return UpdateValueUsesWith(I, I->getOperand(0));
873     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
874         (DemandedMask & ~RHSKnownOne))
875       return UpdateValueUsesWith(I, I->getOperand(1));
876
877     // If all of the potentially set bits on one side are known to be set on
878     // the other side, just use the 'other' side.
879     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
880         (DemandedMask & (~RHSKnownZero)))
881       return UpdateValueUsesWith(I, I->getOperand(0));
882     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
883         (DemandedMask & (~LHSKnownZero)))
884       return UpdateValueUsesWith(I, I->getOperand(1));
885         
886     // If the RHS is a constant, see if we can simplify it.
887     if (ShrinkDemandedConstant(I, 1, DemandedMask))
888       return UpdateValueUsesWith(I, I);
889           
890     // Output known-0 bits are only known if clear in both the LHS & RHS.
891     RHSKnownZero &= LHSKnownZero;
892     // Output known-1 are known to be set if set in either the LHS | RHS.
893     RHSKnownOne |= LHSKnownOne;
894     break;
895   case Instruction::Xor: {
896     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
897                              RHSKnownZero, RHSKnownOne, Depth+1))
898       return true;
899     assert((RHSKnownZero & RHSKnownOne) == 0 && 
900            "Bits known to be one AND zero?"); 
901     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
902                              LHSKnownZero, LHSKnownOne, Depth+1))
903       return true;
904     assert((LHSKnownZero & LHSKnownOne) == 0 && 
905            "Bits known to be one AND zero?"); 
906     
907     // If all of the demanded bits are known zero on one side, return the other.
908     // These bits cannot contribute to the result of the 'xor'.
909     if ((DemandedMask & RHSKnownZero) == DemandedMask)
910       return UpdateValueUsesWith(I, I->getOperand(0));
911     if ((DemandedMask & LHSKnownZero) == DemandedMask)
912       return UpdateValueUsesWith(I, I->getOperand(1));
913     
914     // Output known-0 bits are known if clear or set in both the LHS & RHS.
915     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
916                          (RHSKnownOne & LHSKnownOne);
917     // Output known-1 are known to be set if set in only one of the LHS, RHS.
918     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
919                         (RHSKnownOne & LHSKnownZero);
920     
921     // If all of the demanded bits are known to be zero on one side or the
922     // other, turn this into an *inclusive* or.
923     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
924     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
925       Instruction *Or =
926         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
927                                  I->getName());
928       InsertNewInstBefore(Or, *I);
929       return UpdateValueUsesWith(I, Or);
930     }
931     
932     // If all of the demanded bits on one side are known, and all of the set
933     // bits on that side are also known to be set on the other side, turn this
934     // into an AND, as we know the bits will be cleared.
935     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
936     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
937       // all known
938       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
939         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
940         Instruction *And = 
941           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
942         InsertNewInstBefore(And, *I);
943         return UpdateValueUsesWith(I, And);
944       }
945     }
946     
947     // If the RHS is a constant, see if we can simplify it.
948     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
949     if (ShrinkDemandedConstant(I, 1, DemandedMask))
950       return UpdateValueUsesWith(I, I);
951     
952     RHSKnownZero = KnownZeroOut;
953     RHSKnownOne  = KnownOneOut;
954     break;
955   }
956   case Instruction::Select:
957     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
958                              RHSKnownZero, RHSKnownOne, Depth+1))
959       return true;
960     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
961                              LHSKnownZero, LHSKnownOne, Depth+1))
962       return true;
963     assert((RHSKnownZero & RHSKnownOne) == 0 && 
964            "Bits known to be one AND zero?"); 
965     assert((LHSKnownZero & LHSKnownOne) == 0 && 
966            "Bits known to be one AND zero?"); 
967     
968     // If the operands are constants, see if we can simplify them.
969     if (ShrinkDemandedConstant(I, 1, DemandedMask))
970       return UpdateValueUsesWith(I, I);
971     if (ShrinkDemandedConstant(I, 2, DemandedMask))
972       return UpdateValueUsesWith(I, I);
973     
974     // Only known if known in both the LHS and RHS.
975     RHSKnownOne &= LHSKnownOne;
976     RHSKnownZero &= LHSKnownZero;
977     break;
978   case Instruction::Trunc: {
979     uint32_t truncBf = 
980       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
981     DemandedMask.zext(truncBf);
982     RHSKnownZero.zext(truncBf);
983     RHSKnownOne.zext(truncBf);
984     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
985                              RHSKnownZero, RHSKnownOne, Depth+1))
986       return true;
987     DemandedMask.trunc(BitWidth);
988     RHSKnownZero.trunc(BitWidth);
989     RHSKnownOne.trunc(BitWidth);
990     assert((RHSKnownZero & RHSKnownOne) == 0 && 
991            "Bits known to be one AND zero?"); 
992     break;
993   }
994   case Instruction::BitCast:
995     if (!I->getOperand(0)->getType()->isInteger())
996       return false;
997       
998     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
999                              RHSKnownZero, RHSKnownOne, Depth+1))
1000       return true;
1001     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1002            "Bits known to be one AND zero?"); 
1003     break;
1004   case Instruction::ZExt: {
1005     // Compute the bits in the result that are not present in the input.
1006     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1007     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1008     
1009     DemandedMask.trunc(SrcBitWidth);
1010     RHSKnownZero.trunc(SrcBitWidth);
1011     RHSKnownOne.trunc(SrcBitWidth);
1012     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1013                              RHSKnownZero, RHSKnownOne, Depth+1))
1014       return true;
1015     DemandedMask.zext(BitWidth);
1016     RHSKnownZero.zext(BitWidth);
1017     RHSKnownOne.zext(BitWidth);
1018     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1019            "Bits known to be one AND zero?"); 
1020     // The top bits are known to be zero.
1021     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1022     break;
1023   }
1024   case Instruction::SExt: {
1025     // Compute the bits in the result that are not present in the input.
1026     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1027     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1028     
1029     APInt InputDemandedBits = DemandedMask & 
1030                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1031
1032     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1033     // If any of the sign extended bits are demanded, we know that the sign
1034     // bit is demanded.
1035     if ((NewBits & DemandedMask) != 0)
1036       InputDemandedBits.set(SrcBitWidth-1);
1037       
1038     InputDemandedBits.trunc(SrcBitWidth);
1039     RHSKnownZero.trunc(SrcBitWidth);
1040     RHSKnownOne.trunc(SrcBitWidth);
1041     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1042                              RHSKnownZero, RHSKnownOne, Depth+1))
1043       return true;
1044     InputDemandedBits.zext(BitWidth);
1045     RHSKnownZero.zext(BitWidth);
1046     RHSKnownOne.zext(BitWidth);
1047     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1048            "Bits known to be one AND zero?"); 
1049       
1050     // If the sign bit of the input is known set or clear, then we know the
1051     // top bits of the result.
1052
1053     // If the input sign bit is known zero, or if the NewBits are not demanded
1054     // convert this into a zero extension.
1055     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1056     {
1057       // Convert to ZExt cast
1058       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1059       return UpdateValueUsesWith(I, NewCast);
1060     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1061       RHSKnownOne |= NewBits;
1062     }
1063     break;
1064   }
1065   case Instruction::Add: {
1066     // Figure out what the input bits are.  If the top bits of the and result
1067     // are not demanded, then the add doesn't demand them from its input
1068     // either.
1069     uint32_t NLZ = DemandedMask.countLeadingZeros();
1070       
1071     // If there is a constant on the RHS, there are a variety of xformations
1072     // we can do.
1073     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1074       // If null, this should be simplified elsewhere.  Some of the xforms here
1075       // won't work if the RHS is zero.
1076       if (RHS->isZero())
1077         break;
1078       
1079       // If the top bit of the output is demanded, demand everything from the
1080       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1081       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1082
1083       // Find information about known zero/one bits in the input.
1084       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1085                                LHSKnownZero, LHSKnownOne, Depth+1))
1086         return true;
1087
1088       // If the RHS of the add has bits set that can't affect the input, reduce
1089       // the constant.
1090       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1091         return UpdateValueUsesWith(I, I);
1092       
1093       // Avoid excess work.
1094       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1095         break;
1096       
1097       // Turn it into OR if input bits are zero.
1098       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1099         Instruction *Or =
1100           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1101                                    I->getName());
1102         InsertNewInstBefore(Or, *I);
1103         return UpdateValueUsesWith(I, Or);
1104       }
1105       
1106       // We can say something about the output known-zero and known-one bits,
1107       // depending on potential carries from the input constant and the
1108       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1109       // bits set and the RHS constant is 0x01001, then we know we have a known
1110       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1111       
1112       // To compute this, we first compute the potential carry bits.  These are
1113       // the bits which may be modified.  I'm not aware of a better way to do
1114       // this scan.
1115       const APInt& RHSVal = RHS->getValue();
1116       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1117       
1118       // Now that we know which bits have carries, compute the known-1/0 sets.
1119       
1120       // Bits are known one if they are known zero in one operand and one in the
1121       // other, and there is no input carry.
1122       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1123                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1124       
1125       // Bits are known zero if they are known zero in both operands and there
1126       // is no input carry.
1127       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1128     } else {
1129       // If the high-bits of this ADD are not demanded, then it does not demand
1130       // the high bits of its LHS or RHS.
1131       if (DemandedMask[BitWidth-1] == 0) {
1132         // Right fill the mask of bits for this ADD to demand the most
1133         // significant bit and all those below it.
1134         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1135         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1136                                  LHSKnownZero, LHSKnownOne, Depth+1))
1137           return true;
1138         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1139                                  LHSKnownZero, LHSKnownOne, Depth+1))
1140           return true;
1141       }
1142     }
1143     break;
1144   }
1145   case Instruction::Sub:
1146     // If the high-bits of this SUB are not demanded, then it does not demand
1147     // the high bits of its LHS or RHS.
1148     if (DemandedMask[BitWidth-1] == 0) {
1149       // Right fill the mask of bits for this SUB to demand the most
1150       // significant bit and all those below it.
1151       uint32_t NLZ = DemandedMask.countLeadingZeros();
1152       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1153       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1154                                LHSKnownZero, LHSKnownOne, Depth+1))
1155         return true;
1156       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1157                                LHSKnownZero, LHSKnownOne, Depth+1))
1158         return true;
1159     }
1160     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1161     // the known zeros and ones.
1162     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1163     break;
1164   case Instruction::Shl:
1165     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1166       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1167       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1168       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1169                                RHSKnownZero, RHSKnownOne, Depth+1))
1170         return true;
1171       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1172              "Bits known to be one AND zero?"); 
1173       RHSKnownZero <<= ShiftAmt;
1174       RHSKnownOne  <<= ShiftAmt;
1175       // low bits known zero.
1176       if (ShiftAmt)
1177         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1178     }
1179     break;
1180   case Instruction::LShr:
1181     // For a logical shift right
1182     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1183       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1184       
1185       // Unsigned shift right.
1186       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1187       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1188                                RHSKnownZero, RHSKnownOne, Depth+1))
1189         return true;
1190       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1191              "Bits known to be one AND zero?"); 
1192       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1193       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1194       if (ShiftAmt) {
1195         // Compute the new bits that are at the top now.
1196         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1197         RHSKnownZero |= HighBits;  // high bits known zero.
1198       }
1199     }
1200     break;
1201   case Instruction::AShr:
1202     // If this is an arithmetic shift right and only the low-bit is set, we can
1203     // always convert this into a logical shr, even if the shift amount is
1204     // variable.  The low bit of the shift cannot be an input sign bit unless
1205     // the shift amount is >= the size of the datatype, which is undefined.
1206     if (DemandedMask == 1) {
1207       // Perform the logical shift right.
1208       Value *NewVal = BinaryOperator::CreateLShr(
1209                         I->getOperand(0), I->getOperand(1), I->getName());
1210       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1211       return UpdateValueUsesWith(I, NewVal);
1212     }    
1213
1214     // If the sign bit is the only bit demanded by this ashr, then there is no
1215     // need to do it, the shift doesn't change the high bit.
1216     if (DemandedMask.isSignBit())
1217       return UpdateValueUsesWith(I, I->getOperand(0));
1218     
1219     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1220       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1221       
1222       // Signed shift right.
1223       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1224       // If any of the "high bits" are demanded, we should set the sign bit as
1225       // demanded.
1226       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1227         DemandedMaskIn.set(BitWidth-1);
1228       if (SimplifyDemandedBits(I->getOperand(0),
1229                                DemandedMaskIn,
1230                                RHSKnownZero, RHSKnownOne, Depth+1))
1231         return true;
1232       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1233              "Bits known to be one AND zero?"); 
1234       // Compute the new bits that are at the top now.
1235       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1236       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1237       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1238         
1239       // Handle the sign bits.
1240       APInt SignBit(APInt::getSignBit(BitWidth));
1241       // Adjust to where it is now in the mask.
1242       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1243         
1244       // If the input sign bit is known to be zero, or if none of the top bits
1245       // are demanded, turn this into an unsigned shift right.
1246       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1247           (HighBits & ~DemandedMask) == HighBits) {
1248         // Perform the logical shift right.
1249         Value *NewVal = BinaryOperator::CreateLShr(
1250                           I->getOperand(0), SA, I->getName());
1251         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1252         return UpdateValueUsesWith(I, NewVal);
1253       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1254         RHSKnownOne |= HighBits;
1255       }
1256     }
1257     break;
1258   case Instruction::SRem:
1259     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1260       APInt RA = Rem->getValue().abs();
1261       if (RA.isPowerOf2()) {
1262         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1263           return UpdateValueUsesWith(I, I->getOperand(0));
1264
1265         APInt LowBits = RA - 1;
1266         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1267         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1268                                  LHSKnownZero, LHSKnownOne, Depth+1))
1269           return true;
1270
1271         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1272           LHSKnownZero |= ~LowBits;
1273
1274         KnownZero |= LHSKnownZero & DemandedMask;
1275
1276         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1277       }
1278     }
1279     break;
1280   case Instruction::URem: {
1281     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1282     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1283     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1284                              KnownZero2, KnownOne2, Depth+1))
1285       return true;
1286
1287     uint32_t Leaders = KnownZero2.countLeadingOnes();
1288     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1289                              KnownZero2, KnownOne2, Depth+1))
1290       return true;
1291
1292     Leaders = std::max(Leaders,
1293                        KnownZero2.countLeadingOnes());
1294     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1295     break;
1296   }
1297   case Instruction::Call:
1298     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1299       switch (II->getIntrinsicID()) {
1300       default: break;
1301       case Intrinsic::bswap: {
1302         // If the only bits demanded come from one byte of the bswap result,
1303         // just shift the input byte into position to eliminate the bswap.
1304         unsigned NLZ = DemandedMask.countLeadingZeros();
1305         unsigned NTZ = DemandedMask.countTrailingZeros();
1306           
1307         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1308         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1309         // have 14 leading zeros, round to 8.
1310         NLZ &= ~7;
1311         NTZ &= ~7;
1312         // If we need exactly one byte, we can do this transformation.
1313         if (BitWidth-NLZ-NTZ == 8) {
1314           unsigned ResultBit = NTZ;
1315           unsigned InputBit = BitWidth-NTZ-8;
1316           
1317           // Replace this with either a left or right shift to get the byte into
1318           // the right place.
1319           Instruction *NewVal;
1320           if (InputBit > ResultBit)
1321             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1322                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1323           else
1324             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1325                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1326           NewVal->takeName(I);
1327           InsertNewInstBefore(NewVal, *I);
1328           return UpdateValueUsesWith(I, NewVal);
1329         }
1330           
1331         // TODO: Could compute known zero/one bits based on the input.
1332         break;
1333       }
1334       }
1335     }
1336     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1337     break;
1338   }
1339   
1340   // If the client is only demanding bits that we know, return the known
1341   // constant.
1342   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1343     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1344   return false;
1345 }
1346
1347
1348 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1349 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1350 /// actually used by the caller.  This method analyzes which elements of the
1351 /// operand are undef and returns that information in UndefElts.
1352 ///
1353 /// If the information about demanded elements can be used to simplify the
1354 /// operation, the operation is simplified, then the resultant value is
1355 /// returned.  This returns null if no change was made.
1356 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1357                                                 uint64_t &UndefElts,
1358                                                 unsigned Depth) {
1359   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1360   assert(VWidth <= 64 && "Vector too wide to analyze!");
1361   uint64_t EltMask = ~0ULL >> (64-VWidth);
1362   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1363
1364   if (isa<UndefValue>(V)) {
1365     // If the entire vector is undefined, just return this info.
1366     UndefElts = EltMask;
1367     return 0;
1368   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1369     UndefElts = EltMask;
1370     return UndefValue::get(V->getType());
1371   }
1372
1373   UndefElts = 0;
1374   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1375     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1376     Constant *Undef = UndefValue::get(EltTy);
1377
1378     std::vector<Constant*> Elts;
1379     for (unsigned i = 0; i != VWidth; ++i)
1380       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1381         Elts.push_back(Undef);
1382         UndefElts |= (1ULL << i);
1383       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1384         Elts.push_back(Undef);
1385         UndefElts |= (1ULL << i);
1386       } else {                               // Otherwise, defined.
1387         Elts.push_back(CP->getOperand(i));
1388       }
1389
1390     // If we changed the constant, return it.
1391     Constant *NewCP = ConstantVector::get(Elts);
1392     return NewCP != CP ? NewCP : 0;
1393   } else if (isa<ConstantAggregateZero>(V)) {
1394     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1395     // set to undef.
1396     
1397     // Check if this is identity. If so, return 0 since we are not simplifying
1398     // anything.
1399     if (DemandedElts == ((1ULL << VWidth) -1))
1400       return 0;
1401     
1402     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1403     Constant *Zero = Constant::getNullValue(EltTy);
1404     Constant *Undef = UndefValue::get(EltTy);
1405     std::vector<Constant*> Elts;
1406     for (unsigned i = 0; i != VWidth; ++i)
1407       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1408     UndefElts = DemandedElts ^ EltMask;
1409     return ConstantVector::get(Elts);
1410   }
1411   
1412   // Limit search depth.
1413   if (Depth == 10)
1414     return false;
1415
1416   // If multiple users are using the root value, procede with
1417   // simplification conservatively assuming that all elements
1418   // are needed.
1419   if (!V->hasOneUse()) {
1420     // Quit if we find multiple users of a non-root value though.
1421     // They'll be handled when it's their turn to be visited by
1422     // the main instcombine process.
1423     if (Depth != 0)
1424       // TODO: Just compute the UndefElts information recursively.
1425       return false;
1426
1427     // Conservatively assume that all elements are needed.
1428     DemandedElts = EltMask;
1429   }
1430   
1431   Instruction *I = dyn_cast<Instruction>(V);
1432   if (!I) return false;        // Only analyze instructions.
1433   
1434   bool MadeChange = false;
1435   uint64_t UndefElts2;
1436   Value *TmpV;
1437   switch (I->getOpcode()) {
1438   default: break;
1439     
1440   case Instruction::InsertElement: {
1441     // If this is a variable index, we don't know which element it overwrites.
1442     // demand exactly the same input as we produce.
1443     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1444     if (Idx == 0) {
1445       // Note that we can't propagate undef elt info, because we don't know
1446       // which elt is getting updated.
1447       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1448                                         UndefElts2, Depth+1);
1449       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1450       break;
1451     }
1452     
1453     // If this is inserting an element that isn't demanded, remove this
1454     // insertelement.
1455     unsigned IdxNo = Idx->getZExtValue();
1456     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1457       return AddSoonDeadInstToWorklist(*I, 0);
1458     
1459     // Otherwise, the element inserted overwrites whatever was there, so the
1460     // input demanded set is simpler than the output set.
1461     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1462                                       DemandedElts & ~(1ULL << IdxNo),
1463                                       UndefElts, Depth+1);
1464     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1465
1466     // The inserted element is defined.
1467     UndefElts &= ~(1ULL << IdxNo);
1468     break;
1469   }
1470   case Instruction::ShuffleVector: {
1471     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1472     uint64_t LHSVWidth =
1473       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1474     uint64_t LeftDemanded = 0, RightDemanded = 0;
1475     for (unsigned i = 0; i < VWidth; i++) {
1476       if (DemandedElts & (1ULL << i)) {
1477         unsigned MaskVal = Shuffle->getMaskValue(i);
1478         if (MaskVal != -1u) {
1479           assert(MaskVal < LHSVWidth * 2 &&
1480                  "shufflevector mask index out of range!");
1481           if (MaskVal < LHSVWidth)
1482             LeftDemanded |= 1ULL << MaskVal;
1483           else
1484             RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
1485         }
1486       }
1487     }
1488
1489     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1490                                       UndefElts2, Depth+1);
1491     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1492
1493     uint64_t UndefElts3;
1494     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1495                                       UndefElts3, Depth+1);
1496     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1497
1498     bool NewUndefElts = false;
1499     for (unsigned i = 0; i < VWidth; i++) {
1500       unsigned MaskVal = Shuffle->getMaskValue(i);
1501       if (MaskVal == -1u) {
1502         uint64_t NewBit = 1ULL << i;
1503         UndefElts |= NewBit;
1504       } else if (MaskVal < LHSVWidth) {
1505         uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1506         NewUndefElts |= NewBit;
1507         UndefElts |= NewBit;
1508       } else {
1509         uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
1510         NewUndefElts |= NewBit;
1511         UndefElts |= NewBit;
1512       }
1513     }
1514
1515     if (NewUndefElts) {
1516       // Add additional discovered undefs.
1517       std::vector<Constant*> Elts;
1518       for (unsigned i = 0; i < VWidth; ++i) {
1519         if (UndefElts & (1ULL << i))
1520           Elts.push_back(UndefValue::get(Type::Int32Ty));
1521         else
1522           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1523                                           Shuffle->getMaskValue(i)));
1524       }
1525       I->setOperand(2, ConstantVector::get(Elts));
1526       MadeChange = true;
1527     }
1528     break;
1529   }
1530   case Instruction::BitCast: {
1531     // Vector->vector casts only.
1532     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1533     if (!VTy) break;
1534     unsigned InVWidth = VTy->getNumElements();
1535     uint64_t InputDemandedElts = 0;
1536     unsigned Ratio;
1537
1538     if (VWidth == InVWidth) {
1539       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1540       // elements as are demanded of us.
1541       Ratio = 1;
1542       InputDemandedElts = DemandedElts;
1543     } else if (VWidth > InVWidth) {
1544       // Untested so far.
1545       break;
1546       
1547       // If there are more elements in the result than there are in the source,
1548       // then an input element is live if any of the corresponding output
1549       // elements are live.
1550       Ratio = VWidth/InVWidth;
1551       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1552         if (DemandedElts & (1ULL << OutIdx))
1553           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1554       }
1555     } else {
1556       // Untested so far.
1557       break;
1558       
1559       // If there are more elements in the source than there are in the result,
1560       // then an input element is live if the corresponding output element is
1561       // live.
1562       Ratio = InVWidth/VWidth;
1563       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1564         if (DemandedElts & (1ULL << InIdx/Ratio))
1565           InputDemandedElts |= 1ULL << InIdx;
1566     }
1567     
1568     // div/rem demand all inputs, because they don't want divide by zero.
1569     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1570                                       UndefElts2, Depth+1);
1571     if (TmpV) {
1572       I->setOperand(0, TmpV);
1573       MadeChange = true;
1574     }
1575     
1576     UndefElts = UndefElts2;
1577     if (VWidth > InVWidth) {
1578       assert(0 && "Unimp");
1579       // If there are more elements in the result than there are in the source,
1580       // then an output element is undef if the corresponding input element is
1581       // undef.
1582       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1583         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1584           UndefElts |= 1ULL << OutIdx;
1585     } else if (VWidth < InVWidth) {
1586       assert(0 && "Unimp");
1587       // If there are more elements in the source than there are in the result,
1588       // then a result element is undef if all of the corresponding input
1589       // elements are undef.
1590       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1591       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1592         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1593           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1594     }
1595     break;
1596   }
1597   case Instruction::And:
1598   case Instruction::Or:
1599   case Instruction::Xor:
1600   case Instruction::Add:
1601   case Instruction::Sub:
1602   case Instruction::Mul:
1603     // div/rem demand all inputs, because they don't want divide by zero.
1604     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1605                                       UndefElts, Depth+1);
1606     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1607     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1608                                       UndefElts2, Depth+1);
1609     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1610       
1611     // Output elements are undefined if both are undefined.  Consider things
1612     // like undef&0.  The result is known zero, not undef.
1613     UndefElts &= UndefElts2;
1614     break;
1615     
1616   case Instruction::Call: {
1617     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1618     if (!II) break;
1619     switch (II->getIntrinsicID()) {
1620     default: break;
1621       
1622     // Binary vector operations that work column-wise.  A dest element is a
1623     // function of the corresponding input elements from the two inputs.
1624     case Intrinsic::x86_sse_sub_ss:
1625     case Intrinsic::x86_sse_mul_ss:
1626     case Intrinsic::x86_sse_min_ss:
1627     case Intrinsic::x86_sse_max_ss:
1628     case Intrinsic::x86_sse2_sub_sd:
1629     case Intrinsic::x86_sse2_mul_sd:
1630     case Intrinsic::x86_sse2_min_sd:
1631     case Intrinsic::x86_sse2_max_sd:
1632       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1633                                         UndefElts, Depth+1);
1634       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1635       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1636                                         UndefElts2, Depth+1);
1637       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1638
1639       // If only the low elt is demanded and this is a scalarizable intrinsic,
1640       // scalarize it now.
1641       if (DemandedElts == 1) {
1642         switch (II->getIntrinsicID()) {
1643         default: break;
1644         case Intrinsic::x86_sse_sub_ss:
1645         case Intrinsic::x86_sse_mul_ss:
1646         case Intrinsic::x86_sse2_sub_sd:
1647         case Intrinsic::x86_sse2_mul_sd:
1648           // TODO: Lower MIN/MAX/ABS/etc
1649           Value *LHS = II->getOperand(1);
1650           Value *RHS = II->getOperand(2);
1651           // Extract the element as scalars.
1652           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1653           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1654           
1655           switch (II->getIntrinsicID()) {
1656           default: assert(0 && "Case stmts out of sync!");
1657           case Intrinsic::x86_sse_sub_ss:
1658           case Intrinsic::x86_sse2_sub_sd:
1659             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1660                                                         II->getName()), *II);
1661             break;
1662           case Intrinsic::x86_sse_mul_ss:
1663           case Intrinsic::x86_sse2_mul_sd:
1664             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1665                                                          II->getName()), *II);
1666             break;
1667           }
1668           
1669           Instruction *New =
1670             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1671                                       II->getName());
1672           InsertNewInstBefore(New, *II);
1673           AddSoonDeadInstToWorklist(*II, 0);
1674           return New;
1675         }            
1676       }
1677         
1678       // Output elements are undefined if both are undefined.  Consider things
1679       // like undef&0.  The result is known zero, not undef.
1680       UndefElts &= UndefElts2;
1681       break;
1682     }
1683     break;
1684   }
1685   }
1686   return MadeChange ? I : 0;
1687 }
1688
1689
1690 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1691 /// function is designed to check a chain of associative operators for a
1692 /// potential to apply a certain optimization.  Since the optimization may be
1693 /// applicable if the expression was reassociated, this checks the chain, then
1694 /// reassociates the expression as necessary to expose the optimization
1695 /// opportunity.  This makes use of a special Functor, which must define
1696 /// 'shouldApply' and 'apply' methods.
1697 ///
1698 template<typename Functor>
1699 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1700   unsigned Opcode = Root.getOpcode();
1701   Value *LHS = Root.getOperand(0);
1702
1703   // Quick check, see if the immediate LHS matches...
1704   if (F.shouldApply(LHS))
1705     return F.apply(Root);
1706
1707   // Otherwise, if the LHS is not of the same opcode as the root, return.
1708   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1709   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1710     // Should we apply this transform to the RHS?
1711     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1712
1713     // If not to the RHS, check to see if we should apply to the LHS...
1714     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1715       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1716       ShouldApply = true;
1717     }
1718
1719     // If the functor wants to apply the optimization to the RHS of LHSI,
1720     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1721     if (ShouldApply) {
1722       // Now all of the instructions are in the current basic block, go ahead
1723       // and perform the reassociation.
1724       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1725
1726       // First move the selected RHS to the LHS of the root...
1727       Root.setOperand(0, LHSI->getOperand(1));
1728
1729       // Make what used to be the LHS of the root be the user of the root...
1730       Value *ExtraOperand = TmpLHSI->getOperand(1);
1731       if (&Root == TmpLHSI) {
1732         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1733         return 0;
1734       }
1735       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1736       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1737       BasicBlock::iterator ARI = &Root; ++ARI;
1738       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1739       ARI = Root;
1740
1741       // Now propagate the ExtraOperand down the chain of instructions until we
1742       // get to LHSI.
1743       while (TmpLHSI != LHSI) {
1744         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1745         // Move the instruction to immediately before the chain we are
1746         // constructing to avoid breaking dominance properties.
1747         NextLHSI->moveBefore(ARI);
1748         ARI = NextLHSI;
1749
1750         Value *NextOp = NextLHSI->getOperand(1);
1751         NextLHSI->setOperand(1, ExtraOperand);
1752         TmpLHSI = NextLHSI;
1753         ExtraOperand = NextOp;
1754       }
1755
1756       // Now that the instructions are reassociated, have the functor perform
1757       // the transformation...
1758       return F.apply(Root);
1759     }
1760
1761     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1762   }
1763   return 0;
1764 }
1765
1766 namespace {
1767
1768 // AddRHS - Implements: X + X --> X << 1
1769 struct AddRHS {
1770   Value *RHS;
1771   AddRHS(Value *rhs) : RHS(rhs) {}
1772   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1773   Instruction *apply(BinaryOperator &Add) const {
1774     return BinaryOperator::CreateShl(Add.getOperand(0),
1775                                      ConstantInt::get(Add.getType(), 1));
1776   }
1777 };
1778
1779 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1780 //                 iff C1&C2 == 0
1781 struct AddMaskingAnd {
1782   Constant *C2;
1783   AddMaskingAnd(Constant *c) : C2(c) {}
1784   bool shouldApply(Value *LHS) const {
1785     ConstantInt *C1;
1786     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1787            ConstantExpr::getAnd(C1, C2)->isNullValue();
1788   }
1789   Instruction *apply(BinaryOperator &Add) const {
1790     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1791   }
1792 };
1793
1794 }
1795
1796 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1797                                              InstCombiner *IC) {
1798   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1799     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1800   }
1801
1802   // Figure out if the constant is the left or the right argument.
1803   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1804   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1805
1806   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1807     if (ConstIsRHS)
1808       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1809     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1810   }
1811
1812   Value *Op0 = SO, *Op1 = ConstOperand;
1813   if (!ConstIsRHS)
1814     std::swap(Op0, Op1);
1815   Instruction *New;
1816   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1817     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1818   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1819     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1820                           SO->getName()+".cmp");
1821   else {
1822     assert(0 && "Unknown binary instruction type!");
1823     abort();
1824   }
1825   return IC->InsertNewInstBefore(New, I);
1826 }
1827
1828 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1829 // constant as the other operand, try to fold the binary operator into the
1830 // select arguments.  This also works for Cast instructions, which obviously do
1831 // not have a second operand.
1832 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1833                                      InstCombiner *IC) {
1834   // Don't modify shared select instructions
1835   if (!SI->hasOneUse()) return 0;
1836   Value *TV = SI->getOperand(1);
1837   Value *FV = SI->getOperand(2);
1838
1839   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1840     // Bool selects with constant operands can be folded to logical ops.
1841     if (SI->getType() == Type::Int1Ty) return 0;
1842
1843     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1844     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1845
1846     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1847                               SelectFalseVal);
1848   }
1849   return 0;
1850 }
1851
1852
1853 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1854 /// node as operand #0, see if we can fold the instruction into the PHI (which
1855 /// is only possible if all operands to the PHI are constants).
1856 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1857   PHINode *PN = cast<PHINode>(I.getOperand(0));
1858   unsigned NumPHIValues = PN->getNumIncomingValues();
1859   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1860
1861   // Check to see if all of the operands of the PHI are constants.  If there is
1862   // one non-constant value, remember the BB it is.  If there is more than one
1863   // or if *it* is a PHI, bail out.
1864   BasicBlock *NonConstBB = 0;
1865   for (unsigned i = 0; i != NumPHIValues; ++i)
1866     if (!isa<Constant>(PN->getIncomingValue(i))) {
1867       if (NonConstBB) return 0;  // More than one non-const value.
1868       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1869       NonConstBB = PN->getIncomingBlock(i);
1870       
1871       // If the incoming non-constant value is in I's block, we have an infinite
1872       // loop.
1873       if (NonConstBB == I.getParent())
1874         return 0;
1875     }
1876   
1877   // If there is exactly one non-constant value, we can insert a copy of the
1878   // operation in that block.  However, if this is a critical edge, we would be
1879   // inserting the computation one some other paths (e.g. inside a loop).  Only
1880   // do this if the pred block is unconditionally branching into the phi block.
1881   if (NonConstBB) {
1882     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1883     if (!BI || !BI->isUnconditional()) return 0;
1884   }
1885
1886   // Okay, we can do the transformation: create the new PHI node.
1887   PHINode *NewPN = PHINode::Create(I.getType(), "");
1888   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1889   InsertNewInstBefore(NewPN, *PN);
1890   NewPN->takeName(PN);
1891
1892   // Next, add all of the operands to the PHI.
1893   if (I.getNumOperands() == 2) {
1894     Constant *C = cast<Constant>(I.getOperand(1));
1895     for (unsigned i = 0; i != NumPHIValues; ++i) {
1896       Value *InV = 0;
1897       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1898         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1899           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1900         else
1901           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1902       } else {
1903         assert(PN->getIncomingBlock(i) == NonConstBB);
1904         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1905           InV = BinaryOperator::Create(BO->getOpcode(),
1906                                        PN->getIncomingValue(i), C, "phitmp",
1907                                        NonConstBB->getTerminator());
1908         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1909           InV = CmpInst::Create(CI->getOpcode(), 
1910                                 CI->getPredicate(),
1911                                 PN->getIncomingValue(i), C, "phitmp",
1912                                 NonConstBB->getTerminator());
1913         else
1914           assert(0 && "Unknown binop!");
1915         
1916         AddToWorkList(cast<Instruction>(InV));
1917       }
1918       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1919     }
1920   } else { 
1921     CastInst *CI = cast<CastInst>(&I);
1922     const Type *RetTy = CI->getType();
1923     for (unsigned i = 0; i != NumPHIValues; ++i) {
1924       Value *InV;
1925       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1926         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1927       } else {
1928         assert(PN->getIncomingBlock(i) == NonConstBB);
1929         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1930                                I.getType(), "phitmp", 
1931                                NonConstBB->getTerminator());
1932         AddToWorkList(cast<Instruction>(InV));
1933       }
1934       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1935     }
1936   }
1937   return ReplaceInstUsesWith(I, NewPN);
1938 }
1939
1940
1941 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1942 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1943 /// This basically requires proving that the add in the original type would not
1944 /// overflow to change the sign bit or have a carry out.
1945 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1946   // There are different heuristics we can use for this.  Here are some simple
1947   // ones.
1948   
1949   // Add has the property that adding any two 2's complement numbers can only 
1950   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1951   // have at least two sign bits, we know that the addition of the two values will
1952   // sign extend fine.
1953   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1954     return true;
1955   
1956   
1957   // If one of the operands only has one non-zero bit, and if the other operand
1958   // has a known-zero bit in a more significant place than it (not including the
1959   // sign bit) the ripple may go up to and fill the zero, but won't change the
1960   // sign.  For example, (X & ~4) + 1.
1961   
1962   // TODO: Implement.
1963   
1964   return false;
1965 }
1966
1967
1968 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1969   bool Changed = SimplifyCommutative(I);
1970   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1971
1972   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1973     // X + undef -> undef
1974     if (isa<UndefValue>(RHS))
1975       return ReplaceInstUsesWith(I, RHS);
1976
1977     // X + 0 --> X
1978     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1979       if (RHSC->isNullValue())
1980         return ReplaceInstUsesWith(I, LHS);
1981     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1982       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1983                               (I.getType())->getValueAPF()))
1984         return ReplaceInstUsesWith(I, LHS);
1985     }
1986
1987     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1988       // X + (signbit) --> X ^ signbit
1989       const APInt& Val = CI->getValue();
1990       uint32_t BitWidth = Val.getBitWidth();
1991       if (Val == APInt::getSignBit(BitWidth))
1992         return BinaryOperator::CreateXor(LHS, RHS);
1993       
1994       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1995       // (X & 254)+1 -> (X&254)|1
1996       if (!isa<VectorType>(I.getType())) {
1997         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1998         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1999                                  KnownZero, KnownOne))
2000           return &I;
2001       }
2002
2003       // zext(i1) - 1  ->  select i1, 0, -1
2004       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2005         if (CI->isAllOnesValue() &&
2006             ZI->getOperand(0)->getType() == Type::Int1Ty)
2007           return SelectInst::Create(ZI->getOperand(0),
2008                                     Constant::getNullValue(I.getType()),
2009                                     ConstantInt::getAllOnesValue(I.getType()));
2010     }
2011
2012     if (isa<PHINode>(LHS))
2013       if (Instruction *NV = FoldOpIntoPhi(I))
2014         return NV;
2015     
2016     ConstantInt *XorRHS = 0;
2017     Value *XorLHS = 0;
2018     if (isa<ConstantInt>(RHSC) &&
2019         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2020       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2021       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2022       
2023       uint32_t Size = TySizeBits / 2;
2024       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2025       APInt CFF80Val(-C0080Val);
2026       do {
2027         if (TySizeBits > Size) {
2028           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2029           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2030           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2031               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2032             // This is a sign extend if the top bits are known zero.
2033             if (!MaskedValueIsZero(XorLHS, 
2034                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2035               Size = 0;  // Not a sign ext, but can't be any others either.
2036             break;
2037           }
2038         }
2039         Size >>= 1;
2040         C0080Val = APIntOps::lshr(C0080Val, Size);
2041         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2042       } while (Size >= 1);
2043       
2044       // FIXME: This shouldn't be necessary. When the backends can handle types
2045       // with funny bit widths then this switch statement should be removed. It
2046       // is just here to get the size of the "middle" type back up to something
2047       // that the back ends can handle.
2048       const Type *MiddleType = 0;
2049       switch (Size) {
2050         default: break;
2051         case 32: MiddleType = Type::Int32Ty; break;
2052         case 16: MiddleType = Type::Int16Ty; break;
2053         case  8: MiddleType = Type::Int8Ty; break;
2054       }
2055       if (MiddleType) {
2056         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2057         InsertNewInstBefore(NewTrunc, I);
2058         return new SExtInst(NewTrunc, I.getType(), I.getName());
2059       }
2060     }
2061   }
2062
2063   if (I.getType() == Type::Int1Ty)
2064     return BinaryOperator::CreateXor(LHS, RHS);
2065
2066   // X + X --> X << 1
2067   if (I.getType()->isInteger()) {
2068     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2069
2070     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2071       if (RHSI->getOpcode() == Instruction::Sub)
2072         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2073           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2074     }
2075     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2076       if (LHSI->getOpcode() == Instruction::Sub)
2077         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2078           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2079     }
2080   }
2081
2082   // -A + B  -->  B - A
2083   // -A + -B  -->  -(A + B)
2084   if (Value *LHSV = dyn_castNegVal(LHS)) {
2085     if (LHS->getType()->isIntOrIntVector()) {
2086       if (Value *RHSV = dyn_castNegVal(RHS)) {
2087         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2088         InsertNewInstBefore(NewAdd, I);
2089         return BinaryOperator::CreateNeg(NewAdd);
2090       }
2091     }
2092     
2093     return BinaryOperator::CreateSub(RHS, LHSV);
2094   }
2095
2096   // A + -B  -->  A - B
2097   if (!isa<Constant>(RHS))
2098     if (Value *V = dyn_castNegVal(RHS))
2099       return BinaryOperator::CreateSub(LHS, V);
2100
2101
2102   ConstantInt *C2;
2103   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2104     if (X == RHS)   // X*C + X --> X * (C+1)
2105       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2106
2107     // X*C1 + X*C2 --> X * (C1+C2)
2108     ConstantInt *C1;
2109     if (X == dyn_castFoldableMul(RHS, C1))
2110       return BinaryOperator::CreateMul(X, Add(C1, C2));
2111   }
2112
2113   // X + X*C --> X * (C+1)
2114   if (dyn_castFoldableMul(RHS, C2) == LHS)
2115     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2116
2117   // X + ~X --> -1   since   ~X = -X-1
2118   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2119     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2120   
2121
2122   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2123   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2124     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2125       return R;
2126   
2127   // A+B --> A|B iff A and B have no bits set in common.
2128   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2129     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2130     APInt LHSKnownOne(IT->getBitWidth(), 0);
2131     APInt LHSKnownZero(IT->getBitWidth(), 0);
2132     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2133     if (LHSKnownZero != 0) {
2134       APInt RHSKnownOne(IT->getBitWidth(), 0);
2135       APInt RHSKnownZero(IT->getBitWidth(), 0);
2136       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2137       
2138       // No bits in common -> bitwise or.
2139       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2140         return BinaryOperator::CreateOr(LHS, RHS);
2141     }
2142   }
2143
2144   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2145   if (I.getType()->isIntOrIntVector()) {
2146     Value *W, *X, *Y, *Z;
2147     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2148         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2149       if (W != Y) {
2150         if (W == Z) {
2151           std::swap(Y, Z);
2152         } else if (Y == X) {
2153           std::swap(W, X);
2154         } else if (X == Z) {
2155           std::swap(Y, Z);
2156           std::swap(W, X);
2157         }
2158       }
2159
2160       if (W == Y) {
2161         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2162                                                             LHS->getName()), I);
2163         return BinaryOperator::CreateMul(W, NewAdd);
2164       }
2165     }
2166   }
2167
2168   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2169     Value *X = 0;
2170     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2171       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2172
2173     // (X & FF00) + xx00  -> (X+xx00) & FF00
2174     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2175       Constant *Anded = And(CRHS, C2);
2176       if (Anded == CRHS) {
2177         // See if all bits from the first bit set in the Add RHS up are included
2178         // in the mask.  First, get the rightmost bit.
2179         const APInt& AddRHSV = CRHS->getValue();
2180
2181         // Form a mask of all bits from the lowest bit added through the top.
2182         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2183
2184         // See if the and mask includes all of these bits.
2185         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2186
2187         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2188           // Okay, the xform is safe.  Insert the new add pronto.
2189           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2190                                                             LHS->getName()), I);
2191           return BinaryOperator::CreateAnd(NewAdd, C2);
2192         }
2193       }
2194     }
2195
2196     // Try to fold constant add into select arguments.
2197     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2198       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2199         return R;
2200   }
2201
2202   // add (cast *A to intptrtype) B -> 
2203   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2204   {
2205     CastInst *CI = dyn_cast<CastInst>(LHS);
2206     Value *Other = RHS;
2207     if (!CI) {
2208       CI = dyn_cast<CastInst>(RHS);
2209       Other = LHS;
2210     }
2211     if (CI && CI->getType()->isSized() && 
2212         (CI->getType()->getPrimitiveSizeInBits() == 
2213          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2214         && isa<PointerType>(CI->getOperand(0)->getType())) {
2215       unsigned AS =
2216         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2217       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2218                                       PointerType::get(Type::Int8Ty, AS), I);
2219       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2220       return new PtrToIntInst(I2, CI->getType());
2221     }
2222   }
2223   
2224   // add (select X 0 (sub n A)) A  -->  select X A n
2225   {
2226     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2227     Value *A = RHS;
2228     if (!SI) {
2229       SI = dyn_cast<SelectInst>(RHS);
2230       A = LHS;
2231     }
2232     if (SI && SI->hasOneUse()) {
2233       Value *TV = SI->getTrueValue();
2234       Value *FV = SI->getFalseValue();
2235       Value *N;
2236
2237       // Can we fold the add into the argument of the select?
2238       // We check both true and false select arguments for a matching subtract.
2239       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2240         // Fold the add into the true select value.
2241         return SelectInst::Create(SI->getCondition(), N, A);
2242       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2243         // Fold the add into the false select value.
2244         return SelectInst::Create(SI->getCondition(), A, N);
2245     }
2246   }
2247   
2248   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2249   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2250     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2251       return ReplaceInstUsesWith(I, LHS);
2252
2253   // Check for (add (sext x), y), see if we can merge this into an
2254   // integer add followed by a sext.
2255   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2256     // (add (sext x), cst) --> (sext (add x, cst'))
2257     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2258       Constant *CI = 
2259         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2260       if (LHSConv->hasOneUse() &&
2261           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2262           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2263         // Insert the new, smaller add.
2264         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2265                                                         CI, "addconv");
2266         InsertNewInstBefore(NewAdd, I);
2267         return new SExtInst(NewAdd, I.getType());
2268       }
2269     }
2270     
2271     // (add (sext x), (sext y)) --> (sext (add int x, y))
2272     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2273       // Only do this if x/y have the same type, if at last one of them has a
2274       // single use (so we don't increase the number of sexts), and if the
2275       // integer add will not overflow.
2276       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2277           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2278           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2279                                    RHSConv->getOperand(0))) {
2280         // Insert the new integer add.
2281         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2282                                                         RHSConv->getOperand(0),
2283                                                         "addconv");
2284         InsertNewInstBefore(NewAdd, I);
2285         return new SExtInst(NewAdd, I.getType());
2286       }
2287     }
2288   }
2289   
2290   // Check for (add double (sitofp x), y), see if we can merge this into an
2291   // integer add followed by a promotion.
2292   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2293     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2294     // ... if the constant fits in the integer value.  This is useful for things
2295     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2296     // requires a constant pool load, and generally allows the add to be better
2297     // instcombined.
2298     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2299       Constant *CI = 
2300       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2301       if (LHSConv->hasOneUse() &&
2302           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2303           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2304         // Insert the new integer add.
2305         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2306                                                         CI, "addconv");
2307         InsertNewInstBefore(NewAdd, I);
2308         return new SIToFPInst(NewAdd, I.getType());
2309       }
2310     }
2311     
2312     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2313     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2314       // Only do this if x/y have the same type, if at last one of them has a
2315       // single use (so we don't increase the number of int->fp conversions),
2316       // and if the integer add will not overflow.
2317       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2318           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2319           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2320                                    RHSConv->getOperand(0))) {
2321         // Insert the new integer add.
2322         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2323                                                         RHSConv->getOperand(0),
2324                                                         "addconv");
2325         InsertNewInstBefore(NewAdd, I);
2326         return new SIToFPInst(NewAdd, I.getType());
2327       }
2328     }
2329   }
2330   
2331   return Changed ? &I : 0;
2332 }
2333
2334 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2335   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2336
2337   if (Op0 == Op1 &&                        // sub X, X  -> 0
2338       !I.getType()->isFPOrFPVector())
2339     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2340
2341   // If this is a 'B = x-(-A)', change to B = x+A...
2342   if (Value *V = dyn_castNegVal(Op1))
2343     return BinaryOperator::CreateAdd(Op0, V);
2344
2345   if (isa<UndefValue>(Op0))
2346     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2347   if (isa<UndefValue>(Op1))
2348     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2349
2350   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2351     // Replace (-1 - A) with (~A)...
2352     if (C->isAllOnesValue())
2353       return BinaryOperator::CreateNot(Op1);
2354
2355     // C - ~X == X + (1+C)
2356     Value *X = 0;
2357     if (match(Op1, m_Not(m_Value(X))))
2358       return BinaryOperator::CreateAdd(X, AddOne(C));
2359
2360     // -(X >>u 31) -> (X >>s 31)
2361     // -(X >>s 31) -> (X >>u 31)
2362     if (C->isZero()) {
2363       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2364         if (SI->getOpcode() == Instruction::LShr) {
2365           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2366             // Check to see if we are shifting out everything but the sign bit.
2367             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2368                 SI->getType()->getPrimitiveSizeInBits()-1) {
2369               // Ok, the transformation is safe.  Insert AShr.
2370               return BinaryOperator::Create(Instruction::AShr, 
2371                                           SI->getOperand(0), CU, SI->getName());
2372             }
2373           }
2374         }
2375         else if (SI->getOpcode() == Instruction::AShr) {
2376           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2377             // Check to see if we are shifting out everything but the sign bit.
2378             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2379                 SI->getType()->getPrimitiveSizeInBits()-1) {
2380               // Ok, the transformation is safe.  Insert LShr. 
2381               return BinaryOperator::CreateLShr(
2382                                           SI->getOperand(0), CU, SI->getName());
2383             }
2384           }
2385         }
2386       }
2387     }
2388
2389     // Try to fold constant sub into select arguments.
2390     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2391       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2392         return R;
2393   }
2394
2395   if (I.getType() == Type::Int1Ty)
2396     return BinaryOperator::CreateXor(Op0, Op1);
2397
2398   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2399     if (Op1I->getOpcode() == Instruction::Add &&
2400         !Op0->getType()->isFPOrFPVector()) {
2401       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2402         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2403       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2404         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2405       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2406         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2407           // C1-(X+C2) --> (C1-C2)-X
2408           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2409                                            Op1I->getOperand(0));
2410       }
2411     }
2412
2413     if (Op1I->hasOneUse()) {
2414       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2415       // is not used by anyone else...
2416       //
2417       if (Op1I->getOpcode() == Instruction::Sub &&
2418           !Op1I->getType()->isFPOrFPVector()) {
2419         // Swap the two operands of the subexpr...
2420         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2421         Op1I->setOperand(0, IIOp1);
2422         Op1I->setOperand(1, IIOp0);
2423
2424         // Create the new top level add instruction...
2425         return BinaryOperator::CreateAdd(Op0, Op1);
2426       }
2427
2428       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2429       //
2430       if (Op1I->getOpcode() == Instruction::And &&
2431           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2432         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2433
2434         Value *NewNot =
2435           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2436         return BinaryOperator::CreateAnd(Op0, NewNot);
2437       }
2438
2439       // 0 - (X sdiv C)  -> (X sdiv -C)
2440       if (Op1I->getOpcode() == Instruction::SDiv)
2441         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2442           if (CSI->isZero())
2443             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2444               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2445                                                ConstantExpr::getNeg(DivRHS));
2446
2447       // X - X*C --> X * (1-C)
2448       ConstantInt *C2 = 0;
2449       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2450         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2451         return BinaryOperator::CreateMul(Op0, CP1);
2452       }
2453     }
2454   }
2455
2456   if (!Op0->getType()->isFPOrFPVector())
2457     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2458       if (Op0I->getOpcode() == Instruction::Add) {
2459         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2460           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2461         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2462           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2463       } else if (Op0I->getOpcode() == Instruction::Sub) {
2464         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2465           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2466       }
2467     }
2468
2469   ConstantInt *C1;
2470   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2471     if (X == Op1)  // X*C - X --> X * (C-1)
2472       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2473
2474     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2475     if (X == dyn_castFoldableMul(Op1, C2))
2476       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2477   }
2478   return 0;
2479 }
2480
2481 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2482 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2483 /// TrueIfSigned if the result of the comparison is true when the input value is
2484 /// signed.
2485 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2486                            bool &TrueIfSigned) {
2487   switch (pred) {
2488   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2489     TrueIfSigned = true;
2490     return RHS->isZero();
2491   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2492     TrueIfSigned = true;
2493     return RHS->isAllOnesValue();
2494   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2495     TrueIfSigned = false;
2496     return RHS->isAllOnesValue();
2497   case ICmpInst::ICMP_UGT:
2498     // True if LHS u> RHS and RHS == high-bit-mask - 1
2499     TrueIfSigned = true;
2500     return RHS->getValue() ==
2501       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2502   case ICmpInst::ICMP_UGE: 
2503     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2504     TrueIfSigned = true;
2505     return RHS->getValue().isSignBit();
2506   default:
2507     return false;
2508   }
2509 }
2510
2511 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2512   bool Changed = SimplifyCommutative(I);
2513   Value *Op0 = I.getOperand(0);
2514
2515   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2516     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2517
2518   // Simplify mul instructions with a constant RHS...
2519   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2520     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2521
2522       // ((X << C1)*C2) == (X * (C2 << C1))
2523       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2524         if (SI->getOpcode() == Instruction::Shl)
2525           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2526             return BinaryOperator::CreateMul(SI->getOperand(0),
2527                                              ConstantExpr::getShl(CI, ShOp));
2528
2529       if (CI->isZero())
2530         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2531       if (CI->equalsInt(1))                  // X * 1  == X
2532         return ReplaceInstUsesWith(I, Op0);
2533       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2534         return BinaryOperator::CreateNeg(Op0, I.getName());
2535
2536       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2537       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2538         return BinaryOperator::CreateShl(Op0,
2539                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2540       }
2541     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2542       if (Op1F->isNullValue())
2543         return ReplaceInstUsesWith(I, Op1);
2544
2545       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2546       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2547       if (Op1F->isExactlyValue(1.0))
2548         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2549     } else if (isa<VectorType>(Op1->getType())) {
2550       if (isa<ConstantAggregateZero>(Op1))
2551         return ReplaceInstUsesWith(I, Op1);
2552
2553       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2554         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2555           return BinaryOperator::CreateNeg(Op0, I.getName());
2556
2557         // As above, vector X*splat(1.0) -> X in all defined cases.
2558         if (Constant *Splat = Op1V->getSplatValue()) {
2559           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2560             if (F->isExactlyValue(1.0))
2561               return ReplaceInstUsesWith(I, Op0);
2562           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2563             if (CI->equalsInt(1))
2564               return ReplaceInstUsesWith(I, Op0);
2565         }
2566       }
2567     }
2568     
2569     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2570       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2571           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2572         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2573         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2574                                                      Op1, "tmp");
2575         InsertNewInstBefore(Add, I);
2576         Value *C1C2 = ConstantExpr::getMul(Op1, 
2577                                            cast<Constant>(Op0I->getOperand(1)));
2578         return BinaryOperator::CreateAdd(Add, C1C2);
2579         
2580       }
2581
2582     // Try to fold constant mul into select arguments.
2583     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2584       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2585         return R;
2586
2587     if (isa<PHINode>(Op0))
2588       if (Instruction *NV = FoldOpIntoPhi(I))
2589         return NV;
2590   }
2591
2592   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2593     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2594       return BinaryOperator::CreateMul(Op0v, Op1v);
2595
2596   // (X / Y) *  Y = X - (X % Y)
2597   // (X / Y) * -Y = (X % Y) - X
2598   {
2599     Value *Op1 = I.getOperand(1);
2600     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2601     if (!BO ||
2602         (BO->getOpcode() != Instruction::UDiv && 
2603          BO->getOpcode() != Instruction::SDiv)) {
2604       Op1 = Op0;
2605       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2606     }
2607     Value *Neg = dyn_castNegVal(Op1);
2608     if (BO && BO->hasOneUse() &&
2609         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2610         (BO->getOpcode() == Instruction::UDiv ||
2611          BO->getOpcode() == Instruction::SDiv)) {
2612       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2613
2614       Instruction *Rem;
2615       if (BO->getOpcode() == Instruction::UDiv)
2616         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2617       else
2618         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2619
2620       InsertNewInstBefore(Rem, I);
2621       Rem->takeName(BO);
2622
2623       if (Op1BO == Op1)
2624         return BinaryOperator::CreateSub(Op0BO, Rem);
2625       else
2626         return BinaryOperator::CreateSub(Rem, Op0BO);
2627     }
2628   }
2629
2630   if (I.getType() == Type::Int1Ty)
2631     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2632
2633   // If one of the operands of the multiply is a cast from a boolean value, then
2634   // we know the bool is either zero or one, so this is a 'masking' multiply.
2635   // See if we can simplify things based on how the boolean was originally
2636   // formed.
2637   CastInst *BoolCast = 0;
2638   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2639     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2640       BoolCast = CI;
2641   if (!BoolCast)
2642     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2643       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2644         BoolCast = CI;
2645   if (BoolCast) {
2646     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2647       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2648       const Type *SCOpTy = SCIOp0->getType();
2649       bool TIS = false;
2650       
2651       // If the icmp is true iff the sign bit of X is set, then convert this
2652       // multiply into a shift/and combination.
2653       if (isa<ConstantInt>(SCIOp1) &&
2654           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2655           TIS) {
2656         // Shift the X value right to turn it into "all signbits".
2657         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2658                                           SCOpTy->getPrimitiveSizeInBits()-1);
2659         Value *V =
2660           InsertNewInstBefore(
2661             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2662                                             BoolCast->getOperand(0)->getName()+
2663                                             ".mask"), I);
2664
2665         // If the multiply type is not the same as the source type, sign extend
2666         // or truncate to the multiply type.
2667         if (I.getType() != V->getType()) {
2668           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2669           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2670           Instruction::CastOps opcode = 
2671             (SrcBits == DstBits ? Instruction::BitCast : 
2672              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2673           V = InsertCastBefore(opcode, V, I.getType(), I);
2674         }
2675
2676         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2677         return BinaryOperator::CreateAnd(V, OtherOp);
2678       }
2679     }
2680   }
2681
2682   return Changed ? &I : 0;
2683 }
2684
2685 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2686 /// instruction.
2687 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2688   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2689   
2690   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2691   int NonNullOperand = -1;
2692   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2693     if (ST->isNullValue())
2694       NonNullOperand = 2;
2695   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2696   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2697     if (ST->isNullValue())
2698       NonNullOperand = 1;
2699   
2700   if (NonNullOperand == -1)
2701     return false;
2702   
2703   Value *SelectCond = SI->getOperand(0);
2704   
2705   // Change the div/rem to use 'Y' instead of the select.
2706   I.setOperand(1, SI->getOperand(NonNullOperand));
2707   
2708   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2709   // problem.  However, the select, or the condition of the select may have
2710   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2711   // propagate the known value for the select into other uses of it, and
2712   // propagate a known value of the condition into its other users.
2713   
2714   // If the select and condition only have a single use, don't bother with this,
2715   // early exit.
2716   if (SI->use_empty() && SelectCond->hasOneUse())
2717     return true;
2718   
2719   // Scan the current block backward, looking for other uses of SI.
2720   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2721   
2722   while (BBI != BBFront) {
2723     --BBI;
2724     // If we found a call to a function, we can't assume it will return, so
2725     // information from below it cannot be propagated above it.
2726     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2727       break;
2728     
2729     // Replace uses of the select or its condition with the known values.
2730     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2731          I != E; ++I) {
2732       if (*I == SI) {
2733         *I = SI->getOperand(NonNullOperand);
2734         AddToWorkList(BBI);
2735       } else if (*I == SelectCond) {
2736         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2737                                    ConstantInt::getFalse();
2738         AddToWorkList(BBI);
2739       }
2740     }
2741     
2742     // If we past the instruction, quit looking for it.
2743     if (&*BBI == SI)
2744       SI = 0;
2745     if (&*BBI == SelectCond)
2746       SelectCond = 0;
2747     
2748     // If we ran out of things to eliminate, break out of the loop.
2749     if (SelectCond == 0 && SI == 0)
2750       break;
2751     
2752   }
2753   return true;
2754 }
2755
2756
2757 /// This function implements the transforms on div instructions that work
2758 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2759 /// used by the visitors to those instructions.
2760 /// @brief Transforms common to all three div instructions
2761 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2762   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2763
2764   // undef / X -> 0        for integer.
2765   // undef / X -> undef    for FP (the undef could be a snan).
2766   if (isa<UndefValue>(Op0)) {
2767     if (Op0->getType()->isFPOrFPVector())
2768       return ReplaceInstUsesWith(I, Op0);
2769     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2770   }
2771
2772   // X / undef -> undef
2773   if (isa<UndefValue>(Op1))
2774     return ReplaceInstUsesWith(I, Op1);
2775
2776   return 0;
2777 }
2778
2779 /// This function implements the transforms common to both integer division
2780 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2781 /// division instructions.
2782 /// @brief Common integer divide transforms
2783 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2784   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2785
2786   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2787   if (Op0 == Op1) {
2788     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2789       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2790       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2791       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2792     }
2793
2794     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2795     return ReplaceInstUsesWith(I, CI);
2796   }
2797   
2798   if (Instruction *Common = commonDivTransforms(I))
2799     return Common;
2800   
2801   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2802   // This does not apply for fdiv.
2803   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2804     return &I;
2805
2806   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2807     // div X, 1 == X
2808     if (RHS->equalsInt(1))
2809       return ReplaceInstUsesWith(I, Op0);
2810
2811     // (X / C1) / C2  -> X / (C1*C2)
2812     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2813       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2814         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2815           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2816             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2817           else 
2818             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2819                                           Multiply(RHS, LHSRHS));
2820         }
2821
2822     if (!RHS->isZero()) { // avoid X udiv 0
2823       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2824         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2825           return R;
2826       if (isa<PHINode>(Op0))
2827         if (Instruction *NV = FoldOpIntoPhi(I))
2828           return NV;
2829     }
2830   }
2831
2832   // 0 / X == 0, we don't need to preserve faults!
2833   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2834     if (LHS->equalsInt(0))
2835       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2836
2837   // It can't be division by zero, hence it must be division by one.
2838   if (I.getType() == Type::Int1Ty)
2839     return ReplaceInstUsesWith(I, Op0);
2840
2841   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2842     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2843       // div X, 1 == X
2844       if (X->isOne())
2845         return ReplaceInstUsesWith(I, Op0);
2846   }
2847
2848   return 0;
2849 }
2850
2851 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2852   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2853
2854   // Handle the integer div common cases
2855   if (Instruction *Common = commonIDivTransforms(I))
2856     return Common;
2857
2858   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2859     // X udiv C^2 -> X >> C
2860     // Check to see if this is an unsigned division with an exact power of 2,
2861     // if so, convert to a right shift.
2862     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2863       return BinaryOperator::CreateLShr(Op0, 
2864                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2865
2866     // X udiv C, where C >= signbit
2867     if (C->getValue().isNegative()) {
2868       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2869                                       I);
2870       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2871                                 ConstantInt::get(I.getType(), 1));
2872     }
2873   }
2874
2875   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2876   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2877     if (RHSI->getOpcode() == Instruction::Shl &&
2878         isa<ConstantInt>(RHSI->getOperand(0))) {
2879       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2880       if (C1.isPowerOf2()) {
2881         Value *N = RHSI->getOperand(1);
2882         const Type *NTy = N->getType();
2883         if (uint32_t C2 = C1.logBase2()) {
2884           Constant *C2V = ConstantInt::get(NTy, C2);
2885           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2886         }
2887         return BinaryOperator::CreateLShr(Op0, N);
2888       }
2889     }
2890   }
2891   
2892   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2893   // where C1&C2 are powers of two.
2894   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2895     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2896       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2897         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2898         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2899           // Compute the shift amounts
2900           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2901           // Construct the "on true" case of the select
2902           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2903           Instruction *TSI = BinaryOperator::CreateLShr(
2904                                                  Op0, TC, SI->getName()+".t");
2905           TSI = InsertNewInstBefore(TSI, I);
2906   
2907           // Construct the "on false" case of the select
2908           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2909           Instruction *FSI = BinaryOperator::CreateLShr(
2910                                                  Op0, FC, SI->getName()+".f");
2911           FSI = InsertNewInstBefore(FSI, I);
2912
2913           // construct the select instruction and return it.
2914           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2915         }
2916       }
2917   return 0;
2918 }
2919
2920 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2921   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2922
2923   // Handle the integer div common cases
2924   if (Instruction *Common = commonIDivTransforms(I))
2925     return Common;
2926
2927   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2928     // sdiv X, -1 == -X
2929     if (RHS->isAllOnesValue())
2930       return BinaryOperator::CreateNeg(Op0);
2931   }
2932
2933   // If the sign bits of both operands are zero (i.e. we can prove they are
2934   // unsigned inputs), turn this into a udiv.
2935   if (I.getType()->isInteger()) {
2936     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2937     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2938       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2939       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2940     }
2941   }      
2942   
2943   return 0;
2944 }
2945
2946 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2947   return commonDivTransforms(I);
2948 }
2949
2950 /// This function implements the transforms on rem instructions that work
2951 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2952 /// is used by the visitors to those instructions.
2953 /// @brief Transforms common to all three rem instructions
2954 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2955   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2956
2957   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2958     if (I.getType()->isFPOrFPVector())
2959       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2960     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2961   }
2962   if (isa<UndefValue>(Op1))
2963     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2964
2965   // Handle cases involving: rem X, (select Cond, Y, Z)
2966   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2967     return &I;
2968
2969   return 0;
2970 }
2971
2972 /// This function implements the transforms common to both integer remainder
2973 /// instructions (urem and srem). It is called by the visitors to those integer
2974 /// remainder instructions.
2975 /// @brief Common integer remainder transforms
2976 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2977   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2978
2979   if (Instruction *common = commonRemTransforms(I))
2980     return common;
2981
2982   // 0 % X == 0 for integer, we don't need to preserve faults!
2983   if (Constant *LHS = dyn_cast<Constant>(Op0))
2984     if (LHS->isNullValue())
2985       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2986
2987   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2988     // X % 0 == undef, we don't need to preserve faults!
2989     if (RHS->equalsInt(0))
2990       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2991     
2992     if (RHS->equalsInt(1))  // X % 1 == 0
2993       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2994
2995     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2996       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2997         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2998           return R;
2999       } else if (isa<PHINode>(Op0I)) {
3000         if (Instruction *NV = FoldOpIntoPhi(I))
3001           return NV;
3002       }
3003
3004       // See if we can fold away this rem instruction.
3005       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3006       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3007       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3008                                KnownZero, KnownOne))
3009         return &I;
3010     }
3011   }
3012
3013   return 0;
3014 }
3015
3016 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3017   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3018
3019   if (Instruction *common = commonIRemTransforms(I))
3020     return common;
3021   
3022   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3023     // X urem C^2 -> X and C
3024     // Check to see if this is an unsigned remainder with an exact power of 2,
3025     // if so, convert to a bitwise and.
3026     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3027       if (C->getValue().isPowerOf2())
3028         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3029   }
3030
3031   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3032     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3033     if (RHSI->getOpcode() == Instruction::Shl &&
3034         isa<ConstantInt>(RHSI->getOperand(0))) {
3035       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3036         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3037         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3038                                                                    "tmp"), I);
3039         return BinaryOperator::CreateAnd(Op0, Add);
3040       }
3041     }
3042   }
3043
3044   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3045   // where C1&C2 are powers of two.
3046   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3047     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3048       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3049         // STO == 0 and SFO == 0 handled above.
3050         if ((STO->getValue().isPowerOf2()) && 
3051             (SFO->getValue().isPowerOf2())) {
3052           Value *TrueAnd = InsertNewInstBefore(
3053             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3054           Value *FalseAnd = InsertNewInstBefore(
3055             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3056           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3057         }
3058       }
3059   }
3060   
3061   return 0;
3062 }
3063
3064 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3065   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3066
3067   // Handle the integer rem common cases
3068   if (Instruction *common = commonIRemTransforms(I))
3069     return common;
3070   
3071   if (Value *RHSNeg = dyn_castNegVal(Op1))
3072     if (!isa<Constant>(RHSNeg) ||
3073         (isa<ConstantInt>(RHSNeg) &&
3074          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3075       // X % -Y -> X % Y
3076       AddUsesToWorkList(I);
3077       I.setOperand(1, RHSNeg);
3078       return &I;
3079     }
3080
3081   // If the sign bits of both operands are zero (i.e. we can prove they are
3082   // unsigned inputs), turn this into a urem.
3083   if (I.getType()->isInteger()) {
3084     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3085     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3086       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3087       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3088     }
3089   }
3090
3091   // If it's a constant vector, flip any negative values positive.
3092   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3093     unsigned VWidth = RHSV->getNumOperands();
3094
3095     bool hasNegative = false;
3096     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3097       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3098         if (RHS->getValue().isNegative())
3099           hasNegative = true;
3100
3101     if (hasNegative) {
3102       std::vector<Constant *> Elts(VWidth);
3103       for (unsigned i = 0; i != VWidth; ++i) {
3104         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3105           if (RHS->getValue().isNegative())
3106             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3107           else
3108             Elts[i] = RHS;
3109         }
3110       }
3111
3112       Constant *NewRHSV = ConstantVector::get(Elts);
3113       if (NewRHSV != RHSV) {
3114         AddUsesToWorkList(I);
3115         I.setOperand(1, NewRHSV);
3116         return &I;
3117       }
3118     }
3119   }
3120
3121   return 0;
3122 }
3123
3124 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3125   return commonRemTransforms(I);
3126 }
3127
3128 // isOneBitSet - Return true if there is exactly one bit set in the specified
3129 // constant.
3130 static bool isOneBitSet(const ConstantInt *CI) {
3131   return CI->getValue().isPowerOf2();
3132 }
3133
3134 // isHighOnes - Return true if the constant is of the form 1+0+.
3135 // This is the same as lowones(~X).
3136 static bool isHighOnes(const ConstantInt *CI) {
3137   return (~CI->getValue() + 1).isPowerOf2();
3138 }
3139
3140 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3141 /// are carefully arranged to allow folding of expressions such as:
3142 ///
3143 ///      (A < B) | (A > B) --> (A != B)
3144 ///
3145 /// Note that this is only valid if the first and second predicates have the
3146 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3147 ///
3148 /// Three bits are used to represent the condition, as follows:
3149 ///   0  A > B
3150 ///   1  A == B
3151 ///   2  A < B
3152 ///
3153 /// <=>  Value  Definition
3154 /// 000     0   Always false
3155 /// 001     1   A >  B
3156 /// 010     2   A == B
3157 /// 011     3   A >= B
3158 /// 100     4   A <  B
3159 /// 101     5   A != B
3160 /// 110     6   A <= B
3161 /// 111     7   Always true
3162 ///  
3163 static unsigned getICmpCode(const ICmpInst *ICI) {
3164   switch (ICI->getPredicate()) {
3165     // False -> 0
3166   case ICmpInst::ICMP_UGT: return 1;  // 001
3167   case ICmpInst::ICMP_SGT: return 1;  // 001
3168   case ICmpInst::ICMP_EQ:  return 2;  // 010
3169   case ICmpInst::ICMP_UGE: return 3;  // 011
3170   case ICmpInst::ICMP_SGE: return 3;  // 011
3171   case ICmpInst::ICMP_ULT: return 4;  // 100
3172   case ICmpInst::ICMP_SLT: return 4;  // 100
3173   case ICmpInst::ICMP_NE:  return 5;  // 101
3174   case ICmpInst::ICMP_ULE: return 6;  // 110
3175   case ICmpInst::ICMP_SLE: return 6;  // 110
3176     // True -> 7
3177   default:
3178     assert(0 && "Invalid ICmp predicate!");
3179     return 0;
3180   }
3181 }
3182
3183 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3184 /// predicate into a three bit mask. It also returns whether it is an ordered
3185 /// predicate by reference.
3186 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3187   isOrdered = false;
3188   switch (CC) {
3189   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3190   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3191   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3192   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3193   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3194   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3195   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3196   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3197   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3198   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3199   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3200   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3201   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3202   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3203     // True -> 7
3204   default:
3205     // Not expecting FCMP_FALSE and FCMP_TRUE;
3206     assert(0 && "Unexpected FCmp predicate!");
3207     return 0;
3208   }
3209 }
3210
3211 /// getICmpValue - This is the complement of getICmpCode, which turns an
3212 /// opcode and two operands into either a constant true or false, or a brand 
3213 /// new ICmp instruction. The sign is passed in to determine which kind
3214 /// of predicate to use in the new icmp instruction.
3215 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3216   switch (code) {
3217   default: assert(0 && "Illegal ICmp code!");
3218   case  0: return ConstantInt::getFalse();
3219   case  1: 
3220     if (sign)
3221       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3222     else
3223       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3224   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3225   case  3: 
3226     if (sign)
3227       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3228     else
3229       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3230   case  4: 
3231     if (sign)
3232       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3233     else
3234       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3235   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3236   case  6: 
3237     if (sign)
3238       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3239     else
3240       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3241   case  7: return ConstantInt::getTrue();
3242   }
3243 }
3244
3245 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3246 /// opcode and two operands into either a FCmp instruction. isordered is passed
3247 /// in to determine which kind of predicate to use in the new fcmp instruction.
3248 static Value *getFCmpValue(bool isordered, unsigned code,
3249                            Value *LHS, Value *RHS) {
3250   switch (code) {
3251   default: assert(0 && "Illegal FCmp code!");
3252   case  0:
3253     if (isordered)
3254       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3255     else
3256       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3257   case  1: 
3258     if (isordered)
3259       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3260     else
3261       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3262   case  2: 
3263     if (isordered)
3264       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3265     else
3266       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3267   case  3: 
3268     if (isordered)
3269       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3270     else
3271       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3272   case  4: 
3273     if (isordered)
3274       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3275     else
3276       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3277   case  5: 
3278     if (isordered)
3279       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3280     else
3281       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3282   case  6: 
3283     if (isordered)
3284       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3285     else
3286       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3287   case  7: return ConstantInt::getTrue();
3288   }
3289 }
3290
3291 /// PredicatesFoldable - Return true if both predicates match sign or if at
3292 /// least one of them is an equality comparison (which is signless).
3293 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3294   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3295          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3296          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3297 }
3298
3299 namespace { 
3300 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3301 struct FoldICmpLogical {
3302   InstCombiner &IC;
3303   Value *LHS, *RHS;
3304   ICmpInst::Predicate pred;
3305   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3306     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3307       pred(ICI->getPredicate()) {}
3308   bool shouldApply(Value *V) const {
3309     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3310       if (PredicatesFoldable(pred, ICI->getPredicate()))
3311         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3312                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3313     return false;
3314   }
3315   Instruction *apply(Instruction &Log) const {
3316     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3317     if (ICI->getOperand(0) != LHS) {
3318       assert(ICI->getOperand(1) == LHS);
3319       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3320     }
3321
3322     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3323     unsigned LHSCode = getICmpCode(ICI);
3324     unsigned RHSCode = getICmpCode(RHSICI);
3325     unsigned Code;
3326     switch (Log.getOpcode()) {
3327     case Instruction::And: Code = LHSCode & RHSCode; break;
3328     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3329     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3330     default: assert(0 && "Illegal logical opcode!"); return 0;
3331     }
3332
3333     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3334                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3335       
3336     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3337     if (Instruction *I = dyn_cast<Instruction>(RV))
3338       return I;
3339     // Otherwise, it's a constant boolean value...
3340     return IC.ReplaceInstUsesWith(Log, RV);
3341   }
3342 };
3343 } // end anonymous namespace
3344
3345 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3346 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3347 // guaranteed to be a binary operator.
3348 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3349                                     ConstantInt *OpRHS,
3350                                     ConstantInt *AndRHS,
3351                                     BinaryOperator &TheAnd) {
3352   Value *X = Op->getOperand(0);
3353   Constant *Together = 0;
3354   if (!Op->isShift())
3355     Together = And(AndRHS, OpRHS);
3356
3357   switch (Op->getOpcode()) {
3358   case Instruction::Xor:
3359     if (Op->hasOneUse()) {
3360       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3361       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3362       InsertNewInstBefore(And, TheAnd);
3363       And->takeName(Op);
3364       return BinaryOperator::CreateXor(And, Together);
3365     }
3366     break;
3367   case Instruction::Or:
3368     if (Together == AndRHS) // (X | C) & C --> C
3369       return ReplaceInstUsesWith(TheAnd, AndRHS);
3370
3371     if (Op->hasOneUse() && Together != OpRHS) {
3372       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3373       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3374       InsertNewInstBefore(Or, TheAnd);
3375       Or->takeName(Op);
3376       return BinaryOperator::CreateAnd(Or, AndRHS);
3377     }
3378     break;
3379   case Instruction::Add:
3380     if (Op->hasOneUse()) {
3381       // Adding a one to a single bit bit-field should be turned into an XOR
3382       // of the bit.  First thing to check is to see if this AND is with a
3383       // single bit constant.
3384       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3385
3386       // If there is only one bit set...
3387       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3388         // Ok, at this point, we know that we are masking the result of the
3389         // ADD down to exactly one bit.  If the constant we are adding has
3390         // no bits set below this bit, then we can eliminate the ADD.
3391         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3392
3393         // Check to see if any bits below the one bit set in AndRHSV are set.
3394         if ((AddRHS & (AndRHSV-1)) == 0) {
3395           // If not, the only thing that can effect the output of the AND is
3396           // the bit specified by AndRHSV.  If that bit is set, the effect of
3397           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3398           // no effect.
3399           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3400             TheAnd.setOperand(0, X);
3401             return &TheAnd;
3402           } else {
3403             // Pull the XOR out of the AND.
3404             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3405             InsertNewInstBefore(NewAnd, TheAnd);
3406             NewAnd->takeName(Op);
3407             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3408           }
3409         }
3410       }
3411     }
3412     break;
3413
3414   case Instruction::Shl: {
3415     // We know that the AND will not produce any of the bits shifted in, so if
3416     // the anded constant includes them, clear them now!
3417     //
3418     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3419     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3420     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3421     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3422
3423     if (CI->getValue() == ShlMask) { 
3424     // Masking out bits that the shift already masks
3425       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3426     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3427       TheAnd.setOperand(1, CI);
3428       return &TheAnd;
3429     }
3430     break;
3431   }
3432   case Instruction::LShr:
3433   {
3434     // We know that the AND will not produce any of the bits shifted in, so if
3435     // the anded constant includes them, clear them now!  This only applies to
3436     // unsigned shifts, because a signed shr may bring in set bits!
3437     //
3438     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3439     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3440     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3441     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3442
3443     if (CI->getValue() == ShrMask) {   
3444     // Masking out bits that the shift already masks.
3445       return ReplaceInstUsesWith(TheAnd, Op);
3446     } else if (CI != AndRHS) {
3447       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3448       return &TheAnd;
3449     }
3450     break;
3451   }
3452   case Instruction::AShr:
3453     // Signed shr.
3454     // See if this is shifting in some sign extension, then masking it out
3455     // with an and.
3456     if (Op->hasOneUse()) {
3457       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3458       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3459       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3460       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3461       if (C == AndRHS) {          // Masking out bits shifted in.
3462         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3463         // Make the argument unsigned.
3464         Value *ShVal = Op->getOperand(0);
3465         ShVal = InsertNewInstBefore(
3466             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3467                                    Op->getName()), TheAnd);
3468         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3469       }
3470     }
3471     break;
3472   }
3473   return 0;
3474 }
3475
3476
3477 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3478 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3479 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3480 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3481 /// insert new instructions.
3482 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3483                                            bool isSigned, bool Inside, 
3484                                            Instruction &IB) {
3485   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3486             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3487          "Lo is not <= Hi in range emission code!");
3488     
3489   if (Inside) {
3490     if (Lo == Hi)  // Trivially false.
3491       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3492
3493     // V >= Min && V < Hi --> V < Hi
3494     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3495       ICmpInst::Predicate pred = (isSigned ? 
3496         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3497       return new ICmpInst(pred, V, Hi);
3498     }
3499
3500     // Emit V-Lo <u Hi-Lo
3501     Constant *NegLo = ConstantExpr::getNeg(Lo);
3502     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3503     InsertNewInstBefore(Add, IB);
3504     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3505     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3506   }
3507
3508   if (Lo == Hi)  // Trivially true.
3509     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3510
3511   // V < Min || V >= Hi -> V > Hi-1
3512   Hi = SubOne(cast<ConstantInt>(Hi));
3513   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3514     ICmpInst::Predicate pred = (isSigned ? 
3515         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3516     return new ICmpInst(pred, V, Hi);
3517   }
3518
3519   // Emit V-Lo >u Hi-1-Lo
3520   // Note that Hi has already had one subtracted from it, above.
3521   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3522   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3523   InsertNewInstBefore(Add, IB);
3524   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3525   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3526 }
3527
3528 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3529 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3530 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3531 // not, since all 1s are not contiguous.
3532 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3533   const APInt& V = Val->getValue();
3534   uint32_t BitWidth = Val->getType()->getBitWidth();
3535   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3536
3537   // look for the first zero bit after the run of ones
3538   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3539   // look for the first non-zero bit
3540   ME = V.getActiveBits(); 
3541   return true;
3542 }
3543
3544 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3545 /// where isSub determines whether the operator is a sub.  If we can fold one of
3546 /// the following xforms:
3547 /// 
3548 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3549 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3550 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3551 ///
3552 /// return (A +/- B).
3553 ///
3554 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3555                                         ConstantInt *Mask, bool isSub,
3556                                         Instruction &I) {
3557   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3558   if (!LHSI || LHSI->getNumOperands() != 2 ||
3559       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3560
3561   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3562
3563   switch (LHSI->getOpcode()) {
3564   default: return 0;
3565   case Instruction::And:
3566     if (And(N, Mask) == Mask) {
3567       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3568       if ((Mask->getValue().countLeadingZeros() + 
3569            Mask->getValue().countPopulation()) == 
3570           Mask->getValue().getBitWidth())
3571         break;
3572
3573       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3574       // part, we don't need any explicit masks to take them out of A.  If that
3575       // is all N is, ignore it.
3576       uint32_t MB = 0, ME = 0;
3577       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3578         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3579         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3580         if (MaskedValueIsZero(RHS, Mask))
3581           break;
3582       }
3583     }
3584     return 0;
3585   case Instruction::Or:
3586   case Instruction::Xor:
3587     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3588     if ((Mask->getValue().countLeadingZeros() + 
3589          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3590         && And(N, Mask)->isZero())
3591       break;
3592     return 0;
3593   }
3594   
3595   Instruction *New;
3596   if (isSub)
3597     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3598   else
3599     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3600   return InsertNewInstBefore(New, I);
3601 }
3602
3603 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3604 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3605                                           ICmpInst *LHS, ICmpInst *RHS) {
3606   Value *Val, *Val2;
3607   ConstantInt *LHSCst, *RHSCst;
3608   ICmpInst::Predicate LHSCC, RHSCC;
3609   
3610   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3611   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3612       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3613     return 0;
3614   
3615   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3616   // where C is a power of 2
3617   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3618       LHSCst->getValue().isPowerOf2()) {
3619     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3620     InsertNewInstBefore(NewOr, I);
3621     return new ICmpInst(LHSCC, NewOr, LHSCst);
3622   }
3623   
3624   // From here on, we only handle:
3625   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3626   if (Val != Val2) return 0;
3627   
3628   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3629   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3630       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3631       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3632       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3633     return 0;
3634   
3635   // We can't fold (ugt x, C) & (sgt x, C2).
3636   if (!PredicatesFoldable(LHSCC, RHSCC))
3637     return 0;
3638     
3639   // Ensure that the larger constant is on the RHS.
3640   bool ShouldSwap;
3641   if (ICmpInst::isSignedPredicate(LHSCC) ||
3642       (ICmpInst::isEquality(LHSCC) && 
3643        ICmpInst::isSignedPredicate(RHSCC)))
3644     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3645   else
3646     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3647     
3648   if (ShouldSwap) {
3649     std::swap(LHS, RHS);
3650     std::swap(LHSCst, RHSCst);
3651     std::swap(LHSCC, RHSCC);
3652   }
3653
3654   // At this point, we know we have have two icmp instructions
3655   // comparing a value against two constants and and'ing the result
3656   // together.  Because of the above check, we know that we only have
3657   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3658   // (from the FoldICmpLogical check above), that the two constants 
3659   // are not equal and that the larger constant is on the RHS
3660   assert(LHSCst != RHSCst && "Compares not folded above?");
3661
3662   switch (LHSCC) {
3663   default: assert(0 && "Unknown integer condition code!");
3664   case ICmpInst::ICMP_EQ:
3665     switch (RHSCC) {
3666     default: assert(0 && "Unknown integer condition code!");
3667     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3668     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3669     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3670       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3671     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3672     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3673     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3674       return ReplaceInstUsesWith(I, LHS);
3675     }
3676   case ICmpInst::ICMP_NE:
3677     switch (RHSCC) {
3678     default: assert(0 && "Unknown integer condition code!");
3679     case ICmpInst::ICMP_ULT:
3680       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3681         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3682       break;                        // (X != 13 & X u< 15) -> no change
3683     case ICmpInst::ICMP_SLT:
3684       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3685         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3686       break;                        // (X != 13 & X s< 15) -> no change
3687     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3688     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3689     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3690       return ReplaceInstUsesWith(I, RHS);
3691     case ICmpInst::ICMP_NE:
3692       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3693         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3694         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3695                                                      Val->getName()+".off");
3696         InsertNewInstBefore(Add, I);
3697         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3698                             ConstantInt::get(Add->getType(), 1));
3699       }
3700       break;                        // (X != 13 & X != 15) -> no change
3701     }
3702     break;
3703   case ICmpInst::ICMP_ULT:
3704     switch (RHSCC) {
3705     default: assert(0 && "Unknown integer condition code!");
3706     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3707     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3708       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3709     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3710       break;
3711     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3712     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3713       return ReplaceInstUsesWith(I, LHS);
3714     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3715       break;
3716     }
3717     break;
3718   case ICmpInst::ICMP_SLT:
3719     switch (RHSCC) {
3720     default: assert(0 && "Unknown integer condition code!");
3721     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3722     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3723       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3724     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3725       break;
3726     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3727     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3728       return ReplaceInstUsesWith(I, LHS);
3729     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3730       break;
3731     }
3732     break;
3733   case ICmpInst::ICMP_UGT:
3734     switch (RHSCC) {
3735     default: assert(0 && "Unknown integer condition code!");
3736     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3737     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3738       return ReplaceInstUsesWith(I, RHS);
3739     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3740       break;
3741     case ICmpInst::ICMP_NE:
3742       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3743         return new ICmpInst(LHSCC, Val, RHSCst);
3744       break;                        // (X u> 13 & X != 15) -> no change
3745     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3746       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3747     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3748       break;
3749     }
3750     break;
3751   case ICmpInst::ICMP_SGT:
3752     switch (RHSCC) {
3753     default: assert(0 && "Unknown integer condition code!");
3754     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3755     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3756       return ReplaceInstUsesWith(I, RHS);
3757     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3758       break;
3759     case ICmpInst::ICMP_NE:
3760       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3761         return new ICmpInst(LHSCC, Val, RHSCst);
3762       break;                        // (X s> 13 & X != 15) -> no change
3763     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3764       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3765     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3766       break;
3767     }
3768     break;
3769   }
3770  
3771   return 0;
3772 }
3773
3774
3775 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3776   bool Changed = SimplifyCommutative(I);
3777   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3778
3779   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3780     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3781
3782   // and X, X = X
3783   if (Op0 == Op1)
3784     return ReplaceInstUsesWith(I, Op1);
3785
3786   // See if we can simplify any instructions used by the instruction whose sole 
3787   // purpose is to compute bits we don't care about.
3788   if (!isa<VectorType>(I.getType())) {
3789     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3790     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3791     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3792                              KnownZero, KnownOne))
3793       return &I;
3794   } else {
3795     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3796       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3797         return ReplaceInstUsesWith(I, I.getOperand(0));
3798     } else if (isa<ConstantAggregateZero>(Op1)) {
3799       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3800     }
3801   }
3802   
3803   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3804     const APInt& AndRHSMask = AndRHS->getValue();
3805     APInt NotAndRHS(~AndRHSMask);
3806
3807     // Optimize a variety of ((val OP C1) & C2) combinations...
3808     if (isa<BinaryOperator>(Op0)) {
3809       Instruction *Op0I = cast<Instruction>(Op0);
3810       Value *Op0LHS = Op0I->getOperand(0);
3811       Value *Op0RHS = Op0I->getOperand(1);
3812       switch (Op0I->getOpcode()) {
3813       case Instruction::Xor:
3814       case Instruction::Or:
3815         // If the mask is only needed on one incoming arm, push it up.
3816         if (Op0I->hasOneUse()) {
3817           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3818             // Not masking anything out for the LHS, move to RHS.
3819             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3820                                                    Op0RHS->getName()+".masked");
3821             InsertNewInstBefore(NewRHS, I);
3822             return BinaryOperator::Create(
3823                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3824           }
3825           if (!isa<Constant>(Op0RHS) &&
3826               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3827             // Not masking anything out for the RHS, move to LHS.
3828             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3829                                                    Op0LHS->getName()+".masked");
3830             InsertNewInstBefore(NewLHS, I);
3831             return BinaryOperator::Create(
3832                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3833           }
3834         }
3835
3836         break;
3837       case Instruction::Add:
3838         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3839         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3840         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3841         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3842           return BinaryOperator::CreateAnd(V, AndRHS);
3843         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3844           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3845         break;
3846
3847       case Instruction::Sub:
3848         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3849         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3850         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3851         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3852           return BinaryOperator::CreateAnd(V, AndRHS);
3853
3854         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3855         // has 1's for all bits that the subtraction with A might affect.
3856         if (Op0I->hasOneUse()) {
3857           uint32_t BitWidth = AndRHSMask.getBitWidth();
3858           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3859           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3860
3861           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3862           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3863               MaskedValueIsZero(Op0LHS, Mask)) {
3864             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3865             InsertNewInstBefore(NewNeg, I);
3866             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3867           }
3868         }
3869         break;
3870
3871       case Instruction::Shl:
3872       case Instruction::LShr:
3873         // (1 << x) & 1 --> zext(x == 0)
3874         // (1 >> x) & 1 --> zext(x == 0)
3875         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3876           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3877                                            Constant::getNullValue(I.getType()));
3878           InsertNewInstBefore(NewICmp, I);
3879           return new ZExtInst(NewICmp, I.getType());
3880         }
3881         break;
3882       }
3883
3884       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3885         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3886           return Res;
3887     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3888       // If this is an integer truncation or change from signed-to-unsigned, and
3889       // if the source is an and/or with immediate, transform it.  This
3890       // frequently occurs for bitfield accesses.
3891       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3892         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3893             CastOp->getNumOperands() == 2)
3894           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3895             if (CastOp->getOpcode() == Instruction::And) {
3896               // Change: and (cast (and X, C1) to T), C2
3897               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3898               // This will fold the two constants together, which may allow 
3899               // other simplifications.
3900               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3901                 CastOp->getOperand(0), I.getType(), 
3902                 CastOp->getName()+".shrunk");
3903               NewCast = InsertNewInstBefore(NewCast, I);
3904               // trunc_or_bitcast(C1)&C2
3905               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3906               C3 = ConstantExpr::getAnd(C3, AndRHS);
3907               return BinaryOperator::CreateAnd(NewCast, C3);
3908             } else if (CastOp->getOpcode() == Instruction::Or) {
3909               // Change: and (cast (or X, C1) to T), C2
3910               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3911               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3912               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3913                 return ReplaceInstUsesWith(I, AndRHS);
3914             }
3915           }
3916       }
3917     }
3918
3919     // Try to fold constant and into select arguments.
3920     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3921       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3922         return R;
3923     if (isa<PHINode>(Op0))
3924       if (Instruction *NV = FoldOpIntoPhi(I))
3925         return NV;
3926   }
3927
3928   Value *Op0NotVal = dyn_castNotVal(Op0);
3929   Value *Op1NotVal = dyn_castNotVal(Op1);
3930
3931   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3932     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3933
3934   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3935   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3936     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3937                                                I.getName()+".demorgan");
3938     InsertNewInstBefore(Or, I);
3939     return BinaryOperator::CreateNot(Or);
3940   }
3941   
3942   {
3943     Value *A = 0, *B = 0, *C = 0, *D = 0;
3944     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3945       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3946         return ReplaceInstUsesWith(I, Op1);
3947     
3948       // (A|B) & ~(A&B) -> A^B
3949       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3950         if ((A == C && B == D) || (A == D && B == C))
3951           return BinaryOperator::CreateXor(A, B);
3952       }
3953     }
3954     
3955     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3956       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3957         return ReplaceInstUsesWith(I, Op0);
3958
3959       // ~(A&B) & (A|B) -> A^B
3960       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3961         if ((A == C && B == D) || (A == D && B == C))
3962           return BinaryOperator::CreateXor(A, B);
3963       }
3964     }
3965     
3966     if (Op0->hasOneUse() &&
3967         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3968       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3969         I.swapOperands();     // Simplify below
3970         std::swap(Op0, Op1);
3971       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3972         cast<BinaryOperator>(Op0)->swapOperands();
3973         I.swapOperands();     // Simplify below
3974         std::swap(Op0, Op1);
3975       }
3976     }
3977
3978     if (Op1->hasOneUse() &&
3979         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3980       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3981         cast<BinaryOperator>(Op1)->swapOperands();
3982         std::swap(A, B);
3983       }
3984       if (A == Op0) {                                // A&(A^B) -> A & ~B
3985         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3986         InsertNewInstBefore(NotB, I);
3987         return BinaryOperator::CreateAnd(A, NotB);
3988       }
3989     }
3990
3991     // (A&((~A)|B)) -> A&B
3992     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
3993         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
3994       return BinaryOperator::CreateAnd(A, Op1);
3995     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
3996         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
3997       return BinaryOperator::CreateAnd(A, Op0);
3998   }
3999   
4000   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4001     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4002     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4003       return R;
4004
4005     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4006       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4007         return Res;
4008   }
4009
4010   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4011   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4012     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4013       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4014         const Type *SrcTy = Op0C->getOperand(0)->getType();
4015         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4016             // Only do this if the casts both really cause code to be generated.
4017             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4018                               I.getType(), TD) &&
4019             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4020                               I.getType(), TD)) {
4021           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4022                                                          Op1C->getOperand(0),
4023                                                          I.getName());
4024           InsertNewInstBefore(NewOp, I);
4025           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4026         }
4027       }
4028     
4029   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4030   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4031     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4032       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4033           SI0->getOperand(1) == SI1->getOperand(1) &&
4034           (SI0->hasOneUse() || SI1->hasOneUse())) {
4035         Instruction *NewOp =
4036           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4037                                                         SI1->getOperand(0),
4038                                                         SI0->getName()), I);
4039         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4040                                       SI1->getOperand(1));
4041       }
4042   }
4043
4044   // If and'ing two fcmp, try combine them into one.
4045   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4046     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4047       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4048           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4049         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4050         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4051           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4052             // If either of the constants are nans, then the whole thing returns
4053             // false.
4054             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4055               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4056             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4057                                 RHS->getOperand(0));
4058           }
4059       } else {
4060         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4061         FCmpInst::Predicate Op0CC, Op1CC;
4062         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4063             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4064           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4065             // Swap RHS operands to match LHS.
4066             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4067             std::swap(Op1LHS, Op1RHS);
4068           }
4069           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4070             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4071             if (Op0CC == Op1CC)
4072               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4073             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4074                      Op1CC == FCmpInst::FCMP_FALSE)
4075               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4076             else if (Op0CC == FCmpInst::FCMP_TRUE)
4077               return ReplaceInstUsesWith(I, Op1);
4078             else if (Op1CC == FCmpInst::FCMP_TRUE)
4079               return ReplaceInstUsesWith(I, Op0);
4080             bool Op0Ordered;
4081             bool Op1Ordered;
4082             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4083             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4084             if (Op1Pred == 0) {
4085               std::swap(Op0, Op1);
4086               std::swap(Op0Pred, Op1Pred);
4087               std::swap(Op0Ordered, Op1Ordered);
4088             }
4089             if (Op0Pred == 0) {
4090               // uno && ueq -> uno && (uno || eq) -> ueq
4091               // ord && olt -> ord && (ord && lt) -> olt
4092               if (Op0Ordered == Op1Ordered)
4093                 return ReplaceInstUsesWith(I, Op1);
4094               // uno && oeq -> uno && (ord && eq) -> false
4095               // uno && ord -> false
4096               if (!Op0Ordered)
4097                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4098               // ord && ueq -> ord && (uno || eq) -> oeq
4099               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4100                                                     Op0LHS, Op0RHS));
4101             }
4102           }
4103         }
4104       }
4105     }
4106   }
4107
4108   return Changed ? &I : 0;
4109 }
4110
4111 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4112 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4113 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4114 /// the expression came from the corresponding "byte swapped" byte in some other
4115 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4116 /// we know that the expression deposits the low byte of %X into the high byte
4117 /// of the bswap result and that all other bytes are zero.  This expression is
4118 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4119 /// match.
4120 ///
4121 /// This function returns true if the match was unsuccessful and false if so.
4122 /// On entry to the function the "OverallLeftShift" is a signed integer value
4123 /// indicating the number of bytes that the subexpression is later shifted.  For
4124 /// example, if the expression is later right shifted by 16 bits, the
4125 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4126 /// byte of ByteValues is actually being set.
4127 ///
4128 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4129 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4130 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4131 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4132 /// always in the local (OverallLeftShift) coordinate space.
4133 ///
4134 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4135                               SmallVector<Value*, 8> &ByteValues) {
4136   if (Instruction *I = dyn_cast<Instruction>(V)) {
4137     // If this is an or instruction, it may be an inner node of the bswap.
4138     if (I->getOpcode() == Instruction::Or) {
4139       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4140                                ByteValues) ||
4141              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4142                                ByteValues);
4143     }
4144   
4145     // If this is a logical shift by a constant multiple of 8, recurse with
4146     // OverallLeftShift and ByteMask adjusted.
4147     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4148       unsigned ShAmt = 
4149         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4150       // Ensure the shift amount is defined and of a byte value.
4151       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4152         return true;
4153
4154       unsigned ByteShift = ShAmt >> 3;
4155       if (I->getOpcode() == Instruction::Shl) {
4156         // X << 2 -> collect(X, +2)
4157         OverallLeftShift += ByteShift;
4158         ByteMask >>= ByteShift;
4159       } else {
4160         // X >>u 2 -> collect(X, -2)
4161         OverallLeftShift -= ByteShift;
4162         ByteMask <<= ByteShift;
4163         ByteMask &= (~0U >> (32-ByteValues.size()));
4164       }
4165
4166       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4167       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4168
4169       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4170                                ByteValues);
4171     }
4172
4173     // If this is a logical 'and' with a mask that clears bytes, clear the
4174     // corresponding bytes in ByteMask.
4175     if (I->getOpcode() == Instruction::And &&
4176         isa<ConstantInt>(I->getOperand(1))) {
4177       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4178       unsigned NumBytes = ByteValues.size();
4179       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4180       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4181       
4182       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4183         // If this byte is masked out by a later operation, we don't care what
4184         // the and mask is.
4185         if ((ByteMask & (1 << i)) == 0)
4186           continue;
4187         
4188         // If the AndMask is all zeros for this byte, clear the bit.
4189         APInt MaskB = AndMask & Byte;
4190         if (MaskB == 0) {
4191           ByteMask &= ~(1U << i);
4192           continue;
4193         }
4194         
4195         // If the AndMask is not all ones for this byte, it's not a bytezap.
4196         if (MaskB != Byte)
4197           return true;
4198
4199         // Otherwise, this byte is kept.
4200       }
4201
4202       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4203                                ByteValues);
4204     }
4205   }
4206   
4207   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4208   // the input value to the bswap.  Some observations: 1) if more than one byte
4209   // is demanded from this input, then it could not be successfully assembled
4210   // into a byteswap.  At least one of the two bytes would not be aligned with
4211   // their ultimate destination.
4212   if (!isPowerOf2_32(ByteMask)) return true;
4213   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4214   
4215   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4216   // is demanded, it needs to go into byte 0 of the result.  This means that the
4217   // byte needs to be shifted until it lands in the right byte bucket.  The
4218   // shift amount depends on the position: if the byte is coming from the high
4219   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4220   // low part, it must be shifted left.
4221   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4222   if (InputByteNo < ByteValues.size()/2) {
4223     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4224       return true;
4225   } else {
4226     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4227       return true;
4228   }
4229   
4230   // If the destination byte value is already defined, the values are or'd
4231   // together, which isn't a bswap (unless it's an or of the same bits).
4232   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4233     return true;
4234   ByteValues[DestByteNo] = V;
4235   return false;
4236 }
4237
4238 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4239 /// If so, insert the new bswap intrinsic and return it.
4240 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4241   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4242   if (!ITy || ITy->getBitWidth() % 16 || 
4243       // ByteMask only allows up to 32-byte values.
4244       ITy->getBitWidth() > 32*8) 
4245     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4246   
4247   /// ByteValues - For each byte of the result, we keep track of which value
4248   /// defines each byte.
4249   SmallVector<Value*, 8> ByteValues;
4250   ByteValues.resize(ITy->getBitWidth()/8);
4251     
4252   // Try to find all the pieces corresponding to the bswap.
4253   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4254   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4255     return 0;
4256   
4257   // Check to see if all of the bytes come from the same value.
4258   Value *V = ByteValues[0];
4259   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4260   
4261   // Check to make sure that all of the bytes come from the same value.
4262   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4263     if (ByteValues[i] != V)
4264       return 0;
4265   const Type *Tys[] = { ITy };
4266   Module *M = I.getParent()->getParent()->getParent();
4267   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4268   return CallInst::Create(F, V);
4269 }
4270
4271 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4272 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4273 /// we can simplify this expression to "cond ? C : D or B".
4274 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4275                                          Value *C, Value *D) {
4276   // If A is not a select of -1/0, this cannot match.
4277   Value *Cond = 0;
4278   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4279     return 0;
4280
4281   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4282   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4283     return SelectInst::Create(Cond, C, B);
4284   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4285     return SelectInst::Create(Cond, C, B);
4286   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4287   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4288     return SelectInst::Create(Cond, C, D);
4289   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4290     return SelectInst::Create(Cond, C, D);
4291   return 0;
4292 }
4293
4294 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4295 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4296                                          ICmpInst *LHS, ICmpInst *RHS) {
4297   Value *Val, *Val2;
4298   ConstantInt *LHSCst, *RHSCst;
4299   ICmpInst::Predicate LHSCC, RHSCC;
4300   
4301   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4302   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4303       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4304     return 0;
4305   
4306   // From here on, we only handle:
4307   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4308   if (Val != Val2) return 0;
4309   
4310   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4311   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4312       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4313       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4314       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4315     return 0;
4316   
4317   // We can't fold (ugt x, C) | (sgt x, C2).
4318   if (!PredicatesFoldable(LHSCC, RHSCC))
4319     return 0;
4320   
4321   // Ensure that the larger constant is on the RHS.
4322   bool ShouldSwap;
4323   if (ICmpInst::isSignedPredicate(LHSCC) ||
4324       (ICmpInst::isEquality(LHSCC) && 
4325        ICmpInst::isSignedPredicate(RHSCC)))
4326     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4327   else
4328     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4329   
4330   if (ShouldSwap) {
4331     std::swap(LHS, RHS);
4332     std::swap(LHSCst, RHSCst);
4333     std::swap(LHSCC, RHSCC);
4334   }
4335   
4336   // At this point, we know we have have two icmp instructions
4337   // comparing a value against two constants and or'ing the result
4338   // together.  Because of the above check, we know that we only have
4339   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4340   // FoldICmpLogical check above), that the two constants are not
4341   // equal.
4342   assert(LHSCst != RHSCst && "Compares not folded above?");
4343
4344   switch (LHSCC) {
4345   default: assert(0 && "Unknown integer condition code!");
4346   case ICmpInst::ICMP_EQ:
4347     switch (RHSCC) {
4348     default: assert(0 && "Unknown integer condition code!");
4349     case ICmpInst::ICMP_EQ:
4350       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4351         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4352         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4353                                                      Val->getName()+".off");
4354         InsertNewInstBefore(Add, I);
4355         AddCST = Subtract(AddOne(RHSCst), LHSCst);
4356         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4357       }
4358       break;                         // (X == 13 | X == 15) -> no change
4359     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4360     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4361       break;
4362     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4363     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4364     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4365       return ReplaceInstUsesWith(I, RHS);
4366     }
4367     break;
4368   case ICmpInst::ICMP_NE:
4369     switch (RHSCC) {
4370     default: assert(0 && "Unknown integer condition code!");
4371     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4372     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4373     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4374       return ReplaceInstUsesWith(I, LHS);
4375     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4376     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4377     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4378       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4379     }
4380     break;
4381   case ICmpInst::ICMP_ULT:
4382     switch (RHSCC) {
4383     default: assert(0 && "Unknown integer condition code!");
4384     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4385       break;
4386     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4387       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4388       // this can cause overflow.
4389       if (RHSCst->isMaxValue(false))
4390         return ReplaceInstUsesWith(I, LHS);
4391       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4392     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4393       break;
4394     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4395     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4396       return ReplaceInstUsesWith(I, RHS);
4397     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4398       break;
4399     }
4400     break;
4401   case ICmpInst::ICMP_SLT:
4402     switch (RHSCC) {
4403     default: assert(0 && "Unknown integer condition code!");
4404     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4405       break;
4406     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4407       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4408       // this can cause overflow.
4409       if (RHSCst->isMaxValue(true))
4410         return ReplaceInstUsesWith(I, LHS);
4411       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4412     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4413       break;
4414     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4415     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4416       return ReplaceInstUsesWith(I, RHS);
4417     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4418       break;
4419     }
4420     break;
4421   case ICmpInst::ICMP_UGT:
4422     switch (RHSCC) {
4423     default: assert(0 && "Unknown integer condition code!");
4424     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4425     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4426       return ReplaceInstUsesWith(I, LHS);
4427     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4428       break;
4429     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4430     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4431       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4432     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4433       break;
4434     }
4435     break;
4436   case ICmpInst::ICMP_SGT:
4437     switch (RHSCC) {
4438     default: assert(0 && "Unknown integer condition code!");
4439     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4440     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4441       return ReplaceInstUsesWith(I, LHS);
4442     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4443       break;
4444     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4445     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4446       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4447     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4448       break;
4449     }
4450     break;
4451   }
4452   return 0;
4453 }
4454
4455 /// FoldOrWithConstants - This helper function folds:
4456 ///
4457 ///     ((A | B) & C1) | (B & C2)
4458 ///
4459 /// into:
4460 /// 
4461 ///     (A & C1) | B
4462 ///
4463 /// when the XOR of the two constants is "all ones" (-1).
4464 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4465                                                Value *A, Value *B, Value *C) {
4466   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4467   if (!CI1) return 0;
4468
4469   Value *V1 = 0;
4470   ConstantInt *CI2 = 0;
4471   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4472
4473   APInt Xor = CI1->getValue() ^ CI2->getValue();
4474   if (!Xor.isAllOnesValue()) return 0;
4475
4476   if (V1 == A || V1 == B) {
4477     Instruction *NewOp =
4478       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4479     return BinaryOperator::CreateOr(NewOp, V1);
4480   }
4481
4482   return 0;
4483 }
4484
4485 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4486   bool Changed = SimplifyCommutative(I);
4487   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4488
4489   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4490     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4491
4492   // or X, X = X
4493   if (Op0 == Op1)
4494     return ReplaceInstUsesWith(I, Op0);
4495
4496   // See if we can simplify any instructions used by the instruction whose sole 
4497   // purpose is to compute bits we don't care about.
4498   if (!isa<VectorType>(I.getType())) {
4499     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4500     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4501     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4502                              KnownZero, KnownOne))
4503       return &I;
4504   } else if (isa<ConstantAggregateZero>(Op1)) {
4505     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4506   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4507     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4508       return ReplaceInstUsesWith(I, I.getOperand(1));
4509   }
4510     
4511
4512   
4513   // or X, -1 == -1
4514   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4515     ConstantInt *C1 = 0; Value *X = 0;
4516     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4517     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4518       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4519       InsertNewInstBefore(Or, I);
4520       Or->takeName(Op0);
4521       return BinaryOperator::CreateAnd(Or, 
4522                ConstantInt::get(RHS->getValue() | C1->getValue()));
4523     }
4524
4525     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4526     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4527       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4528       InsertNewInstBefore(Or, I);
4529       Or->takeName(Op0);
4530       return BinaryOperator::CreateXor(Or,
4531                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4532     }
4533
4534     // Try to fold constant and into select arguments.
4535     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4536       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4537         return R;
4538     if (isa<PHINode>(Op0))
4539       if (Instruction *NV = FoldOpIntoPhi(I))
4540         return NV;
4541   }
4542
4543   Value *A = 0, *B = 0;
4544   ConstantInt *C1 = 0, *C2 = 0;
4545
4546   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4547     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4548       return ReplaceInstUsesWith(I, Op1);
4549   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4550     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4551       return ReplaceInstUsesWith(I, Op0);
4552
4553   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4554   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4555   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4556       match(Op1, m_Or(m_Value(), m_Value())) ||
4557       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4558        match(Op1, m_Shift(m_Value(), m_Value())))) {
4559     if (Instruction *BSwap = MatchBSwap(I))
4560       return BSwap;
4561   }
4562   
4563   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4564   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4565       MaskedValueIsZero(Op1, C1->getValue())) {
4566     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4567     InsertNewInstBefore(NOr, I);
4568     NOr->takeName(Op0);
4569     return BinaryOperator::CreateXor(NOr, C1);
4570   }
4571
4572   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4573   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4574       MaskedValueIsZero(Op0, C1->getValue())) {
4575     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4576     InsertNewInstBefore(NOr, I);
4577     NOr->takeName(Op0);
4578     return BinaryOperator::CreateXor(NOr, C1);
4579   }
4580
4581   // (A & C)|(B & D)
4582   Value *C = 0, *D = 0;
4583   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4584       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4585     Value *V1 = 0, *V2 = 0, *V3 = 0;
4586     C1 = dyn_cast<ConstantInt>(C);
4587     C2 = dyn_cast<ConstantInt>(D);
4588     if (C1 && C2) {  // (A & C1)|(B & C2)
4589       // If we have: ((V + N) & C1) | (V & C2)
4590       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4591       // replace with V+N.
4592       if (C1->getValue() == ~C2->getValue()) {
4593         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4594             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4595           // Add commutes, try both ways.
4596           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4597             return ReplaceInstUsesWith(I, A);
4598           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4599             return ReplaceInstUsesWith(I, A);
4600         }
4601         // Or commutes, try both ways.
4602         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4603             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4604           // Add commutes, try both ways.
4605           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4606             return ReplaceInstUsesWith(I, B);
4607           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4608             return ReplaceInstUsesWith(I, B);
4609         }
4610       }
4611       V1 = 0; V2 = 0; V3 = 0;
4612     }
4613     
4614     // Check to see if we have any common things being and'ed.  If so, find the
4615     // terms for V1 & (V2|V3).
4616     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4617       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4618         V1 = A, V2 = C, V3 = D;
4619       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4620         V1 = A, V2 = B, V3 = C;
4621       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4622         V1 = C, V2 = A, V3 = D;
4623       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4624         V1 = C, V2 = A, V3 = B;
4625       
4626       if (V1) {
4627         Value *Or =
4628           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4629         return BinaryOperator::CreateAnd(V1, Or);
4630       }
4631     }
4632
4633     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4634     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4635       return Match;
4636     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4637       return Match;
4638     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4639       return Match;
4640     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4641       return Match;
4642
4643     // ((A&~B)|(~A&B)) -> A^B
4644     if ((match(C, m_Not(m_Specific(D))) &&
4645          match(B, m_Not(m_Specific(A)))))
4646       return BinaryOperator::CreateXor(A, D);
4647     // ((~B&A)|(~A&B)) -> A^B
4648     if ((match(A, m_Not(m_Specific(D))) &&
4649          match(B, m_Not(m_Specific(C)))))
4650       return BinaryOperator::CreateXor(C, D);
4651     // ((A&~B)|(B&~A)) -> A^B
4652     if ((match(C, m_Not(m_Specific(B))) &&
4653          match(D, m_Not(m_Specific(A)))))
4654       return BinaryOperator::CreateXor(A, B);
4655     // ((~B&A)|(B&~A)) -> A^B
4656     if ((match(A, m_Not(m_Specific(B))) &&
4657          match(D, m_Not(m_Specific(C)))))
4658       return BinaryOperator::CreateXor(C, B);
4659   }
4660   
4661   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4662   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4663     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4664       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4665           SI0->getOperand(1) == SI1->getOperand(1) &&
4666           (SI0->hasOneUse() || SI1->hasOneUse())) {
4667         Instruction *NewOp =
4668         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4669                                                      SI1->getOperand(0),
4670                                                      SI0->getName()), I);
4671         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4672                                       SI1->getOperand(1));
4673       }
4674   }
4675
4676   // ((A|B)&1)|(B&-2) -> (A&1) | B
4677   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4678       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4679     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4680     if (Ret) return Ret;
4681   }
4682   // (B&-2)|((A|B)&1) -> (A&1) | B
4683   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4684       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4685     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4686     if (Ret) return Ret;
4687   }
4688
4689   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4690     if (A == Op1)   // ~A | A == -1
4691       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4692   } else {
4693     A = 0;
4694   }
4695   // Note, A is still live here!
4696   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4697     if (Op0 == B)
4698       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4699
4700     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4701     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4702       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4703                                               I.getName()+".demorgan"), I);
4704       return BinaryOperator::CreateNot(And);
4705     }
4706   }
4707
4708   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4709   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4710     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4711       return R;
4712
4713     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4714       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4715         return Res;
4716   }
4717     
4718   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4719   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4720     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4721       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4722         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4723             !isa<ICmpInst>(Op1C->getOperand(0))) {
4724           const Type *SrcTy = Op0C->getOperand(0)->getType();
4725           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4726               // Only do this if the casts both really cause code to be
4727               // generated.
4728               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4729                                 I.getType(), TD) &&
4730               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4731                                 I.getType(), TD)) {
4732             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4733                                                           Op1C->getOperand(0),
4734                                                           I.getName());
4735             InsertNewInstBefore(NewOp, I);
4736             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4737           }
4738         }
4739       }
4740   }
4741   
4742     
4743   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4744   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4745     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4746       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4747           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4748           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4749         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4750           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4751             // If either of the constants are nans, then the whole thing returns
4752             // true.
4753             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4754               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4755             
4756             // Otherwise, no need to compare the two constants, compare the
4757             // rest.
4758             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4759                                 RHS->getOperand(0));
4760           }
4761       } else {
4762         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4763         FCmpInst::Predicate Op0CC, Op1CC;
4764         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4765             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4766           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4767             // Swap RHS operands to match LHS.
4768             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4769             std::swap(Op1LHS, Op1RHS);
4770           }
4771           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4772             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4773             if (Op0CC == Op1CC)
4774               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4775             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4776                      Op1CC == FCmpInst::FCMP_TRUE)
4777               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4778             else if (Op0CC == FCmpInst::FCMP_FALSE)
4779               return ReplaceInstUsesWith(I, Op1);
4780             else if (Op1CC == FCmpInst::FCMP_FALSE)
4781               return ReplaceInstUsesWith(I, Op0);
4782             bool Op0Ordered;
4783             bool Op1Ordered;
4784             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4785             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4786             if (Op0Ordered == Op1Ordered) {
4787               // If both are ordered or unordered, return a new fcmp with
4788               // or'ed predicates.
4789               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4790                                        Op0LHS, Op0RHS);
4791               if (Instruction *I = dyn_cast<Instruction>(RV))
4792                 return I;
4793               // Otherwise, it's a constant boolean value...
4794               return ReplaceInstUsesWith(I, RV);
4795             }
4796           }
4797         }
4798       }
4799     }
4800   }
4801
4802   return Changed ? &I : 0;
4803 }
4804
4805 namespace {
4806
4807 // XorSelf - Implements: X ^ X --> 0
4808 struct XorSelf {
4809   Value *RHS;
4810   XorSelf(Value *rhs) : RHS(rhs) {}
4811   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4812   Instruction *apply(BinaryOperator &Xor) const {
4813     return &Xor;
4814   }
4815 };
4816
4817 }
4818
4819 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4820   bool Changed = SimplifyCommutative(I);
4821   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4822
4823   if (isa<UndefValue>(Op1)) {
4824     if (isa<UndefValue>(Op0))
4825       // Handle undef ^ undef -> 0 special case. This is a common
4826       // idiom (misuse).
4827       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4828     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4829   }
4830
4831   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4832   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4833     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4834     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4835   }
4836   
4837   // See if we can simplify any instructions used by the instruction whose sole 
4838   // purpose is to compute bits we don't care about.
4839   if (!isa<VectorType>(I.getType())) {
4840     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4841     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4842     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4843                              KnownZero, KnownOne))
4844       return &I;
4845   } else if (isa<ConstantAggregateZero>(Op1)) {
4846     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4847   }
4848
4849   // Is this a ~ operation?
4850   if (Value *NotOp = dyn_castNotVal(&I)) {
4851     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4852     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4853     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4854       if (Op0I->getOpcode() == Instruction::And || 
4855           Op0I->getOpcode() == Instruction::Or) {
4856         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4857         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4858           Instruction *NotY =
4859             BinaryOperator::CreateNot(Op0I->getOperand(1),
4860                                       Op0I->getOperand(1)->getName()+".not");
4861           InsertNewInstBefore(NotY, I);
4862           if (Op0I->getOpcode() == Instruction::And)
4863             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4864           else
4865             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4866         }
4867       }
4868     }
4869   }
4870   
4871   
4872   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4873     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4874       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4875       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4876         return new ICmpInst(ICI->getInversePredicate(),
4877                             ICI->getOperand(0), ICI->getOperand(1));
4878
4879       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4880         return new FCmpInst(FCI->getInversePredicate(),
4881                             FCI->getOperand(0), FCI->getOperand(1));
4882     }
4883
4884     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4885     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4886       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4887         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4888           Instruction::CastOps Opcode = Op0C->getOpcode();
4889           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4890             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4891                                              Op0C->getDestTy())) {
4892               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4893                                      CI->getOpcode(), CI->getInversePredicate(),
4894                                      CI->getOperand(0), CI->getOperand(1)), I);
4895               NewCI->takeName(CI);
4896               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4897             }
4898           }
4899         }
4900       }
4901     }
4902
4903     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4904       // ~(c-X) == X-c-1 == X+(-c-1)
4905       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4906         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4907           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4908           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4909                                               ConstantInt::get(I.getType(), 1));
4910           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4911         }
4912           
4913       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4914         if (Op0I->getOpcode() == Instruction::Add) {
4915           // ~(X-c) --> (-c-1)-X
4916           if (RHS->isAllOnesValue()) {
4917             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4918             return BinaryOperator::CreateSub(
4919                            ConstantExpr::getSub(NegOp0CI,
4920                                              ConstantInt::get(I.getType(), 1)),
4921                                           Op0I->getOperand(0));
4922           } else if (RHS->getValue().isSignBit()) {
4923             // (X + C) ^ signbit -> (X + C + signbit)
4924             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4925             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4926
4927           }
4928         } else if (Op0I->getOpcode() == Instruction::Or) {
4929           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4930           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4931             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4932             // Anything in both C1 and C2 is known to be zero, remove it from
4933             // NewRHS.
4934             Constant *CommonBits = And(Op0CI, RHS);
4935             NewRHS = ConstantExpr::getAnd(NewRHS, 
4936                                           ConstantExpr::getNot(CommonBits));
4937             AddToWorkList(Op0I);
4938             I.setOperand(0, Op0I->getOperand(0));
4939             I.setOperand(1, NewRHS);
4940             return &I;
4941           }
4942         }
4943       }
4944     }
4945
4946     // Try to fold constant and into select arguments.
4947     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4948       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4949         return R;
4950     if (isa<PHINode>(Op0))
4951       if (Instruction *NV = FoldOpIntoPhi(I))
4952         return NV;
4953   }
4954
4955   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4956     if (X == Op1)
4957       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4958
4959   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4960     if (X == Op0)
4961       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4962
4963   
4964   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4965   if (Op1I) {
4966     Value *A, *B;
4967     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4968       if (A == Op0) {              // B^(B|A) == (A|B)^B
4969         Op1I->swapOperands();
4970         I.swapOperands();
4971         std::swap(Op0, Op1);
4972       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4973         I.swapOperands();     // Simplified below.
4974         std::swap(Op0, Op1);
4975       }
4976     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
4977       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
4978     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
4979       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
4980     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4981       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4982         Op1I->swapOperands();
4983         std::swap(A, B);
4984       }
4985       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4986         I.swapOperands();     // Simplified below.
4987         std::swap(Op0, Op1);
4988       }
4989     }
4990   }
4991   
4992   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4993   if (Op0I) {
4994     Value *A, *B;
4995     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4996       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4997         std::swap(A, B);
4998       if (B == Op1) {                                // (A|B)^B == A & ~B
4999         Instruction *NotB =
5000           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5001         return BinaryOperator::CreateAnd(A, NotB);
5002       }
5003     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5004       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5005     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5006       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5007     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5008       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5009         std::swap(A, B);
5010       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5011           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5012         Instruction *N =
5013           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5014         return BinaryOperator::CreateAnd(N, Op1);
5015       }
5016     }
5017   }
5018   
5019   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5020   if (Op0I && Op1I && Op0I->isShift() && 
5021       Op0I->getOpcode() == Op1I->getOpcode() && 
5022       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5023       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5024     Instruction *NewOp =
5025       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5026                                                     Op1I->getOperand(0),
5027                                                     Op0I->getName()), I);
5028     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5029                                   Op1I->getOperand(1));
5030   }
5031     
5032   if (Op0I && Op1I) {
5033     Value *A, *B, *C, *D;
5034     // (A & B)^(A | B) -> A ^ B
5035     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5036         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5037       if ((A == C && B == D) || (A == D && B == C)) 
5038         return BinaryOperator::CreateXor(A, B);
5039     }
5040     // (A | B)^(A & B) -> A ^ B
5041     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5042         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5043       if ((A == C && B == D) || (A == D && B == C)) 
5044         return BinaryOperator::CreateXor(A, B);
5045     }
5046     
5047     // (A & B)^(C & D)
5048     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5049         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5050         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5051       // (X & Y)^(X & Y) -> (Y^Z) & X
5052       Value *X = 0, *Y = 0, *Z = 0;
5053       if (A == C)
5054         X = A, Y = B, Z = D;
5055       else if (A == D)
5056         X = A, Y = B, Z = C;
5057       else if (B == C)
5058         X = B, Y = A, Z = D;
5059       else if (B == D)
5060         X = B, Y = A, Z = C;
5061       
5062       if (X) {
5063         Instruction *NewOp =
5064         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5065         return BinaryOperator::CreateAnd(NewOp, X);
5066       }
5067     }
5068   }
5069     
5070   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5071   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5072     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5073       return R;
5074
5075   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5076   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5077     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5078       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5079         const Type *SrcTy = Op0C->getOperand(0)->getType();
5080         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5081             // Only do this if the casts both really cause code to be generated.
5082             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5083                               I.getType(), TD) &&
5084             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5085                               I.getType(), TD)) {
5086           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5087                                                          Op1C->getOperand(0),
5088                                                          I.getName());
5089           InsertNewInstBefore(NewOp, I);
5090           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5091         }
5092       }
5093   }
5094
5095   return Changed ? &I : 0;
5096 }
5097
5098 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5099 /// overflowed for this type.
5100 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5101                             ConstantInt *In2, bool IsSigned = false) {
5102   Result = cast<ConstantInt>(Add(In1, In2));
5103
5104   if (IsSigned)
5105     if (In2->getValue().isNegative())
5106       return Result->getValue().sgt(In1->getValue());
5107     else
5108       return Result->getValue().slt(In1->getValue());
5109   else
5110     return Result->getValue().ult(In1->getValue());
5111 }
5112
5113 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5114 /// overflowed for this type.
5115 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5116                             ConstantInt *In2, bool IsSigned = false) {
5117   Result = cast<ConstantInt>(Subtract(In1, In2));
5118
5119   if (IsSigned)
5120     if (In2->getValue().isNegative())
5121       return Result->getValue().slt(In1->getValue());
5122     else
5123       return Result->getValue().sgt(In1->getValue());
5124   else
5125     return Result->getValue().ugt(In1->getValue());
5126 }
5127
5128 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5129 /// code necessary to compute the offset from the base pointer (without adding
5130 /// in the base pointer).  Return the result as a signed integer of intptr size.
5131 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5132   TargetData &TD = IC.getTargetData();
5133   gep_type_iterator GTI = gep_type_begin(GEP);
5134   const Type *IntPtrTy = TD.getIntPtrType();
5135   Value *Result = Constant::getNullValue(IntPtrTy);
5136
5137   // Build a mask for high order bits.
5138   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5139   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5140
5141   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5142        ++i, ++GTI) {
5143     Value *Op = *i;
5144     uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
5145     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5146       if (OpC->isZero()) continue;
5147       
5148       // Handle a struct index, which adds its field offset to the pointer.
5149       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5150         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5151         
5152         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5153           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5154         else
5155           Result = IC.InsertNewInstBefore(
5156                    BinaryOperator::CreateAdd(Result,
5157                                              ConstantInt::get(IntPtrTy, Size),
5158                                              GEP->getName()+".offs"), I);
5159         continue;
5160       }
5161       
5162       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5163       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5164       Scale = ConstantExpr::getMul(OC, Scale);
5165       if (Constant *RC = dyn_cast<Constant>(Result))
5166         Result = ConstantExpr::getAdd(RC, Scale);
5167       else {
5168         // Emit an add instruction.
5169         Result = IC.InsertNewInstBefore(
5170            BinaryOperator::CreateAdd(Result, Scale,
5171                                      GEP->getName()+".offs"), I);
5172       }
5173       continue;
5174     }
5175     // Convert to correct type.
5176     if (Op->getType() != IntPtrTy) {
5177       if (Constant *OpC = dyn_cast<Constant>(Op))
5178         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5179       else
5180         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5181                                                  Op->getName()+".c"), I);
5182     }
5183     if (Size != 1) {
5184       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5185       if (Constant *OpC = dyn_cast<Constant>(Op))
5186         Op = ConstantExpr::getMul(OpC, Scale);
5187       else    // We'll let instcombine(mul) convert this to a shl if possible.
5188         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5189                                                   GEP->getName()+".idx"), I);
5190     }
5191
5192     // Emit an add instruction.
5193     if (isa<Constant>(Op) && isa<Constant>(Result))
5194       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5195                                     cast<Constant>(Result));
5196     else
5197       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5198                                                   GEP->getName()+".offs"), I);
5199   }
5200   return Result;
5201 }
5202
5203
5204 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5205 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5206 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5207 /// complex, and scales are involved.  The above expression would also be legal
5208 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5209 /// later form is less amenable to optimization though, and we are allowed to
5210 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5211 ///
5212 /// If we can't emit an optimized form for this expression, this returns null.
5213 /// 
5214 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5215                                           InstCombiner &IC) {
5216   TargetData &TD = IC.getTargetData();
5217   gep_type_iterator GTI = gep_type_begin(GEP);
5218
5219   // Check to see if this gep only has a single variable index.  If so, and if
5220   // any constant indices are a multiple of its scale, then we can compute this
5221   // in terms of the scale of the variable index.  For example, if the GEP
5222   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5223   // because the expression will cross zero at the same point.
5224   unsigned i, e = GEP->getNumOperands();
5225   int64_t Offset = 0;
5226   for (i = 1; i != e; ++i, ++GTI) {
5227     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5228       // Compute the aggregate offset of constant indices.
5229       if (CI->isZero()) continue;
5230
5231       // Handle a struct index, which adds its field offset to the pointer.
5232       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5233         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5234       } else {
5235         uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
5236         Offset += Size*CI->getSExtValue();
5237       }
5238     } else {
5239       // Found our variable index.
5240       break;
5241     }
5242   }
5243   
5244   // If there are no variable indices, we must have a constant offset, just
5245   // evaluate it the general way.
5246   if (i == e) return 0;
5247   
5248   Value *VariableIdx = GEP->getOperand(i);
5249   // Determine the scale factor of the variable element.  For example, this is
5250   // 4 if the variable index is into an array of i32.
5251   uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
5252   
5253   // Verify that there are no other variable indices.  If so, emit the hard way.
5254   for (++i, ++GTI; i != e; ++i, ++GTI) {
5255     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5256     if (!CI) return 0;
5257    
5258     // Compute the aggregate offset of constant indices.
5259     if (CI->isZero()) continue;
5260     
5261     // Handle a struct index, which adds its field offset to the pointer.
5262     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5263       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5264     } else {
5265       uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
5266       Offset += Size*CI->getSExtValue();
5267     }
5268   }
5269   
5270   // Okay, we know we have a single variable index, which must be a
5271   // pointer/array/vector index.  If there is no offset, life is simple, return
5272   // the index.
5273   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5274   if (Offset == 0) {
5275     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5276     // we don't need to bother extending: the extension won't affect where the
5277     // computation crosses zero.
5278     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5279       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5280                                   VariableIdx->getNameStart(), &I);
5281     return VariableIdx;
5282   }
5283   
5284   // Otherwise, there is an index.  The computation we will do will be modulo
5285   // the pointer size, so get it.
5286   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5287   
5288   Offset &= PtrSizeMask;
5289   VariableScale &= PtrSizeMask;
5290
5291   // To do this transformation, any constant index must be a multiple of the
5292   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5293   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5294   // multiple of the variable scale.
5295   int64_t NewOffs = Offset / (int64_t)VariableScale;
5296   if (Offset != NewOffs*(int64_t)VariableScale)
5297     return 0;
5298
5299   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5300   const Type *IntPtrTy = TD.getIntPtrType();
5301   if (VariableIdx->getType() != IntPtrTy)
5302     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5303                                               true /*SExt*/, 
5304                                               VariableIdx->getNameStart(), &I);
5305   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5306   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5307 }
5308
5309
5310 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5311 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5312 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5313                                        ICmpInst::Predicate Cond,
5314                                        Instruction &I) {
5315   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5316
5317   // Look through bitcasts.
5318   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5319     RHS = BCI->getOperand(0);
5320
5321   Value *PtrBase = GEPLHS->getOperand(0);
5322   if (PtrBase == RHS) {
5323     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5324     // This transformation (ignoring the base and scales) is valid because we
5325     // know pointers can't overflow.  See if we can output an optimized form.
5326     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5327     
5328     // If not, synthesize the offset the hard way.
5329     if (Offset == 0)
5330       Offset = EmitGEPOffset(GEPLHS, I, *this);
5331     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5332                         Constant::getNullValue(Offset->getType()));
5333   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5334     // If the base pointers are different, but the indices are the same, just
5335     // compare the base pointer.
5336     if (PtrBase != GEPRHS->getOperand(0)) {
5337       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5338       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5339                         GEPRHS->getOperand(0)->getType();
5340       if (IndicesTheSame)
5341         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5342           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5343             IndicesTheSame = false;
5344             break;
5345           }
5346
5347       // If all indices are the same, just compare the base pointers.
5348       if (IndicesTheSame)
5349         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5350                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5351
5352       // Otherwise, the base pointers are different and the indices are
5353       // different, bail out.
5354       return 0;
5355     }
5356
5357     // If one of the GEPs has all zero indices, recurse.
5358     bool AllZeros = true;
5359     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5360       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5361           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5362         AllZeros = false;
5363         break;
5364       }
5365     if (AllZeros)
5366       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5367                           ICmpInst::getSwappedPredicate(Cond), I);
5368
5369     // If the other GEP has all zero indices, recurse.
5370     AllZeros = true;
5371     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5372       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5373           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5374         AllZeros = false;
5375         break;
5376       }
5377     if (AllZeros)
5378       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5379
5380     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5381       // If the GEPs only differ by one index, compare it.
5382       unsigned NumDifferences = 0;  // Keep track of # differences.
5383       unsigned DiffOperand = 0;     // The operand that differs.
5384       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5385         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5386           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5387                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5388             // Irreconcilable differences.
5389             NumDifferences = 2;
5390             break;
5391           } else {
5392             if (NumDifferences++) break;
5393             DiffOperand = i;
5394           }
5395         }
5396
5397       if (NumDifferences == 0)   // SAME GEP?
5398         return ReplaceInstUsesWith(I, // No comparison is needed here.
5399                                    ConstantInt::get(Type::Int1Ty,
5400                                              ICmpInst::isTrueWhenEqual(Cond)));
5401
5402       else if (NumDifferences == 1) {
5403         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5404         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5405         // Make sure we do a signed comparison here.
5406         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5407       }
5408     }
5409
5410     // Only lower this if the icmp is the only user of the GEP or if we expect
5411     // the result to fold to a constant!
5412     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5413         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5414       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5415       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5416       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5417       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5418     }
5419   }
5420   return 0;
5421 }
5422
5423 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5424 ///
5425 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5426                                                 Instruction *LHSI,
5427                                                 Constant *RHSC) {
5428   if (!isa<ConstantFP>(RHSC)) return 0;
5429   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5430   
5431   // Get the width of the mantissa.  We don't want to hack on conversions that
5432   // might lose information from the integer, e.g. "i64 -> float"
5433   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5434   if (MantissaWidth == -1) return 0;  // Unknown.
5435   
5436   // Check to see that the input is converted from an integer type that is small
5437   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5438   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5439   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5440   
5441   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5442   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5443   if (LHSUnsigned)
5444     ++InputSize;
5445   
5446   // If the conversion would lose info, don't hack on this.
5447   if ((int)InputSize > MantissaWidth)
5448     return 0;
5449   
5450   // Otherwise, we can potentially simplify the comparison.  We know that it
5451   // will always come through as an integer value and we know the constant is
5452   // not a NAN (it would have been previously simplified).
5453   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5454   
5455   ICmpInst::Predicate Pred;
5456   switch (I.getPredicate()) {
5457   default: assert(0 && "Unexpected predicate!");
5458   case FCmpInst::FCMP_UEQ:
5459   case FCmpInst::FCMP_OEQ:
5460     Pred = ICmpInst::ICMP_EQ;
5461     break;
5462   case FCmpInst::FCMP_UGT:
5463   case FCmpInst::FCMP_OGT:
5464     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5465     break;
5466   case FCmpInst::FCMP_UGE:
5467   case FCmpInst::FCMP_OGE:
5468     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5469     break;
5470   case FCmpInst::FCMP_ULT:
5471   case FCmpInst::FCMP_OLT:
5472     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5473     break;
5474   case FCmpInst::FCMP_ULE:
5475   case FCmpInst::FCMP_OLE:
5476     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5477     break;
5478   case FCmpInst::FCMP_UNE:
5479   case FCmpInst::FCMP_ONE:
5480     Pred = ICmpInst::ICMP_NE;
5481     break;
5482   case FCmpInst::FCMP_ORD:
5483     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5484   case FCmpInst::FCMP_UNO:
5485     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5486   }
5487   
5488   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5489   
5490   // Now we know that the APFloat is a normal number, zero or inf.
5491   
5492   // See if the FP constant is too large for the integer.  For example,
5493   // comparing an i8 to 300.0.
5494   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5495   
5496   if (!LHSUnsigned) {
5497     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5498     // and large values.
5499     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5500     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5501                           APFloat::rmNearestTiesToEven);
5502     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5503       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5504           Pred == ICmpInst::ICMP_SLE)
5505         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5506       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5507     }
5508   } else {
5509     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5510     // +INF and large values.
5511     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5512     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5513                           APFloat::rmNearestTiesToEven);
5514     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5515       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5516           Pred == ICmpInst::ICMP_ULE)
5517         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5518       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5519     }
5520   }
5521   
5522   if (!LHSUnsigned) {
5523     // See if the RHS value is < SignedMin.
5524     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5525     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5526                           APFloat::rmNearestTiesToEven);
5527     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5528       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5529           Pred == ICmpInst::ICMP_SGE)
5530         return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5531       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5532     }
5533   }
5534
5535   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5536   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5537   // casting the FP value to the integer value and back, checking for equality.
5538   // Don't do this for zero, because -0.0 is not fractional.
5539   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5540   if (!RHS.isZero() &&
5541       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5542     // If we had a comparison against a fractional value, we have to adjust the
5543     // compare predicate and sometimes the value.  RHSC is rounded towards zero
5544     // at this point.
5545     switch (Pred) {
5546     default: assert(0 && "Unexpected integer comparison!");
5547     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5548       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5549     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5550       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5551     case ICmpInst::ICMP_ULE:
5552       // (float)int <= 4.4   --> int <= 4
5553       // (float)int <= -4.4  --> false
5554       if (RHS.isNegative())
5555         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5556       break;
5557     case ICmpInst::ICMP_SLE:
5558       // (float)int <= 4.4   --> int <= 4
5559       // (float)int <= -4.4  --> int < -4
5560       if (RHS.isNegative())
5561         Pred = ICmpInst::ICMP_SLT;
5562       break;
5563     case ICmpInst::ICMP_ULT:
5564       // (float)int < -4.4   --> false
5565       // (float)int < 4.4    --> int <= 4
5566       if (RHS.isNegative())
5567         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5568       Pred = ICmpInst::ICMP_ULE;
5569       break;
5570     case ICmpInst::ICMP_SLT:
5571       // (float)int < -4.4   --> int < -4
5572       // (float)int < 4.4    --> int <= 4
5573       if (!RHS.isNegative())
5574         Pred = ICmpInst::ICMP_SLE;
5575       break;
5576     case ICmpInst::ICMP_UGT:
5577       // (float)int > 4.4    --> int > 4
5578       // (float)int > -4.4   --> true
5579       if (RHS.isNegative())
5580         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5581       break;
5582     case ICmpInst::ICMP_SGT:
5583       // (float)int > 4.4    --> int > 4
5584       // (float)int > -4.4   --> int >= -4
5585       if (RHS.isNegative())
5586         Pred = ICmpInst::ICMP_SGE;
5587       break;
5588     case ICmpInst::ICMP_UGE:
5589       // (float)int >= -4.4   --> true
5590       // (float)int >= 4.4    --> int > 4
5591       if (!RHS.isNegative())
5592         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5593       Pred = ICmpInst::ICMP_UGT;
5594       break;
5595     case ICmpInst::ICMP_SGE:
5596       // (float)int >= -4.4   --> int >= -4
5597       // (float)int >= 4.4    --> int > 4
5598       if (!RHS.isNegative())
5599         Pred = ICmpInst::ICMP_SGT;
5600       break;
5601     }
5602   }
5603
5604   // Lower this FP comparison into an appropriate integer version of the
5605   // comparison.
5606   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5607 }
5608
5609 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5610   bool Changed = SimplifyCompare(I);
5611   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5612
5613   // Fold trivial predicates.
5614   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5615     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5616   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5617     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5618   
5619   // Simplify 'fcmp pred X, X'
5620   if (Op0 == Op1) {
5621     switch (I.getPredicate()) {
5622     default: assert(0 && "Unknown predicate!");
5623     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5624     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5625     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5626       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5627     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5628     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5629     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5630       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5631       
5632     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5633     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5634     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5635     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5636       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5637       I.setPredicate(FCmpInst::FCMP_UNO);
5638       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5639       return &I;
5640       
5641     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5642     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5643     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5644     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5645       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5646       I.setPredicate(FCmpInst::FCMP_ORD);
5647       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5648       return &I;
5649     }
5650   }
5651     
5652   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5653     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5654
5655   // Handle fcmp with constant RHS
5656   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5657     // If the constant is a nan, see if we can fold the comparison based on it.
5658     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5659       if (CFP->getValueAPF().isNaN()) {
5660         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5661           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5662         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5663                "Comparison must be either ordered or unordered!");
5664         // True if unordered.
5665         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5666       }
5667     }
5668     
5669     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5670       switch (LHSI->getOpcode()) {
5671       case Instruction::PHI:
5672         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5673         // block.  If in the same block, we're encouraging jump threading.  If
5674         // not, we are just pessimizing the code by making an i1 phi.
5675         if (LHSI->getParent() == I.getParent())
5676           if (Instruction *NV = FoldOpIntoPhi(I))
5677             return NV;
5678         break;
5679       case Instruction::SIToFP:
5680       case Instruction::UIToFP:
5681         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5682           return NV;
5683         break;
5684       case Instruction::Select:
5685         // If either operand of the select is a constant, we can fold the
5686         // comparison into the select arms, which will cause one to be
5687         // constant folded and the select turned into a bitwise or.
5688         Value *Op1 = 0, *Op2 = 0;
5689         if (LHSI->hasOneUse()) {
5690           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5691             // Fold the known value into the constant operand.
5692             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5693             // Insert a new FCmp of the other select operand.
5694             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5695                                                       LHSI->getOperand(2), RHSC,
5696                                                       I.getName()), I);
5697           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5698             // Fold the known value into the constant operand.
5699             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5700             // Insert a new FCmp of the other select operand.
5701             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5702                                                       LHSI->getOperand(1), RHSC,
5703                                                       I.getName()), I);
5704           }
5705         }
5706
5707         if (Op1)
5708           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5709         break;
5710       }
5711   }
5712
5713   return Changed ? &I : 0;
5714 }
5715
5716 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5717   bool Changed = SimplifyCompare(I);
5718   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5719   const Type *Ty = Op0->getType();
5720
5721   // icmp X, X
5722   if (Op0 == Op1)
5723     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5724                                                    I.isTrueWhenEqual()));
5725
5726   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5727     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5728   
5729   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5730   // addresses never equal each other!  We already know that Op0 != Op1.
5731   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5732        isa<ConstantPointerNull>(Op0)) &&
5733       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5734        isa<ConstantPointerNull>(Op1)))
5735     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5736                                                    !I.isTrueWhenEqual()));
5737
5738   // icmp's with boolean values can always be turned into bitwise operations
5739   if (Ty == Type::Int1Ty) {
5740     switch (I.getPredicate()) {
5741     default: assert(0 && "Invalid icmp instruction!");
5742     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5743       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5744       InsertNewInstBefore(Xor, I);
5745       return BinaryOperator::CreateNot(Xor);
5746     }
5747     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5748       return BinaryOperator::CreateXor(Op0, Op1);
5749
5750     case ICmpInst::ICMP_UGT:
5751       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5752       // FALL THROUGH
5753     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5754       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5755       InsertNewInstBefore(Not, I);
5756       return BinaryOperator::CreateAnd(Not, Op1);
5757     }
5758     case ICmpInst::ICMP_SGT:
5759       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5760       // FALL THROUGH
5761     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5762       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5763       InsertNewInstBefore(Not, I);
5764       return BinaryOperator::CreateAnd(Not, Op0);
5765     }
5766     case ICmpInst::ICMP_UGE:
5767       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5768       // FALL THROUGH
5769     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5770       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5771       InsertNewInstBefore(Not, I);
5772       return BinaryOperator::CreateOr(Not, Op1);
5773     }
5774     case ICmpInst::ICMP_SGE:
5775       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5776       // FALL THROUGH
5777     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5778       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5779       InsertNewInstBefore(Not, I);
5780       return BinaryOperator::CreateOr(Not, Op0);
5781     }
5782     }
5783   }
5784
5785   // See if we are doing a comparison with a constant.
5786   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5787     Value *A, *B;
5788     
5789     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5790     if (I.isEquality() && CI->isNullValue() &&
5791         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5792       // (icmp cond A B) if cond is equality
5793       return new ICmpInst(I.getPredicate(), A, B);
5794     }
5795     
5796     // If we have an icmp le or icmp ge instruction, turn it into the
5797     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5798     // them being folded in the code below.
5799     switch (I.getPredicate()) {
5800     default: break;
5801     case ICmpInst::ICMP_ULE:
5802       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5803         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5804       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5805     case ICmpInst::ICMP_SLE:
5806       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5807         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5808       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5809     case ICmpInst::ICMP_UGE:
5810       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5811         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5812       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5813     case ICmpInst::ICMP_SGE:
5814       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5815         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5816       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5817     }
5818     
5819     // See if we can fold the comparison based on range information we can get
5820     // by checking whether bits are known to be zero or one in the input.
5821     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5822     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5823     
5824     // If this comparison is a normal comparison, it demands all
5825     // bits, if it is a sign bit comparison, it only demands the sign bit.
5826     bool UnusedBit;
5827     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5828     
5829     if (SimplifyDemandedBits(Op0, 
5830                              isSignBit ? APInt::getSignBit(BitWidth)
5831                                        : APInt::getAllOnesValue(BitWidth),
5832                              KnownZero, KnownOne, 0))
5833       return &I;
5834         
5835     // Given the known and unknown bits, compute a range that the LHS could be
5836     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5837     // EQ and NE we use unsigned values.
5838     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5839     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5840       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5841     else
5842       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5843     
5844     // If Min and Max are known to be the same, then SimplifyDemandedBits
5845     // figured out that the LHS is a constant.  Just constant fold this now so
5846     // that code below can assume that Min != Max.
5847     if (Min == Max)
5848       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5849                                                           ConstantInt::get(Min),
5850                                                           CI));
5851     
5852     // Based on the range information we know about the LHS, see if we can
5853     // simplify this comparison.  For example, (x&4) < 8  is always true.
5854     const APInt &RHSVal = CI->getValue();
5855     switch (I.getPredicate()) {  // LE/GE have been folded already.
5856     default: assert(0 && "Unknown icmp opcode!");
5857     case ICmpInst::ICMP_EQ:
5858       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5859         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5860       break;
5861     case ICmpInst::ICMP_NE:
5862       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5863         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5864       break;
5865     case ICmpInst::ICMP_ULT:
5866       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5867         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5868       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5869         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5870       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5871         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5872       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5873         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5874         
5875       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5876       if (CI->isMinValue(true))
5877         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5878                             ConstantInt::getAllOnesValue(Op0->getType()));
5879       break;
5880     case ICmpInst::ICMP_UGT:
5881       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5882         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5883       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5884         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5885         
5886       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5887         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5888       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5889         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5890       
5891       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5892       if (CI->isMaxValue(true))
5893         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5894                             ConstantInt::getNullValue(Op0->getType()));
5895       break;
5896     case ICmpInst::ICMP_SLT:
5897       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5898         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5899       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5900         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5901       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5902         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5903       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5904         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5905       break;
5906     case ICmpInst::ICMP_SGT: 
5907       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5908         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5909       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5910         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5911         
5912       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5913         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5914       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5915         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5916       break;
5917     }
5918   }
5919
5920   // Test if the ICmpInst instruction is used exclusively by a select as
5921   // part of a minimum or maximum operation. If so, refrain from doing
5922   // any other folding. This helps out other analyses which understand
5923   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5924   // and CodeGen. And in this case, at least one of the comparison
5925   // operands has at least one user besides the compare (the select),
5926   // which would often largely negate the benefit of folding anyway.
5927   if (I.hasOneUse())
5928     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5929       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5930           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5931         return 0;
5932
5933   // See if we are doing a comparison between a constant and an instruction that
5934   // can be folded into the comparison.
5935   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5936     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5937     // instruction, see if that instruction also has constants so that the 
5938     // instruction can be folded into the icmp 
5939     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5940       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5941         return Res;
5942   }
5943
5944   // Handle icmp with constant (but not simple integer constant) RHS
5945   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5946     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5947       switch (LHSI->getOpcode()) {
5948       case Instruction::GetElementPtr:
5949         if (RHSC->isNullValue()) {
5950           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5951           bool isAllZeros = true;
5952           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5953             if (!isa<Constant>(LHSI->getOperand(i)) ||
5954                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5955               isAllZeros = false;
5956               break;
5957             }
5958           if (isAllZeros)
5959             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5960                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5961         }
5962         break;
5963
5964       case Instruction::PHI:
5965         // Only fold icmp into the PHI if the phi and fcmp are in the same
5966         // block.  If in the same block, we're encouraging jump threading.  If
5967         // not, we are just pessimizing the code by making an i1 phi.
5968         if (LHSI->getParent() == I.getParent())
5969           if (Instruction *NV = FoldOpIntoPhi(I))
5970             return NV;
5971         break;
5972       case Instruction::Select: {
5973         // If either operand of the select is a constant, we can fold the
5974         // comparison into the select arms, which will cause one to be
5975         // constant folded and the select turned into a bitwise or.
5976         Value *Op1 = 0, *Op2 = 0;
5977         if (LHSI->hasOneUse()) {
5978           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5979             // Fold the known value into the constant operand.
5980             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5981             // Insert a new ICmp of the other select operand.
5982             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5983                                                    LHSI->getOperand(2), RHSC,
5984                                                    I.getName()), I);
5985           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5986             // Fold the known value into the constant operand.
5987             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5988             // Insert a new ICmp of the other select operand.
5989             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5990                                                    LHSI->getOperand(1), RHSC,
5991                                                    I.getName()), I);
5992           }
5993         }
5994
5995         if (Op1)
5996           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5997         break;
5998       }
5999       case Instruction::Malloc:
6000         // If we have (malloc != null), and if the malloc has a single use, we
6001         // can assume it is successful and remove the malloc.
6002         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6003           AddToWorkList(LHSI);
6004           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6005                                                          !I.isTrueWhenEqual()));
6006         }
6007         break;
6008       }
6009   }
6010
6011   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6012   if (User *GEP = dyn_castGetElementPtr(Op0))
6013     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6014       return NI;
6015   if (User *GEP = dyn_castGetElementPtr(Op1))
6016     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6017                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6018       return NI;
6019
6020   // Test to see if the operands of the icmp are casted versions of other
6021   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6022   // now.
6023   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6024     if (isa<PointerType>(Op0->getType()) && 
6025         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6026       // We keep moving the cast from the left operand over to the right
6027       // operand, where it can often be eliminated completely.
6028       Op0 = CI->getOperand(0);
6029
6030       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6031       // so eliminate it as well.
6032       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6033         Op1 = CI2->getOperand(0);
6034
6035       // If Op1 is a constant, we can fold the cast into the constant.
6036       if (Op0->getType() != Op1->getType()) {
6037         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6038           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6039         } else {
6040           // Otherwise, cast the RHS right before the icmp
6041           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6042         }
6043       }
6044       return new ICmpInst(I.getPredicate(), Op0, Op1);
6045     }
6046   }
6047   
6048   if (isa<CastInst>(Op0)) {
6049     // Handle the special case of: icmp (cast bool to X), <cst>
6050     // This comes up when you have code like
6051     //   int X = A < B;
6052     //   if (X) ...
6053     // For generality, we handle any zero-extension of any operand comparison
6054     // with a constant or another cast from the same type.
6055     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6056       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6057         return R;
6058   }
6059   
6060   // See if it's the same type of instruction on the left and right.
6061   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6062     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6063       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6064           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
6065           I.isEquality()) {
6066         switch (Op0I->getOpcode()) {
6067         default: break;
6068         case Instruction::Add:
6069         case Instruction::Sub:
6070         case Instruction::Xor:
6071           // a+x icmp eq/ne b+x --> a icmp b
6072           return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6073                               Op1I->getOperand(0));
6074           break;
6075         case Instruction::Mul:
6076           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6077             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6078             // Mask = -1 >> count-trailing-zeros(Cst).
6079             if (!CI->isZero() && !CI->isOne()) {
6080               const APInt &AP = CI->getValue();
6081               ConstantInt *Mask = ConstantInt::get(
6082                                       APInt::getLowBitsSet(AP.getBitWidth(),
6083                                                            AP.getBitWidth() -
6084                                                       AP.countTrailingZeros()));
6085               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6086                                                             Mask);
6087               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6088                                                             Mask);
6089               InsertNewInstBefore(And1, I);
6090               InsertNewInstBefore(And2, I);
6091               return new ICmpInst(I.getPredicate(), And1, And2);
6092             }
6093           }
6094           break;
6095         }
6096       }
6097     }
6098   }
6099   
6100   // ~x < ~y --> y < x
6101   { Value *A, *B;
6102     if (match(Op0, m_Not(m_Value(A))) &&
6103         match(Op1, m_Not(m_Value(B))))
6104       return new ICmpInst(I.getPredicate(), B, A);
6105   }
6106   
6107   if (I.isEquality()) {
6108     Value *A, *B, *C, *D;
6109     
6110     // -x == -y --> x == y
6111     if (match(Op0, m_Neg(m_Value(A))) &&
6112         match(Op1, m_Neg(m_Value(B))))
6113       return new ICmpInst(I.getPredicate(), A, B);
6114     
6115     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6116       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6117         Value *OtherVal = A == Op1 ? B : A;
6118         return new ICmpInst(I.getPredicate(), OtherVal,
6119                             Constant::getNullValue(A->getType()));
6120       }
6121
6122       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6123         // A^c1 == C^c2 --> A == C^(c1^c2)
6124         ConstantInt *C1, *C2;
6125         if (match(B, m_ConstantInt(C1)) &&
6126             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6127           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6128           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6129           return new ICmpInst(I.getPredicate(), A,
6130                               InsertNewInstBefore(Xor, I));
6131         }
6132         
6133         // A^B == A^D -> B == D
6134         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6135         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6136         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6137         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6138       }
6139     }
6140     
6141     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6142         (A == Op0 || B == Op0)) {
6143       // A == (A^B)  ->  B == 0
6144       Value *OtherVal = A == Op0 ? B : A;
6145       return new ICmpInst(I.getPredicate(), OtherVal,
6146                           Constant::getNullValue(A->getType()));
6147     }
6148
6149     // (A-B) == A  ->  B == 0
6150     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6151       return new ICmpInst(I.getPredicate(), B, 
6152                           Constant::getNullValue(B->getType()));
6153
6154     // A == (A-B)  ->  B == 0
6155     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6156       return new ICmpInst(I.getPredicate(), B,
6157                           Constant::getNullValue(B->getType()));
6158     
6159     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6160     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6161         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6162         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6163       Value *X = 0, *Y = 0, *Z = 0;
6164       
6165       if (A == C) {
6166         X = B; Y = D; Z = A;
6167       } else if (A == D) {
6168         X = B; Y = C; Z = A;
6169       } else if (B == C) {
6170         X = A; Y = D; Z = B;
6171       } else if (B == D) {
6172         X = A; Y = C; Z = B;
6173       }
6174       
6175       if (X) {   // Build (X^Y) & Z
6176         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6177         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6178         I.setOperand(0, Op1);
6179         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6180         return &I;
6181       }
6182     }
6183   }
6184   return Changed ? &I : 0;
6185 }
6186
6187
6188 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6189 /// and CmpRHS are both known to be integer constants.
6190 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6191                                           ConstantInt *DivRHS) {
6192   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6193   const APInt &CmpRHSV = CmpRHS->getValue();
6194   
6195   // FIXME: If the operand types don't match the type of the divide 
6196   // then don't attempt this transform. The code below doesn't have the
6197   // logic to deal with a signed divide and an unsigned compare (and
6198   // vice versa). This is because (x /s C1) <s C2  produces different 
6199   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6200   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6201   // work. :(  The if statement below tests that condition and bails 
6202   // if it finds it. 
6203   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6204   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6205     return 0;
6206   if (DivRHS->isZero())
6207     return 0; // The ProdOV computation fails on divide by zero.
6208   if (DivIsSigned && DivRHS->isAllOnesValue())
6209     return 0; // The overflow computation also screws up here
6210   if (DivRHS->isOne())
6211     return 0; // Not worth bothering, and eliminates some funny cases
6212               // with INT_MIN.
6213
6214   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6215   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6216   // C2 (CI). By solving for X we can turn this into a range check 
6217   // instead of computing a divide. 
6218   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6219
6220   // Determine if the product overflows by seeing if the product is
6221   // not equal to the divide. Make sure we do the same kind of divide
6222   // as in the LHS instruction that we're folding. 
6223   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6224                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6225
6226   // Get the ICmp opcode
6227   ICmpInst::Predicate Pred = ICI.getPredicate();
6228
6229   // Figure out the interval that is being checked.  For example, a comparison
6230   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6231   // Compute this interval based on the constants involved and the signedness of
6232   // the compare/divide.  This computes a half-open interval, keeping track of
6233   // whether either value in the interval overflows.  After analysis each
6234   // overflow variable is set to 0 if it's corresponding bound variable is valid
6235   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6236   int LoOverflow = 0, HiOverflow = 0;
6237   ConstantInt *LoBound = 0, *HiBound = 0;
6238   
6239   if (!DivIsSigned) {  // udiv
6240     // e.g. X/5 op 3  --> [15, 20)
6241     LoBound = Prod;
6242     HiOverflow = LoOverflow = ProdOV;
6243     if (!HiOverflow)
6244       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6245   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6246     if (CmpRHSV == 0) {       // (X / pos) op 0
6247       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6248       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6249       HiBound = DivRHS;
6250     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6251       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6252       HiOverflow = LoOverflow = ProdOV;
6253       if (!HiOverflow)
6254         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6255     } else {                       // (X / pos) op neg
6256       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6257       HiBound = AddOne(Prod);
6258       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6259       if (!LoOverflow) {
6260         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6261         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6262                                      true) ? -1 : 0;
6263        }
6264     }
6265   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6266     if (CmpRHSV == 0) {       // (X / neg) op 0
6267       // e.g. X/-5 op 0  --> [-4, 5)
6268       LoBound = AddOne(DivRHS);
6269       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6270       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6271         HiOverflow = 1;            // [INTMIN+1, overflow)
6272         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6273       }
6274     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6275       // e.g. X/-5 op 3  --> [-19, -14)
6276       HiBound = AddOne(Prod);
6277       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6278       if (!LoOverflow)
6279         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6280     } else {                       // (X / neg) op neg
6281       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6282       LoOverflow = HiOverflow = ProdOV;
6283       if (!HiOverflow)
6284         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6285     }
6286     
6287     // Dividing by a negative swaps the condition.  LT <-> GT
6288     Pred = ICmpInst::getSwappedPredicate(Pred);
6289   }
6290
6291   Value *X = DivI->getOperand(0);
6292   switch (Pred) {
6293   default: assert(0 && "Unhandled icmp opcode!");
6294   case ICmpInst::ICMP_EQ:
6295     if (LoOverflow && HiOverflow)
6296       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6297     else if (HiOverflow)
6298       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6299                           ICmpInst::ICMP_UGE, X, LoBound);
6300     else if (LoOverflow)
6301       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6302                           ICmpInst::ICMP_ULT, X, HiBound);
6303     else
6304       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6305   case ICmpInst::ICMP_NE:
6306     if (LoOverflow && HiOverflow)
6307       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6308     else if (HiOverflow)
6309       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6310                           ICmpInst::ICMP_ULT, X, LoBound);
6311     else if (LoOverflow)
6312       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6313                           ICmpInst::ICMP_UGE, X, HiBound);
6314     else
6315       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6316   case ICmpInst::ICMP_ULT:
6317   case ICmpInst::ICMP_SLT:
6318     if (LoOverflow == +1)   // Low bound is greater than input range.
6319       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6320     if (LoOverflow == -1)   // Low bound is less than input range.
6321       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6322     return new ICmpInst(Pred, X, LoBound);
6323   case ICmpInst::ICMP_UGT:
6324   case ICmpInst::ICMP_SGT:
6325     if (HiOverflow == +1)       // High bound greater than input range.
6326       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6327     else if (HiOverflow == -1)  // High bound less than input range.
6328       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6329     if (Pred == ICmpInst::ICMP_UGT)
6330       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6331     else
6332       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6333   }
6334 }
6335
6336
6337 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6338 ///
6339 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6340                                                           Instruction *LHSI,
6341                                                           ConstantInt *RHS) {
6342   const APInt &RHSV = RHS->getValue();
6343   
6344   switch (LHSI->getOpcode()) {
6345   case Instruction::Trunc:
6346     if (ICI.isEquality() && LHSI->hasOneUse()) {
6347       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6348       // of the high bits truncated out of x are known.
6349       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6350              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6351       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6352       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6353       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6354       
6355       // If all the high bits are known, we can do this xform.
6356       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6357         // Pull in the high bits from known-ones set.
6358         APInt NewRHS(RHS->getValue());
6359         NewRHS.zext(SrcBits);
6360         NewRHS |= KnownOne;
6361         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6362                             ConstantInt::get(NewRHS));
6363       }
6364     }
6365     break;
6366       
6367   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6368     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6369       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6370       // fold the xor.
6371       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6372           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6373         Value *CompareVal = LHSI->getOperand(0);
6374         
6375         // If the sign bit of the XorCST is not set, there is no change to
6376         // the operation, just stop using the Xor.
6377         if (!XorCST->getValue().isNegative()) {
6378           ICI.setOperand(0, CompareVal);
6379           AddToWorkList(LHSI);
6380           return &ICI;
6381         }
6382         
6383         // Was the old condition true if the operand is positive?
6384         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6385         
6386         // If so, the new one isn't.
6387         isTrueIfPositive ^= true;
6388         
6389         if (isTrueIfPositive)
6390           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6391         else
6392           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6393       }
6394     }
6395     break;
6396   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6397     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6398         LHSI->getOperand(0)->hasOneUse()) {
6399       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6400       
6401       // If the LHS is an AND of a truncating cast, we can widen the
6402       // and/compare to be the input width without changing the value
6403       // produced, eliminating a cast.
6404       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6405         // We can do this transformation if either the AND constant does not
6406         // have its sign bit set or if it is an equality comparison. 
6407         // Extending a relational comparison when we're checking the sign
6408         // bit would not work.
6409         if (Cast->hasOneUse() &&
6410             (ICI.isEquality() ||
6411              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6412           uint32_t BitWidth = 
6413             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6414           APInt NewCST = AndCST->getValue();
6415           NewCST.zext(BitWidth);
6416           APInt NewCI = RHSV;
6417           NewCI.zext(BitWidth);
6418           Instruction *NewAnd = 
6419             BinaryOperator::CreateAnd(Cast->getOperand(0),
6420                                       ConstantInt::get(NewCST),LHSI->getName());
6421           InsertNewInstBefore(NewAnd, ICI);
6422           return new ICmpInst(ICI.getPredicate(), NewAnd,
6423                               ConstantInt::get(NewCI));
6424         }
6425       }
6426       
6427       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6428       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6429       // happens a LOT in code produced by the C front-end, for bitfield
6430       // access.
6431       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6432       if (Shift && !Shift->isShift())
6433         Shift = 0;
6434       
6435       ConstantInt *ShAmt;
6436       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6437       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6438       const Type *AndTy = AndCST->getType();          // Type of the and.
6439       
6440       // We can fold this as long as we can't shift unknown bits
6441       // into the mask.  This can only happen with signed shift
6442       // rights, as they sign-extend.
6443       if (ShAmt) {
6444         bool CanFold = Shift->isLogicalShift();
6445         if (!CanFold) {
6446           // To test for the bad case of the signed shr, see if any
6447           // of the bits shifted in could be tested after the mask.
6448           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6449           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6450           
6451           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6452           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6453                AndCST->getValue()) == 0)
6454             CanFold = true;
6455         }
6456         
6457         if (CanFold) {
6458           Constant *NewCst;
6459           if (Shift->getOpcode() == Instruction::Shl)
6460             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6461           else
6462             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6463           
6464           // Check to see if we are shifting out any of the bits being
6465           // compared.
6466           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6467             // If we shifted bits out, the fold is not going to work out.
6468             // As a special case, check to see if this means that the
6469             // result is always true or false now.
6470             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6471               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6472             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6473               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6474           } else {
6475             ICI.setOperand(1, NewCst);
6476             Constant *NewAndCST;
6477             if (Shift->getOpcode() == Instruction::Shl)
6478               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6479             else
6480               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6481             LHSI->setOperand(1, NewAndCST);
6482             LHSI->setOperand(0, Shift->getOperand(0));
6483             AddToWorkList(Shift); // Shift is dead.
6484             AddUsesToWorkList(ICI);
6485             return &ICI;
6486           }
6487         }
6488       }
6489       
6490       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6491       // preferable because it allows the C<<Y expression to be hoisted out
6492       // of a loop if Y is invariant and X is not.
6493       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6494           ICI.isEquality() && !Shift->isArithmeticShift() &&
6495           isa<Instruction>(Shift->getOperand(0))) {
6496         // Compute C << Y.
6497         Value *NS;
6498         if (Shift->getOpcode() == Instruction::LShr) {
6499           NS = BinaryOperator::CreateShl(AndCST, 
6500                                          Shift->getOperand(1), "tmp");
6501         } else {
6502           // Insert a logical shift.
6503           NS = BinaryOperator::CreateLShr(AndCST,
6504                                           Shift->getOperand(1), "tmp");
6505         }
6506         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6507         
6508         // Compute X & (C << Y).
6509         Instruction *NewAnd = 
6510           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6511         InsertNewInstBefore(NewAnd, ICI);
6512         
6513         ICI.setOperand(0, NewAnd);
6514         return &ICI;
6515       }
6516     }
6517     break;
6518     
6519   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6520     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6521     if (!ShAmt) break;
6522     
6523     uint32_t TypeBits = RHSV.getBitWidth();
6524     
6525     // Check that the shift amount is in range.  If not, don't perform
6526     // undefined shifts.  When the shift is visited it will be
6527     // simplified.
6528     if (ShAmt->uge(TypeBits))
6529       break;
6530     
6531     if (ICI.isEquality()) {
6532       // If we are comparing against bits always shifted out, the
6533       // comparison cannot succeed.
6534       Constant *Comp =
6535         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6536       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6537         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6538         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6539         return ReplaceInstUsesWith(ICI, Cst);
6540       }
6541       
6542       if (LHSI->hasOneUse()) {
6543         // Otherwise strength reduce the shift into an and.
6544         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6545         Constant *Mask =
6546           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6547         
6548         Instruction *AndI =
6549           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6550                                     Mask, LHSI->getName()+".mask");
6551         Value *And = InsertNewInstBefore(AndI, ICI);
6552         return new ICmpInst(ICI.getPredicate(), And,
6553                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6554       }
6555     }
6556     
6557     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6558     bool TrueIfSigned = false;
6559     if (LHSI->hasOneUse() &&
6560         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6561       // (X << 31) <s 0  --> (X&1) != 0
6562       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6563                                            (TypeBits-ShAmt->getZExtValue()-1));
6564       Instruction *AndI =
6565         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6566                                   Mask, LHSI->getName()+".mask");
6567       Value *And = InsertNewInstBefore(AndI, ICI);
6568       
6569       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6570                           And, Constant::getNullValue(And->getType()));
6571     }
6572     break;
6573   }
6574     
6575   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6576   case Instruction::AShr: {
6577     // Only handle equality comparisons of shift-by-constant.
6578     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6579     if (!ShAmt || !ICI.isEquality()) break;
6580
6581     // Check that the shift amount is in range.  If not, don't perform
6582     // undefined shifts.  When the shift is visited it will be
6583     // simplified.
6584     uint32_t TypeBits = RHSV.getBitWidth();
6585     if (ShAmt->uge(TypeBits))
6586       break;
6587     
6588     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6589       
6590     // If we are comparing against bits always shifted out, the
6591     // comparison cannot succeed.
6592     APInt Comp = RHSV << ShAmtVal;
6593     if (LHSI->getOpcode() == Instruction::LShr)
6594       Comp = Comp.lshr(ShAmtVal);
6595     else
6596       Comp = Comp.ashr(ShAmtVal);
6597     
6598     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6599       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6600       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6601       return ReplaceInstUsesWith(ICI, Cst);
6602     }
6603     
6604     // Otherwise, check to see if the bits shifted out are known to be zero.
6605     // If so, we can compare against the unshifted value:
6606     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6607     if (LHSI->hasOneUse() &&
6608         MaskedValueIsZero(LHSI->getOperand(0), 
6609                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6610       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6611                           ConstantExpr::getShl(RHS, ShAmt));
6612     }
6613       
6614     if (LHSI->hasOneUse()) {
6615       // Otherwise strength reduce the shift into an and.
6616       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6617       Constant *Mask = ConstantInt::get(Val);
6618       
6619       Instruction *AndI =
6620         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6621                                   Mask, LHSI->getName()+".mask");
6622       Value *And = InsertNewInstBefore(AndI, ICI);
6623       return new ICmpInst(ICI.getPredicate(), And,
6624                           ConstantExpr::getShl(RHS, ShAmt));
6625     }
6626     break;
6627   }
6628     
6629   case Instruction::SDiv:
6630   case Instruction::UDiv:
6631     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6632     // Fold this div into the comparison, producing a range check. 
6633     // Determine, based on the divide type, what the range is being 
6634     // checked.  If there is an overflow on the low or high side, remember 
6635     // it, otherwise compute the range [low, hi) bounding the new value.
6636     // See: InsertRangeTest above for the kinds of replacements possible.
6637     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6638       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6639                                           DivRHS))
6640         return R;
6641     break;
6642
6643   case Instruction::Add:
6644     // Fold: icmp pred (add, X, C1), C2
6645
6646     if (!ICI.isEquality()) {
6647       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6648       if (!LHSC) break;
6649       const APInt &LHSV = LHSC->getValue();
6650
6651       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6652                             .subtract(LHSV);
6653
6654       if (ICI.isSignedPredicate()) {
6655         if (CR.getLower().isSignBit()) {
6656           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6657                               ConstantInt::get(CR.getUpper()));
6658         } else if (CR.getUpper().isSignBit()) {
6659           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6660                               ConstantInt::get(CR.getLower()));
6661         }
6662       } else {
6663         if (CR.getLower().isMinValue()) {
6664           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6665                               ConstantInt::get(CR.getUpper()));
6666         } else if (CR.getUpper().isMinValue()) {
6667           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6668                               ConstantInt::get(CR.getLower()));
6669         }
6670       }
6671     }
6672     break;
6673   }
6674   
6675   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6676   if (ICI.isEquality()) {
6677     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6678     
6679     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6680     // the second operand is a constant, simplify a bit.
6681     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6682       switch (BO->getOpcode()) {
6683       case Instruction::SRem:
6684         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6685         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6686           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6687           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6688             Instruction *NewRem =
6689               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6690                                          BO->getName());
6691             InsertNewInstBefore(NewRem, ICI);
6692             return new ICmpInst(ICI.getPredicate(), NewRem, 
6693                                 Constant::getNullValue(BO->getType()));
6694           }
6695         }
6696         break;
6697       case Instruction::Add:
6698         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6699         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6700           if (BO->hasOneUse())
6701             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6702                                 Subtract(RHS, BOp1C));
6703         } else if (RHSV == 0) {
6704           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6705           // efficiently invertible, or if the add has just this one use.
6706           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6707           
6708           if (Value *NegVal = dyn_castNegVal(BOp1))
6709             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6710           else if (Value *NegVal = dyn_castNegVal(BOp0))
6711             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6712           else if (BO->hasOneUse()) {
6713             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6714             InsertNewInstBefore(Neg, ICI);
6715             Neg->takeName(BO);
6716             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6717           }
6718         }
6719         break;
6720       case Instruction::Xor:
6721         // For the xor case, we can xor two constants together, eliminating
6722         // the explicit xor.
6723         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6724           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6725                               ConstantExpr::getXor(RHS, BOC));
6726         
6727         // FALLTHROUGH
6728       case Instruction::Sub:
6729         // Replace (([sub|xor] A, B) != 0) with (A != B)
6730         if (RHSV == 0)
6731           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6732                               BO->getOperand(1));
6733         break;
6734         
6735       case Instruction::Or:
6736         // If bits are being or'd in that are not present in the constant we
6737         // are comparing against, then the comparison could never succeed!
6738         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6739           Constant *NotCI = ConstantExpr::getNot(RHS);
6740           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6741             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6742                                                              isICMP_NE));
6743         }
6744         break;
6745         
6746       case Instruction::And:
6747         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6748           // If bits are being compared against that are and'd out, then the
6749           // comparison can never succeed!
6750           if ((RHSV & ~BOC->getValue()) != 0)
6751             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6752                                                              isICMP_NE));
6753           
6754           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6755           if (RHS == BOC && RHSV.isPowerOf2())
6756             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6757                                 ICmpInst::ICMP_NE, LHSI,
6758                                 Constant::getNullValue(RHS->getType()));
6759           
6760           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6761           if (BOC->getValue().isSignBit()) {
6762             Value *X = BO->getOperand(0);
6763             Constant *Zero = Constant::getNullValue(X->getType());
6764             ICmpInst::Predicate pred = isICMP_NE ? 
6765               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6766             return new ICmpInst(pred, X, Zero);
6767           }
6768           
6769           // ((X & ~7) == 0) --> X < 8
6770           if (RHSV == 0 && isHighOnes(BOC)) {
6771             Value *X = BO->getOperand(0);
6772             Constant *NegX = ConstantExpr::getNeg(BOC);
6773             ICmpInst::Predicate pred = isICMP_NE ? 
6774               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6775             return new ICmpInst(pred, X, NegX);
6776           }
6777         }
6778       default: break;
6779       }
6780     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6781       // Handle icmp {eq|ne} <intrinsic>, intcst.
6782       if (II->getIntrinsicID() == Intrinsic::bswap) {
6783         AddToWorkList(II);
6784         ICI.setOperand(0, II->getOperand(1));
6785         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6786         return &ICI;
6787       }
6788     }
6789   }
6790   return 0;
6791 }
6792
6793 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6794 /// We only handle extending casts so far.
6795 ///
6796 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6797   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6798   Value *LHSCIOp        = LHSCI->getOperand(0);
6799   const Type *SrcTy     = LHSCIOp->getType();
6800   const Type *DestTy    = LHSCI->getType();
6801   Value *RHSCIOp;
6802
6803   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6804   // integer type is the same size as the pointer type.
6805   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6806       getTargetData().getPointerSizeInBits() == 
6807          cast<IntegerType>(DestTy)->getBitWidth()) {
6808     Value *RHSOp = 0;
6809     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6810       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6811     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6812       RHSOp = RHSC->getOperand(0);
6813       // If the pointer types don't match, insert a bitcast.
6814       if (LHSCIOp->getType() != RHSOp->getType())
6815         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6816     }
6817
6818     if (RHSOp)
6819       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6820   }
6821   
6822   // The code below only handles extension cast instructions, so far.
6823   // Enforce this.
6824   if (LHSCI->getOpcode() != Instruction::ZExt &&
6825       LHSCI->getOpcode() != Instruction::SExt)
6826     return 0;
6827
6828   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6829   bool isSignedCmp = ICI.isSignedPredicate();
6830
6831   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6832     // Not an extension from the same type?
6833     RHSCIOp = CI->getOperand(0);
6834     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6835       return 0;
6836     
6837     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6838     // and the other is a zext), then we can't handle this.
6839     if (CI->getOpcode() != LHSCI->getOpcode())
6840       return 0;
6841
6842     // Deal with equality cases early.
6843     if (ICI.isEquality())
6844       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6845
6846     // A signed comparison of sign extended values simplifies into a
6847     // signed comparison.
6848     if (isSignedCmp && isSignedExt)
6849       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6850
6851     // The other three cases all fold into an unsigned comparison.
6852     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6853   }
6854
6855   // If we aren't dealing with a constant on the RHS, exit early
6856   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6857   if (!CI)
6858     return 0;
6859
6860   // Compute the constant that would happen if we truncated to SrcTy then
6861   // reextended to DestTy.
6862   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6863   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6864
6865   // If the re-extended constant didn't change...
6866   if (Res2 == CI) {
6867     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6868     // For example, we might have:
6869     //    %A = sext short %X to uint
6870     //    %B = icmp ugt uint %A, 1330
6871     // It is incorrect to transform this into 
6872     //    %B = icmp ugt short %X, 1330 
6873     // because %A may have negative value. 
6874     //
6875     // However, we allow this when the compare is EQ/NE, because they are
6876     // signless.
6877     if (isSignedExt == isSignedCmp || ICI.isEquality())
6878       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6879     return 0;
6880   }
6881
6882   // The re-extended constant changed so the constant cannot be represented 
6883   // in the shorter type. Consequently, we cannot emit a simple comparison.
6884
6885   // First, handle some easy cases. We know the result cannot be equal at this
6886   // point so handle the ICI.isEquality() cases
6887   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6888     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6889   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6890     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6891
6892   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6893   // should have been folded away previously and not enter in here.
6894   Value *Result;
6895   if (isSignedCmp) {
6896     // We're performing a signed comparison.
6897     if (cast<ConstantInt>(CI)->getValue().isNegative())
6898       Result = ConstantInt::getFalse();          // X < (small) --> false
6899     else
6900       Result = ConstantInt::getTrue();           // X < (large) --> true
6901   } else {
6902     // We're performing an unsigned comparison.
6903     if (isSignedExt) {
6904       // We're performing an unsigned comp with a sign extended value.
6905       // This is true if the input is >= 0. [aka >s -1]
6906       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6907       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6908                                    NegOne, ICI.getName()), ICI);
6909     } else {
6910       // Unsigned extend & unsigned compare -> always true.
6911       Result = ConstantInt::getTrue();
6912     }
6913   }
6914
6915   // Finally, return the value computed.
6916   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6917       ICI.getPredicate() == ICmpInst::ICMP_SLT)
6918     return ReplaceInstUsesWith(ICI, Result);
6919
6920   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6921           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6922          "ICmp should be folded!");
6923   if (Constant *CI = dyn_cast<Constant>(Result))
6924     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6925   return BinaryOperator::CreateNot(Result);
6926 }
6927
6928 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6929   return commonShiftTransforms(I);
6930 }
6931
6932 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6933   return commonShiftTransforms(I);
6934 }
6935
6936 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6937   if (Instruction *R = commonShiftTransforms(I))
6938     return R;
6939   
6940   Value *Op0 = I.getOperand(0);
6941   
6942   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6943   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6944     if (CSI->isAllOnesValue())
6945       return ReplaceInstUsesWith(I, CSI);
6946   
6947   // See if we can turn a signed shr into an unsigned shr.
6948   if (!isa<VectorType>(I.getType()) &&
6949       MaskedValueIsZero(Op0,
6950                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6951     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6952   
6953   return 0;
6954 }
6955
6956 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6957   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6958   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6959
6960   // shl X, 0 == X and shr X, 0 == X
6961   // shl 0, X == 0 and shr 0, X == 0
6962   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6963       Op0 == Constant::getNullValue(Op0->getType()))
6964     return ReplaceInstUsesWith(I, Op0);
6965   
6966   if (isa<UndefValue>(Op0)) {            
6967     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6968       return ReplaceInstUsesWith(I, Op0);
6969     else                                    // undef << X -> 0, undef >>u X -> 0
6970       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6971   }
6972   if (isa<UndefValue>(Op1)) {
6973     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6974       return ReplaceInstUsesWith(I, Op0);          
6975     else                                     // X << undef, X >>u undef -> 0
6976       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6977   }
6978
6979   // Try to fold constant and into select arguments.
6980   if (isa<Constant>(Op0))
6981     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6982       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6983         return R;
6984
6985   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6986     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6987       return Res;
6988   return 0;
6989 }
6990
6991 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6992                                                BinaryOperator &I) {
6993   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6994
6995   // See if we can simplify any instructions used by the instruction whose sole 
6996   // purpose is to compute bits we don't care about.
6997   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6998   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6999   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
7000                            KnownZero, KnownOne))
7001     return &I;
7002   
7003   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7004   // of a signed value.
7005   //
7006   if (Op1->uge(TypeBits)) {
7007     if (I.getOpcode() != Instruction::AShr)
7008       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7009     else {
7010       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7011       return &I;
7012     }
7013   }
7014   
7015   // ((X*C1) << C2) == (X * (C1 << C2))
7016   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7017     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7018       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7019         return BinaryOperator::CreateMul(BO->getOperand(0),
7020                                          ConstantExpr::getShl(BOOp, Op1));
7021   
7022   // Try to fold constant and into select arguments.
7023   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7024     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7025       return R;
7026   if (isa<PHINode>(Op0))
7027     if (Instruction *NV = FoldOpIntoPhi(I))
7028       return NV;
7029   
7030   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7031   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7032     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7033     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7034     // place.  Don't try to do this transformation in this case.  Also, we
7035     // require that the input operand is a shift-by-constant so that we have
7036     // confidence that the shifts will get folded together.  We could do this
7037     // xform in more cases, but it is unlikely to be profitable.
7038     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7039         isa<ConstantInt>(TrOp->getOperand(1))) {
7040       // Okay, we'll do this xform.  Make the shift of shift.
7041       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7042       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7043                                                 I.getName());
7044       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7045
7046       // For logical shifts, the truncation has the effect of making the high
7047       // part of the register be zeros.  Emulate this by inserting an AND to
7048       // clear the top bits as needed.  This 'and' will usually be zapped by
7049       // other xforms later if dead.
7050       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7051       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7052       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7053       
7054       // The mask we constructed says what the trunc would do if occurring
7055       // between the shifts.  We want to know the effect *after* the second
7056       // shift.  We know that it is a logical shift by a constant, so adjust the
7057       // mask as appropriate.
7058       if (I.getOpcode() == Instruction::Shl)
7059         MaskV <<= Op1->getZExtValue();
7060       else {
7061         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7062         MaskV = MaskV.lshr(Op1->getZExtValue());
7063       }
7064
7065       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7066                                                    TI->getName());
7067       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7068
7069       // Return the value truncated to the interesting size.
7070       return new TruncInst(And, I.getType());
7071     }
7072   }
7073   
7074   if (Op0->hasOneUse()) {
7075     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7076       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7077       Value *V1, *V2;
7078       ConstantInt *CC;
7079       switch (Op0BO->getOpcode()) {
7080         default: break;
7081         case Instruction::Add:
7082         case Instruction::And:
7083         case Instruction::Or:
7084         case Instruction::Xor: {
7085           // These operators commute.
7086           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7087           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7088               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7089             Instruction *YS = BinaryOperator::CreateShl(
7090                                             Op0BO->getOperand(0), Op1,
7091                                             Op0BO->getName());
7092             InsertNewInstBefore(YS, I); // (Y << C)
7093             Instruction *X = 
7094               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7095                                      Op0BO->getOperand(1)->getName());
7096             InsertNewInstBefore(X, I);  // (X + (Y << C))
7097             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7098             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7099                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7100           }
7101           
7102           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7103           Value *Op0BOOp1 = Op0BO->getOperand(1);
7104           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7105               match(Op0BOOp1, 
7106                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7107                           m_ConstantInt(CC))) &&
7108               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7109             Instruction *YS = BinaryOperator::CreateShl(
7110                                                      Op0BO->getOperand(0), Op1,
7111                                                      Op0BO->getName());
7112             InsertNewInstBefore(YS, I); // (Y << C)
7113             Instruction *XM =
7114               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7115                                         V1->getName()+".mask");
7116             InsertNewInstBefore(XM, I); // X & (CC << C)
7117             
7118             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7119           }
7120         }
7121           
7122         // FALL THROUGH.
7123         case Instruction::Sub: {
7124           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7125           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7126               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7127             Instruction *YS = BinaryOperator::CreateShl(
7128                                                      Op0BO->getOperand(1), Op1,
7129                                                      Op0BO->getName());
7130             InsertNewInstBefore(YS, I); // (Y << C)
7131             Instruction *X =
7132               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7133                                      Op0BO->getOperand(0)->getName());
7134             InsertNewInstBefore(X, I);  // (X + (Y << C))
7135             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7136             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7137                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7138           }
7139           
7140           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7141           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7142               match(Op0BO->getOperand(0),
7143                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7144                           m_ConstantInt(CC))) && V2 == Op1 &&
7145               cast<BinaryOperator>(Op0BO->getOperand(0))
7146                   ->getOperand(0)->hasOneUse()) {
7147             Instruction *YS = BinaryOperator::CreateShl(
7148                                                      Op0BO->getOperand(1), Op1,
7149                                                      Op0BO->getName());
7150             InsertNewInstBefore(YS, I); // (Y << C)
7151             Instruction *XM =
7152               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7153                                         V1->getName()+".mask");
7154             InsertNewInstBefore(XM, I); // X & (CC << C)
7155             
7156             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7157           }
7158           
7159           break;
7160         }
7161       }
7162       
7163       
7164       // If the operand is an bitwise operator with a constant RHS, and the
7165       // shift is the only use, we can pull it out of the shift.
7166       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7167         bool isValid = true;     // Valid only for And, Or, Xor
7168         bool highBitSet = false; // Transform if high bit of constant set?
7169         
7170         switch (Op0BO->getOpcode()) {
7171           default: isValid = false; break;   // Do not perform transform!
7172           case Instruction::Add:
7173             isValid = isLeftShift;
7174             break;
7175           case Instruction::Or:
7176           case Instruction::Xor:
7177             highBitSet = false;
7178             break;
7179           case Instruction::And:
7180             highBitSet = true;
7181             break;
7182         }
7183         
7184         // If this is a signed shift right, and the high bit is modified
7185         // by the logical operation, do not perform the transformation.
7186         // The highBitSet boolean indicates the value of the high bit of
7187         // the constant which would cause it to be modified for this
7188         // operation.
7189         //
7190         if (isValid && I.getOpcode() == Instruction::AShr)
7191           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7192         
7193         if (isValid) {
7194           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7195           
7196           Instruction *NewShift =
7197             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7198           InsertNewInstBefore(NewShift, I);
7199           NewShift->takeName(Op0BO);
7200           
7201           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7202                                         NewRHS);
7203         }
7204       }
7205     }
7206   }
7207   
7208   // Find out if this is a shift of a shift by a constant.
7209   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7210   if (ShiftOp && !ShiftOp->isShift())
7211     ShiftOp = 0;
7212   
7213   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7214     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7215     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7216     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7217     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7218     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7219     Value *X = ShiftOp->getOperand(0);
7220     
7221     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7222     if (AmtSum > TypeBits)
7223       AmtSum = TypeBits;
7224     
7225     const IntegerType *Ty = cast<IntegerType>(I.getType());
7226     
7227     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7228     if (I.getOpcode() == ShiftOp->getOpcode()) {
7229       return BinaryOperator::Create(I.getOpcode(), X,
7230                                     ConstantInt::get(Ty, AmtSum));
7231     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7232                I.getOpcode() == Instruction::AShr) {
7233       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7234       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7235     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7236                I.getOpcode() == Instruction::LShr) {
7237       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7238       Instruction *Shift =
7239         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7240       InsertNewInstBefore(Shift, I);
7241
7242       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7243       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7244     }
7245     
7246     // Okay, if we get here, one shift must be left, and the other shift must be
7247     // right.  See if the amounts are equal.
7248     if (ShiftAmt1 == ShiftAmt2) {
7249       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7250       if (I.getOpcode() == Instruction::Shl) {
7251         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7252         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7253       }
7254       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7255       if (I.getOpcode() == Instruction::LShr) {
7256         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7257         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7258       }
7259       // We can simplify ((X << C) >>s C) into a trunc + sext.
7260       // NOTE: we could do this for any C, but that would make 'unusual' integer
7261       // types.  For now, just stick to ones well-supported by the code
7262       // generators.
7263       const Type *SExtType = 0;
7264       switch (Ty->getBitWidth() - ShiftAmt1) {
7265       case 1  :
7266       case 8  :
7267       case 16 :
7268       case 32 :
7269       case 64 :
7270       case 128:
7271         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7272         break;
7273       default: break;
7274       }
7275       if (SExtType) {
7276         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7277         InsertNewInstBefore(NewTrunc, I);
7278         return new SExtInst(NewTrunc, Ty);
7279       }
7280       // Otherwise, we can't handle it yet.
7281     } else if (ShiftAmt1 < ShiftAmt2) {
7282       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7283       
7284       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7285       if (I.getOpcode() == Instruction::Shl) {
7286         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7287                ShiftOp->getOpcode() == Instruction::AShr);
7288         Instruction *Shift =
7289           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7290         InsertNewInstBefore(Shift, I);
7291         
7292         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7293         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7294       }
7295       
7296       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7297       if (I.getOpcode() == Instruction::LShr) {
7298         assert(ShiftOp->getOpcode() == Instruction::Shl);
7299         Instruction *Shift =
7300           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7301         InsertNewInstBefore(Shift, I);
7302         
7303         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7304         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7305       }
7306       
7307       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7308     } else {
7309       assert(ShiftAmt2 < ShiftAmt1);
7310       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7311
7312       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7313       if (I.getOpcode() == Instruction::Shl) {
7314         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7315                ShiftOp->getOpcode() == Instruction::AShr);
7316         Instruction *Shift =
7317           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7318                                  ConstantInt::get(Ty, ShiftDiff));
7319         InsertNewInstBefore(Shift, I);
7320         
7321         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7322         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7323       }
7324       
7325       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7326       if (I.getOpcode() == Instruction::LShr) {
7327         assert(ShiftOp->getOpcode() == Instruction::Shl);
7328         Instruction *Shift =
7329           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7330         InsertNewInstBefore(Shift, I);
7331         
7332         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7333         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7334       }
7335       
7336       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7337     }
7338   }
7339   return 0;
7340 }
7341
7342
7343 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7344 /// expression.  If so, decompose it, returning some value X, such that Val is
7345 /// X*Scale+Offset.
7346 ///
7347 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7348                                         int &Offset) {
7349   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7350   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7351     Offset = CI->getZExtValue();
7352     Scale  = 0;
7353     return ConstantInt::get(Type::Int32Ty, 0);
7354   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7355     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7356       if (I->getOpcode() == Instruction::Shl) {
7357         // This is a value scaled by '1 << the shift amt'.
7358         Scale = 1U << RHS->getZExtValue();
7359         Offset = 0;
7360         return I->getOperand(0);
7361       } else if (I->getOpcode() == Instruction::Mul) {
7362         // This value is scaled by 'RHS'.
7363         Scale = RHS->getZExtValue();
7364         Offset = 0;
7365         return I->getOperand(0);
7366       } else if (I->getOpcode() == Instruction::Add) {
7367         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7368         // where C1 is divisible by C2.
7369         unsigned SubScale;
7370         Value *SubVal = 
7371           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7372         Offset += RHS->getZExtValue();
7373         Scale = SubScale;
7374         return SubVal;
7375       }
7376     }
7377   }
7378
7379   // Otherwise, we can't look past this.
7380   Scale = 1;
7381   Offset = 0;
7382   return Val;
7383 }
7384
7385
7386 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7387 /// try to eliminate the cast by moving the type information into the alloc.
7388 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7389                                                    AllocationInst &AI) {
7390   const PointerType *PTy = cast<PointerType>(CI.getType());
7391   
7392   // Remove any uses of AI that are dead.
7393   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7394   
7395   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7396     Instruction *User = cast<Instruction>(*UI++);
7397     if (isInstructionTriviallyDead(User)) {
7398       while (UI != E && *UI == User)
7399         ++UI; // If this instruction uses AI more than once, don't break UI.
7400       
7401       ++NumDeadInst;
7402       DOUT << "IC: DCE: " << *User;
7403       EraseInstFromFunction(*User);
7404     }
7405   }
7406   
7407   // Get the type really allocated and the type casted to.
7408   const Type *AllocElTy = AI.getAllocatedType();
7409   const Type *CastElTy = PTy->getElementType();
7410   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7411
7412   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7413   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7414   if (CastElTyAlign < AllocElTyAlign) return 0;
7415
7416   // If the allocation has multiple uses, only promote it if we are strictly
7417   // increasing the alignment of the resultant allocation.  If we keep it the
7418   // same, we open the door to infinite loops of various kinds.
7419   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7420
7421   uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7422   uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
7423   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7424
7425   // See if we can satisfy the modulus by pulling a scale out of the array
7426   // size argument.
7427   unsigned ArraySizeScale;
7428   int ArrayOffset;
7429   Value *NumElements = // See if the array size is a decomposable linear expr.
7430     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7431  
7432   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7433   // do the xform.
7434   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7435       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7436
7437   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7438   Value *Amt = 0;
7439   if (Scale == 1) {
7440     Amt = NumElements;
7441   } else {
7442     // If the allocation size is constant, form a constant mul expression
7443     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7444     if (isa<ConstantInt>(NumElements))
7445       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7446     // otherwise multiply the amount and the number of elements
7447     else if (Scale != 1) {
7448       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7449       Amt = InsertNewInstBefore(Tmp, AI);
7450     }
7451   }
7452   
7453   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7454     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7455     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7456     Amt = InsertNewInstBefore(Tmp, AI);
7457   }
7458   
7459   AllocationInst *New;
7460   if (isa<MallocInst>(AI))
7461     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7462   else
7463     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7464   InsertNewInstBefore(New, AI);
7465   New->takeName(&AI);
7466   
7467   // If the allocation has multiple uses, insert a cast and change all things
7468   // that used it to use the new cast.  This will also hack on CI, but it will
7469   // die soon.
7470   if (!AI.hasOneUse()) {
7471     AddUsesToWorkList(AI);
7472     // New is the allocation instruction, pointer typed. AI is the original
7473     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7474     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7475     InsertNewInstBefore(NewCast, AI);
7476     AI.replaceAllUsesWith(NewCast);
7477   }
7478   return ReplaceInstUsesWith(CI, New);
7479 }
7480
7481 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7482 /// and return it as type Ty without inserting any new casts and without
7483 /// changing the computed value.  This is used by code that tries to decide
7484 /// whether promoting or shrinking integer operations to wider or smaller types
7485 /// will allow us to eliminate a truncate or extend.
7486 ///
7487 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7488 /// extension operation if Ty is larger.
7489 ///
7490 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7491 /// should return true if trunc(V) can be computed by computing V in the smaller
7492 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7493 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7494 /// efficiently truncated.
7495 ///
7496 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7497 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7498 /// the final result.
7499 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7500                                               unsigned CastOpc,
7501                                               int &NumCastsRemoved){
7502   // We can always evaluate constants in another type.
7503   if (isa<ConstantInt>(V))
7504     return true;
7505   
7506   Instruction *I = dyn_cast<Instruction>(V);
7507   if (!I) return false;
7508   
7509   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7510   
7511   // If this is an extension or truncate, we can often eliminate it.
7512   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7513     // If this is a cast from the destination type, we can trivially eliminate
7514     // it, and this will remove a cast overall.
7515     if (I->getOperand(0)->getType() == Ty) {
7516       // If the first operand is itself a cast, and is eliminable, do not count
7517       // this as an eliminable cast.  We would prefer to eliminate those two
7518       // casts first.
7519       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7520         ++NumCastsRemoved;
7521       return true;
7522     }
7523   }
7524
7525   // We can't extend or shrink something that has multiple uses: doing so would
7526   // require duplicating the instruction in general, which isn't profitable.
7527   if (!I->hasOneUse()) return false;
7528
7529   unsigned Opc = I->getOpcode();
7530   switch (Opc) {
7531   case Instruction::Add:
7532   case Instruction::Sub:
7533   case Instruction::Mul:
7534   case Instruction::And:
7535   case Instruction::Or:
7536   case Instruction::Xor:
7537     // These operators can all arbitrarily be extended or truncated.
7538     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7539                                       NumCastsRemoved) &&
7540            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7541                                       NumCastsRemoved);
7542
7543   case Instruction::Shl:
7544     // If we are truncating the result of this SHL, and if it's a shift of a
7545     // constant amount, we can always perform a SHL in a smaller type.
7546     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7547       uint32_t BitWidth = Ty->getBitWidth();
7548       if (BitWidth < OrigTy->getBitWidth() && 
7549           CI->getLimitedValue(BitWidth) < BitWidth)
7550         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7551                                           NumCastsRemoved);
7552     }
7553     break;
7554   case Instruction::LShr:
7555     // If this is a truncate of a logical shr, we can truncate it to a smaller
7556     // lshr iff we know that the bits we would otherwise be shifting in are
7557     // already zeros.
7558     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7559       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7560       uint32_t BitWidth = Ty->getBitWidth();
7561       if (BitWidth < OrigBitWidth &&
7562           MaskedValueIsZero(I->getOperand(0),
7563             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7564           CI->getLimitedValue(BitWidth) < BitWidth) {
7565         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7566                                           NumCastsRemoved);
7567       }
7568     }
7569     break;
7570   case Instruction::ZExt:
7571   case Instruction::SExt:
7572   case Instruction::Trunc:
7573     // If this is the same kind of case as our original (e.g. zext+zext), we
7574     // can safely replace it.  Note that replacing it does not reduce the number
7575     // of casts in the input.
7576     if (Opc == CastOpc)
7577       return true;
7578
7579     // sext (zext ty1), ty2 -> zext ty2
7580     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7581       return true;
7582     break;
7583   case Instruction::Select: {
7584     SelectInst *SI = cast<SelectInst>(I);
7585     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7586                                       NumCastsRemoved) &&
7587            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7588                                       NumCastsRemoved);
7589   }
7590   case Instruction::PHI: {
7591     // We can change a phi if we can change all operands.
7592     PHINode *PN = cast<PHINode>(I);
7593     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7594       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7595                                       NumCastsRemoved))
7596         return false;
7597     return true;
7598   }
7599   default:
7600     // TODO: Can handle more cases here.
7601     break;
7602   }
7603   
7604   return false;
7605 }
7606
7607 /// EvaluateInDifferentType - Given an expression that 
7608 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7609 /// evaluate the expression.
7610 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7611                                              bool isSigned) {
7612   if (Constant *C = dyn_cast<Constant>(V))
7613     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7614
7615   // Otherwise, it must be an instruction.
7616   Instruction *I = cast<Instruction>(V);
7617   Instruction *Res = 0;
7618   unsigned Opc = I->getOpcode();
7619   switch (Opc) {
7620   case Instruction::Add:
7621   case Instruction::Sub:
7622   case Instruction::Mul:
7623   case Instruction::And:
7624   case Instruction::Or:
7625   case Instruction::Xor:
7626   case Instruction::AShr:
7627   case Instruction::LShr:
7628   case Instruction::Shl: {
7629     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7630     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7631     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7632     break;
7633   }    
7634   case Instruction::Trunc:
7635   case Instruction::ZExt:
7636   case Instruction::SExt:
7637     // If the source type of the cast is the type we're trying for then we can
7638     // just return the source.  There's no need to insert it because it is not
7639     // new.
7640     if (I->getOperand(0)->getType() == Ty)
7641       return I->getOperand(0);
7642     
7643     // Otherwise, must be the same type of cast, so just reinsert a new one.
7644     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7645                            Ty);
7646     break;
7647   case Instruction::Select: {
7648     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7649     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7650     Res = SelectInst::Create(I->getOperand(0), True, False);
7651     break;
7652   }
7653   case Instruction::PHI: {
7654     PHINode *OPN = cast<PHINode>(I);
7655     PHINode *NPN = PHINode::Create(Ty);
7656     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7657       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7658       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7659     }
7660     Res = NPN;
7661     break;
7662   }
7663   default: 
7664     // TODO: Can handle more cases here.
7665     assert(0 && "Unreachable!");
7666     break;
7667   }
7668   
7669   Res->takeName(I);
7670   return InsertNewInstBefore(Res, *I);
7671 }
7672
7673 /// @brief Implement the transforms common to all CastInst visitors.
7674 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7675   Value *Src = CI.getOperand(0);
7676
7677   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7678   // eliminate it now.
7679   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7680     if (Instruction::CastOps opc = 
7681         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7682       // The first cast (CSrc) is eliminable so we need to fix up or replace
7683       // the second cast (CI). CSrc will then have a good chance of being dead.
7684       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7685     }
7686   }
7687
7688   // If we are casting a select then fold the cast into the select
7689   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7690     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7691       return NV;
7692
7693   // If we are casting a PHI then fold the cast into the PHI
7694   if (isa<PHINode>(Src))
7695     if (Instruction *NV = FoldOpIntoPhi(CI))
7696       return NV;
7697   
7698   return 0;
7699 }
7700
7701 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7702 /// or not there is a sequence of GEP indices into the type that will land us at
7703 /// the specified offset.  If so, fill them into NewIndices and return true,
7704 /// otherwise return false.
7705 static bool FindElementAtOffset(const Type *Ty, int64_t Offset, 
7706                                 SmallVectorImpl<Value*> &NewIndices,
7707                                 const TargetData *TD) {
7708   if (!Ty->isSized()) return false;
7709   
7710   // Start with the index over the outer type.  Note that the type size
7711   // might be zero (even if the offset isn't zero) if the indexed type
7712   // is something like [0 x {int, int}]
7713   const Type *IntPtrTy = TD->getIntPtrType();
7714   int64_t FirstIdx = 0;
7715   if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
7716     FirstIdx = Offset/TySize;
7717     Offset -= FirstIdx*TySize;
7718     
7719     // Handle hosts where % returns negative instead of values [0..TySize).
7720     if (Offset < 0) {
7721       --FirstIdx;
7722       Offset += TySize;
7723       assert(Offset >= 0);
7724     }
7725     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7726   }
7727   
7728   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7729     
7730   // Index into the types.  If we fail, set OrigBase to null.
7731   while (Offset) {
7732     // Indexing into tail padding between struct/array elements.
7733     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
7734       return false;
7735     
7736     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7737       const StructLayout *SL = TD->getStructLayout(STy);
7738       assert(Offset < (int64_t)SL->getSizeInBytes() &&
7739              "Offset must stay within the indexed type");
7740       
7741       unsigned Elt = SL->getElementContainingOffset(Offset);
7742       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7743       
7744       Offset -= SL->getElementOffset(Elt);
7745       Ty = STy->getElementType(Elt);
7746     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
7747       uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
7748       assert(EltSize && "Cannot index into a zero-sized array");
7749       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7750       Offset %= EltSize;
7751       Ty = AT->getElementType();
7752     } else {
7753       // Otherwise, we can't index into the middle of this atomic type, bail.
7754       return false;
7755     }
7756   }
7757   
7758   return true;
7759 }
7760
7761 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7762 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7763   Value *Src = CI.getOperand(0);
7764   
7765   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7766     // If casting the result of a getelementptr instruction with no offset, turn
7767     // this into a cast of the original pointer!
7768     if (GEP->hasAllZeroIndices()) {
7769       // Changing the cast operand is usually not a good idea but it is safe
7770       // here because the pointer operand is being replaced with another 
7771       // pointer operand so the opcode doesn't need to change.
7772       AddToWorkList(GEP);
7773       CI.setOperand(0, GEP->getOperand(0));
7774       return &CI;
7775     }
7776     
7777     // If the GEP has a single use, and the base pointer is a bitcast, and the
7778     // GEP computes a constant offset, see if we can convert these three
7779     // instructions into fewer.  This typically happens with unions and other
7780     // non-type-safe code.
7781     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7782       if (GEP->hasAllConstantIndices()) {
7783         // We are guaranteed to get a constant from EmitGEPOffset.
7784         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7785         int64_t Offset = OffsetV->getSExtValue();
7786         
7787         // Get the base pointer input of the bitcast, and the type it points to.
7788         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7789         const Type *GEPIdxTy =
7790           cast<PointerType>(OrigBase->getType())->getElementType();
7791         SmallVector<Value*, 8> NewIndices;
7792         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7793           // If we were able to index down into an element, create the GEP
7794           // and bitcast the result.  This eliminates one bitcast, potentially
7795           // two.
7796           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7797                                                         NewIndices.begin(),
7798                                                         NewIndices.end(), "");
7799           InsertNewInstBefore(NGEP, CI);
7800           NGEP->takeName(GEP);
7801           
7802           if (isa<BitCastInst>(CI))
7803             return new BitCastInst(NGEP, CI.getType());
7804           assert(isa<PtrToIntInst>(CI));
7805           return new PtrToIntInst(NGEP, CI.getType());
7806         }
7807       }      
7808     }
7809   }
7810     
7811   return commonCastTransforms(CI);
7812 }
7813
7814
7815 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7816 /// integer types. This function implements the common transforms for all those
7817 /// cases.
7818 /// @brief Implement the transforms common to CastInst with integer operands
7819 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7820   if (Instruction *Result = commonCastTransforms(CI))
7821     return Result;
7822
7823   Value *Src = CI.getOperand(0);
7824   const Type *SrcTy = Src->getType();
7825   const Type *DestTy = CI.getType();
7826   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7827   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7828
7829   // See if we can simplify any instructions used by the LHS whose sole 
7830   // purpose is to compute bits we don't care about.
7831   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7832   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7833                            KnownZero, KnownOne))
7834     return &CI;
7835
7836   // If the source isn't an instruction or has more than one use then we
7837   // can't do anything more. 
7838   Instruction *SrcI = dyn_cast<Instruction>(Src);
7839   if (!SrcI || !Src->hasOneUse())
7840     return 0;
7841
7842   // Attempt to propagate the cast into the instruction for int->int casts.
7843   int NumCastsRemoved = 0;
7844   if (!isa<BitCastInst>(CI) &&
7845       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7846                                  CI.getOpcode(), NumCastsRemoved)) {
7847     // If this cast is a truncate, evaluting in a different type always
7848     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7849     // we need to do an AND to maintain the clear top-part of the computation,
7850     // so we require that the input have eliminated at least one cast.  If this
7851     // is a sign extension, we insert two new casts (to do the extension) so we
7852     // require that two casts have been eliminated.
7853     bool DoXForm = false;
7854     bool JustReplace = false;
7855     switch (CI.getOpcode()) {
7856     default:
7857       // All the others use floating point so we shouldn't actually 
7858       // get here because of the check above.
7859       assert(0 && "Unknown cast type");
7860     case Instruction::Trunc:
7861       DoXForm = true;
7862       break;
7863     case Instruction::ZExt: {
7864       DoXForm = NumCastsRemoved >= 1;
7865       if (!DoXForm) {
7866         // If it's unnecessary to issue an AND to clear the high bits, it's
7867         // always profitable to do this xform.
7868         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, 
7869                                            CI.getOpcode() == Instruction::SExt);
7870         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7871         if (MaskedValueIsZero(TryRes, Mask))
7872           return ReplaceInstUsesWith(CI, TryRes);
7873         else if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7874           if (TryI->use_empty())
7875             EraseInstFromFunction(*TryI);
7876       }
7877       break;
7878     }
7879     case Instruction::SExt: {
7880       DoXForm = NumCastsRemoved >= 2;
7881       if (!DoXForm && !isa<TruncInst>(SrcI)) {
7882         // If we do not have to emit the truncate + sext pair, then it's always
7883         // profitable to do this xform.
7884         //
7885         // It's not safe to eliminate the trunc + sext pair if one of the
7886         // eliminated cast is a truncate. e.g.
7887         // t2 = trunc i32 t1 to i16
7888         // t3 = sext i16 t2 to i32
7889         // !=
7890         // i32 t1
7891         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, 
7892                                            CI.getOpcode() == Instruction::SExt);
7893         unsigned NumSignBits = ComputeNumSignBits(TryRes);
7894         if (NumSignBits > (DestBitSize - SrcBitSize))
7895           return ReplaceInstUsesWith(CI, TryRes);
7896         else if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7897           if (TryI->use_empty())
7898             EraseInstFromFunction(*TryI);
7899       }
7900       break;
7901     }
7902     }
7903     
7904     if (DoXForm) {
7905       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7906                                            CI.getOpcode() == Instruction::SExt);
7907       if (JustReplace)
7908           // Just replace this cast with the result.
7909           return ReplaceInstUsesWith(CI, Res);
7910
7911       assert(Res->getType() == DestTy);
7912       switch (CI.getOpcode()) {
7913       default: assert(0 && "Unknown cast type!");
7914       case Instruction::Trunc:
7915       case Instruction::BitCast:
7916         // Just replace this cast with the result.
7917         return ReplaceInstUsesWith(CI, Res);
7918       case Instruction::ZExt: {
7919         assert(SrcBitSize < DestBitSize && "Not a zext?");
7920
7921         // If the high bits are already zero, just replace this cast with the
7922         // result.
7923         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7924         if (MaskedValueIsZero(Res, Mask))
7925           return ReplaceInstUsesWith(CI, Res);
7926
7927         // We need to emit an AND to clear the high bits.
7928         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7929                                                             SrcBitSize));
7930         return BinaryOperator::CreateAnd(Res, C);
7931       }
7932       case Instruction::SExt: {
7933         // If the high bits are already filled with sign bit, just replace this
7934         // cast with the result.
7935         unsigned NumSignBits = ComputeNumSignBits(Res);
7936         if (NumSignBits > (DestBitSize - SrcBitSize))
7937           return ReplaceInstUsesWith(CI, Res);
7938
7939         // We need to emit a cast to truncate, then a cast to sext.
7940         return CastInst::Create(Instruction::SExt,
7941             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7942                              CI), DestTy);
7943       }
7944       }
7945     }
7946   }
7947   
7948   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7949   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7950
7951   switch (SrcI->getOpcode()) {
7952   case Instruction::Add:
7953   case Instruction::Mul:
7954   case Instruction::And:
7955   case Instruction::Or:
7956   case Instruction::Xor:
7957     // If we are discarding information, rewrite.
7958     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7959       // Don't insert two casts if they cannot be eliminated.  We allow 
7960       // two casts to be inserted if the sizes are the same.  This could 
7961       // only be converting signedness, which is a noop.
7962       if (DestBitSize == SrcBitSize || 
7963           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7964           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7965         Instruction::CastOps opcode = CI.getOpcode();
7966         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7967         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
7968         return BinaryOperator::Create(
7969             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7970       }
7971     }
7972
7973     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7974     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7975         SrcI->getOpcode() == Instruction::Xor &&
7976         Op1 == ConstantInt::getTrue() &&
7977         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7978       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
7979       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7980     }
7981     break;
7982   case Instruction::SDiv:
7983   case Instruction::UDiv:
7984   case Instruction::SRem:
7985   case Instruction::URem:
7986     // If we are just changing the sign, rewrite.
7987     if (DestBitSize == SrcBitSize) {
7988       // Don't insert two casts if they cannot be eliminated.  We allow 
7989       // two casts to be inserted if the sizes are the same.  This could 
7990       // only be converting signedness, which is a noop.
7991       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7992           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7993         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
7994                                        Op0, DestTy, *SrcI);
7995         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
7996                                        Op1, DestTy, *SrcI);
7997         return BinaryOperator::Create(
7998           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7999       }
8000     }
8001     break;
8002
8003   case Instruction::Shl:
8004     // Allow changing the sign of the source operand.  Do not allow 
8005     // changing the size of the shift, UNLESS the shift amount is a 
8006     // constant.  We must not change variable sized shifts to a smaller 
8007     // size, because it is undefined to shift more bits out than exist 
8008     // in the value.
8009     if (DestBitSize == SrcBitSize ||
8010         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8011       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8012           Instruction::BitCast : Instruction::Trunc);
8013       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8014       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8015       return BinaryOperator::CreateShl(Op0c, Op1c);
8016     }
8017     break;
8018   case Instruction::AShr:
8019     // If this is a signed shr, and if all bits shifted in are about to be
8020     // truncated off, turn it into an unsigned shr to allow greater
8021     // simplifications.
8022     if (DestBitSize < SrcBitSize &&
8023         isa<ConstantInt>(Op1)) {
8024       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8025       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8026         // Insert the new logical shift right.
8027         return BinaryOperator::CreateLShr(Op0, Op1);
8028       }
8029     }
8030     break;
8031   }
8032   return 0;
8033 }
8034
8035 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8036   if (Instruction *Result = commonIntCastTransforms(CI))
8037     return Result;
8038   
8039   Value *Src = CI.getOperand(0);
8040   const Type *Ty = CI.getType();
8041   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8042   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
8043   
8044   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
8045     switch (SrcI->getOpcode()) {
8046     default: break;
8047     case Instruction::LShr:
8048       // We can shrink lshr to something smaller if we know the bits shifted in
8049       // are already zeros.
8050       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
8051         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8052         
8053         // Get a mask for the bits shifting in.
8054         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8055         Value* SrcIOp0 = SrcI->getOperand(0);
8056         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
8057           if (ShAmt >= DestBitWidth)        // All zeros.
8058             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8059
8060           // Okay, we can shrink this.  Truncate the input, then return a new
8061           // shift.
8062           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
8063           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
8064                                        Ty, CI);
8065           return BinaryOperator::CreateLShr(V1, V2);
8066         }
8067       } else {     // This is a variable shr.
8068         
8069         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
8070         // more LLVM instructions, but allows '1 << Y' to be hoisted if
8071         // loop-invariant and CSE'd.
8072         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
8073           Value *One = ConstantInt::get(SrcI->getType(), 1);
8074
8075           Value *V = InsertNewInstBefore(
8076               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
8077                                      "tmp"), CI);
8078           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
8079                                                             SrcI->getOperand(0),
8080                                                             "tmp"), CI);
8081           Value *Zero = Constant::getNullValue(V->getType());
8082           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
8083         }
8084       }
8085       break;
8086     }
8087   }
8088   
8089   return 0;
8090 }
8091
8092 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8093 /// in order to eliminate the icmp.
8094 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8095                                              bool DoXform) {
8096   // If we are just checking for a icmp eq of a single bit and zext'ing it
8097   // to an integer, then shift the bit to the appropriate place and then
8098   // cast to integer to avoid the comparison.
8099   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8100     const APInt &Op1CV = Op1C->getValue();
8101       
8102     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8103     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8104     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8105         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8106       if (!DoXform) return ICI;
8107
8108       Value *In = ICI->getOperand(0);
8109       Value *Sh = ConstantInt::get(In->getType(),
8110                                    In->getType()->getPrimitiveSizeInBits()-1);
8111       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8112                                                         In->getName()+".lobit"),
8113                                CI);
8114       if (In->getType() != CI.getType())
8115         In = CastInst::CreateIntegerCast(In, CI.getType(),
8116                                          false/*ZExt*/, "tmp", &CI);
8117
8118       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8119         Constant *One = ConstantInt::get(In->getType(), 1);
8120         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8121                                                          In->getName()+".not"),
8122                                  CI);
8123       }
8124
8125       return ReplaceInstUsesWith(CI, In);
8126     }
8127       
8128       
8129       
8130     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8131     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8132     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8133     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8134     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8135     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8136     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8137     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8138     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8139         // This only works for EQ and NE
8140         ICI->isEquality()) {
8141       // If Op1C some other power of two, convert:
8142       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8143       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8144       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8145       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8146         
8147       APInt KnownZeroMask(~KnownZero);
8148       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8149         if (!DoXform) return ICI;
8150
8151         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8152         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8153           // (X&4) == 2 --> false
8154           // (X&4) != 2 --> true
8155           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8156           Res = ConstantExpr::getZExt(Res, CI.getType());
8157           return ReplaceInstUsesWith(CI, Res);
8158         }
8159           
8160         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8161         Value *In = ICI->getOperand(0);
8162         if (ShiftAmt) {
8163           // Perform a logical shr by shiftamt.
8164           // Insert the shift to put the result in the low bit.
8165           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8166                                   ConstantInt::get(In->getType(), ShiftAmt),
8167                                                    In->getName()+".lobit"), CI);
8168         }
8169           
8170         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8171           Constant *One = ConstantInt::get(In->getType(), 1);
8172           In = BinaryOperator::CreateXor(In, One, "tmp");
8173           InsertNewInstBefore(cast<Instruction>(In), CI);
8174         }
8175           
8176         if (CI.getType() == In->getType())
8177           return ReplaceInstUsesWith(CI, In);
8178         else
8179           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8180       }
8181     }
8182   }
8183
8184   return 0;
8185 }
8186
8187 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8188   // If one of the common conversion will work ..
8189   if (Instruction *Result = commonIntCastTransforms(CI))
8190     return Result;
8191
8192   Value *Src = CI.getOperand(0);
8193
8194   // If this is a cast of a cast
8195   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8196     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8197     // types and if the sizes are just right we can convert this into a logical
8198     // 'and' which will be much cheaper than the pair of casts.
8199     if (isa<TruncInst>(CSrc)) {
8200       // Get the sizes of the types involved
8201       Value *A = CSrc->getOperand(0);
8202       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8203       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8204       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8205       // If we're actually extending zero bits and the trunc is a no-op
8206       if (MidSize < DstSize && SrcSize == DstSize) {
8207         // Replace both of the casts with an And of the type mask.
8208         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8209         Constant *AndConst = ConstantInt::get(AndValue);
8210         Instruction *And = 
8211           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8212         // Unfortunately, if the type changed, we need to cast it back.
8213         if (And->getType() != CI.getType()) {
8214           And->setName(CSrc->getName()+".mask");
8215           InsertNewInstBefore(And, CI);
8216           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8217         }
8218         return And;
8219       }
8220     }
8221   }
8222
8223   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8224     return transformZExtICmp(ICI, CI);
8225
8226   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8227   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8228     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8229     // of the (zext icmp) will be transformed.
8230     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8231     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8232     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8233         (transformZExtICmp(LHS, CI, false) ||
8234          transformZExtICmp(RHS, CI, false))) {
8235       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8236       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8237       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8238     }
8239   }
8240
8241   return 0;
8242 }
8243
8244 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8245   if (Instruction *I = commonIntCastTransforms(CI))
8246     return I;
8247   
8248   Value *Src = CI.getOperand(0);
8249   
8250   // Canonicalize sign-extend from i1 to a select.
8251   if (Src->getType() == Type::Int1Ty)
8252     return SelectInst::Create(Src,
8253                               ConstantInt::getAllOnesValue(CI.getType()),
8254                               Constant::getNullValue(CI.getType()));
8255
8256   // See if the value being truncated is already sign extended.  If so, just
8257   // eliminate the trunc/sext pair.
8258   if (getOpcode(Src) == Instruction::Trunc) {
8259     Value *Op = cast<User>(Src)->getOperand(0);
8260     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8261     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8262     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8263     unsigned NumSignBits = ComputeNumSignBits(Op);
8264
8265     if (OpBits == DestBits) {
8266       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8267       // bits, it is already ready.
8268       if (NumSignBits > DestBits-MidBits)
8269         return ReplaceInstUsesWith(CI, Op);
8270     } else if (OpBits < DestBits) {
8271       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8272       // bits, just sext from i32.
8273       if (NumSignBits > OpBits-MidBits)
8274         return new SExtInst(Op, CI.getType(), "tmp");
8275     } else {
8276       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8277       // bits, just truncate to i32.
8278       if (NumSignBits > OpBits-MidBits)
8279         return new TruncInst(Op, CI.getType(), "tmp");
8280     }
8281   }
8282
8283   // If the input is a shl/ashr pair of a same constant, then this is a sign
8284   // extension from a smaller value.  If we could trust arbitrary bitwidth
8285   // integers, we could turn this into a truncate to the smaller bit and then
8286   // use a sext for the whole extension.  Since we don't, look deeper and check
8287   // for a truncate.  If the source and dest are the same type, eliminate the
8288   // trunc and extend and just do shifts.  For example, turn:
8289   //   %a = trunc i32 %i to i8
8290   //   %b = shl i8 %a, 6
8291   //   %c = ashr i8 %b, 6
8292   //   %d = sext i8 %c to i32
8293   // into:
8294   //   %a = shl i32 %i, 30
8295   //   %d = ashr i32 %a, 30
8296   Value *A = 0;
8297   ConstantInt *BA = 0, *CA = 0;
8298   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8299                         m_ConstantInt(CA))) &&
8300       BA == CA && isa<TruncInst>(A)) {
8301     Value *I = cast<TruncInst>(A)->getOperand(0);
8302     if (I->getType() == CI.getType()) {
8303       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8304       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8305       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8306       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8307       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8308                                                         CI.getName()), CI);
8309       return BinaryOperator::CreateAShr(I, ShAmtV);
8310     }
8311   }
8312   
8313   return 0;
8314 }
8315
8316 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8317 /// in the specified FP type without changing its value.
8318 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8319   bool losesInfo;
8320   APFloat F = CFP->getValueAPF();
8321   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8322   if (!losesInfo)
8323     return ConstantFP::get(F);
8324   return 0;
8325 }
8326
8327 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8328 /// through it until we get the source value.
8329 static Value *LookThroughFPExtensions(Value *V) {
8330   if (Instruction *I = dyn_cast<Instruction>(V))
8331     if (I->getOpcode() == Instruction::FPExt)
8332       return LookThroughFPExtensions(I->getOperand(0));
8333   
8334   // If this value is a constant, return the constant in the smallest FP type
8335   // that can accurately represent it.  This allows us to turn
8336   // (float)((double)X+2.0) into x+2.0f.
8337   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8338     if (CFP->getType() == Type::PPC_FP128Ty)
8339       return V;  // No constant folding of this.
8340     // See if the value can be truncated to float and then reextended.
8341     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8342       return V;
8343     if (CFP->getType() == Type::DoubleTy)
8344       return V;  // Won't shrink.
8345     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8346       return V;
8347     // Don't try to shrink to various long double types.
8348   }
8349   
8350   return V;
8351 }
8352
8353 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8354   if (Instruction *I = commonCastTransforms(CI))
8355     return I;
8356   
8357   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8358   // smaller than the destination type, we can eliminate the truncate by doing
8359   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8360   // many builtins (sqrt, etc).
8361   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8362   if (OpI && OpI->hasOneUse()) {
8363     switch (OpI->getOpcode()) {
8364     default: break;
8365     case Instruction::Add:
8366     case Instruction::Sub:
8367     case Instruction::Mul:
8368     case Instruction::FDiv:
8369     case Instruction::FRem:
8370       const Type *SrcTy = OpI->getType();
8371       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8372       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8373       if (LHSTrunc->getType() != SrcTy && 
8374           RHSTrunc->getType() != SrcTy) {
8375         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8376         // If the source types were both smaller than the destination type of
8377         // the cast, do this xform.
8378         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8379             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8380           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8381                                       CI.getType(), CI);
8382           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8383                                       CI.getType(), CI);
8384           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8385         }
8386       }
8387       break;  
8388     }
8389   }
8390   return 0;
8391 }
8392
8393 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8394   return commonCastTransforms(CI);
8395 }
8396
8397 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8398   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8399   if (OpI == 0)
8400     return commonCastTransforms(FI);
8401
8402   // fptoui(uitofp(X)) --> X
8403   // fptoui(sitofp(X)) --> X
8404   // This is safe if the intermediate type has enough bits in its mantissa to
8405   // accurately represent all values of X.  For example, do not do this with
8406   // i64->float->i64.  This is also safe for sitofp case, because any negative
8407   // 'X' value would cause an undefined result for the fptoui. 
8408   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8409       OpI->getOperand(0)->getType() == FI.getType() &&
8410       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8411                     OpI->getType()->getFPMantissaWidth())
8412     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8413
8414   return commonCastTransforms(FI);
8415 }
8416
8417 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8418   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8419   if (OpI == 0)
8420     return commonCastTransforms(FI);
8421   
8422   // fptosi(sitofp(X)) --> X
8423   // fptosi(uitofp(X)) --> X
8424   // This is safe if the intermediate type has enough bits in its mantissa to
8425   // accurately represent all values of X.  For example, do not do this with
8426   // i64->float->i64.  This is also safe for sitofp case, because any negative
8427   // 'X' value would cause an undefined result for the fptoui. 
8428   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8429       OpI->getOperand(0)->getType() == FI.getType() &&
8430       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8431                     OpI->getType()->getFPMantissaWidth())
8432     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8433   
8434   return commonCastTransforms(FI);
8435 }
8436
8437 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8438   return commonCastTransforms(CI);
8439 }
8440
8441 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8442   return commonCastTransforms(CI);
8443 }
8444
8445 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8446   return commonPointerCastTransforms(CI);
8447 }
8448
8449 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8450   if (Instruction *I = commonCastTransforms(CI))
8451     return I;
8452   
8453   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8454   if (!DestPointee->isSized()) return 0;
8455
8456   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8457   ConstantInt *Cst;
8458   Value *X;
8459   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8460                                     m_ConstantInt(Cst)))) {
8461     // If the source and destination operands have the same type, see if this
8462     // is a single-index GEP.
8463     if (X->getType() == CI.getType()) {
8464       // Get the size of the pointee type.
8465       uint64_t Size = TD->getTypePaddedSize(DestPointee);
8466
8467       // Convert the constant to intptr type.
8468       APInt Offset = Cst->getValue();
8469       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8470
8471       // If Offset is evenly divisible by Size, we can do this xform.
8472       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8473         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8474         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8475       }
8476     }
8477     // TODO: Could handle other cases, e.g. where add is indexing into field of
8478     // struct etc.
8479   } else if (CI.getOperand(0)->hasOneUse() &&
8480              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8481     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8482     // "inttoptr+GEP" instead of "add+intptr".
8483     
8484     // Get the size of the pointee type.
8485     uint64_t Size = TD->getTypePaddedSize(DestPointee);
8486     
8487     // Convert the constant to intptr type.
8488     APInt Offset = Cst->getValue();
8489     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8490     
8491     // If Offset is evenly divisible by Size, we can do this xform.
8492     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8493       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8494       
8495       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8496                                                             "tmp"), CI);
8497       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8498     }
8499   }
8500   return 0;
8501 }
8502
8503 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8504   // If the operands are integer typed then apply the integer transforms,
8505   // otherwise just apply the common ones.
8506   Value *Src = CI.getOperand(0);
8507   const Type *SrcTy = Src->getType();
8508   const Type *DestTy = CI.getType();
8509
8510   if (SrcTy->isInteger() && DestTy->isInteger()) {
8511     if (Instruction *Result = commonIntCastTransforms(CI))
8512       return Result;
8513   } else if (isa<PointerType>(SrcTy)) {
8514     if (Instruction *I = commonPointerCastTransforms(CI))
8515       return I;
8516   } else {
8517     if (Instruction *Result = commonCastTransforms(CI))
8518       return Result;
8519   }
8520
8521
8522   // Get rid of casts from one type to the same type. These are useless and can
8523   // be replaced by the operand.
8524   if (DestTy == Src->getType())
8525     return ReplaceInstUsesWith(CI, Src);
8526
8527   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8528     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8529     const Type *DstElTy = DstPTy->getElementType();
8530     const Type *SrcElTy = SrcPTy->getElementType();
8531     
8532     // If the address spaces don't match, don't eliminate the bitcast, which is
8533     // required for changing types.
8534     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8535       return 0;
8536     
8537     // If we are casting a malloc or alloca to a pointer to a type of the same
8538     // size, rewrite the allocation instruction to allocate the "right" type.
8539     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8540       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8541         return V;
8542     
8543     // If the source and destination are pointers, and this cast is equivalent
8544     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8545     // This can enhance SROA and other transforms that want type-safe pointers.
8546     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8547     unsigned NumZeros = 0;
8548     while (SrcElTy != DstElTy && 
8549            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8550            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8551       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8552       ++NumZeros;
8553     }
8554
8555     // If we found a path from the src to dest, create the getelementptr now.
8556     if (SrcElTy == DstElTy) {
8557       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8558       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8559                                        ((Instruction*) NULL));
8560     }
8561   }
8562
8563   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8564     if (SVI->hasOneUse()) {
8565       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8566       // a bitconvert to a vector with the same # elts.
8567       if (isa<VectorType>(DestTy) && 
8568           cast<VectorType>(DestTy)->getNumElements() ==
8569                 SVI->getType()->getNumElements() &&
8570           SVI->getType()->getNumElements() ==
8571             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8572         CastInst *Tmp;
8573         // If either of the operands is a cast from CI.getType(), then
8574         // evaluating the shuffle in the casted destination's type will allow
8575         // us to eliminate at least one cast.
8576         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8577              Tmp->getOperand(0)->getType() == DestTy) ||
8578             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8579              Tmp->getOperand(0)->getType() == DestTy)) {
8580           Value *LHS = InsertCastBefore(Instruction::BitCast,
8581                                         SVI->getOperand(0), DestTy, CI);
8582           Value *RHS = InsertCastBefore(Instruction::BitCast,
8583                                         SVI->getOperand(1), DestTy, CI);
8584           // Return a new shuffle vector.  Use the same element ID's, as we
8585           // know the vector types match #elts.
8586           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8587         }
8588       }
8589     }
8590   }
8591   return 0;
8592 }
8593
8594 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8595 ///   %C = or %A, %B
8596 ///   %D = select %cond, %C, %A
8597 /// into:
8598 ///   %C = select %cond, %B, 0
8599 ///   %D = or %A, %C
8600 ///
8601 /// Assuming that the specified instruction is an operand to the select, return
8602 /// a bitmask indicating which operands of this instruction are foldable if they
8603 /// equal the other incoming value of the select.
8604 ///
8605 static unsigned GetSelectFoldableOperands(Instruction *I) {
8606   switch (I->getOpcode()) {
8607   case Instruction::Add:
8608   case Instruction::Mul:
8609   case Instruction::And:
8610   case Instruction::Or:
8611   case Instruction::Xor:
8612     return 3;              // Can fold through either operand.
8613   case Instruction::Sub:   // Can only fold on the amount subtracted.
8614   case Instruction::Shl:   // Can only fold on the shift amount.
8615   case Instruction::LShr:
8616   case Instruction::AShr:
8617     return 1;
8618   default:
8619     return 0;              // Cannot fold
8620   }
8621 }
8622
8623 /// GetSelectFoldableConstant - For the same transformation as the previous
8624 /// function, return the identity constant that goes into the select.
8625 static Constant *GetSelectFoldableConstant(Instruction *I) {
8626   switch (I->getOpcode()) {
8627   default: assert(0 && "This cannot happen!"); abort();
8628   case Instruction::Add:
8629   case Instruction::Sub:
8630   case Instruction::Or:
8631   case Instruction::Xor:
8632   case Instruction::Shl:
8633   case Instruction::LShr:
8634   case Instruction::AShr:
8635     return Constant::getNullValue(I->getType());
8636   case Instruction::And:
8637     return Constant::getAllOnesValue(I->getType());
8638   case Instruction::Mul:
8639     return ConstantInt::get(I->getType(), 1);
8640   }
8641 }
8642
8643 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8644 /// have the same opcode and only one use each.  Try to simplify this.
8645 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8646                                           Instruction *FI) {
8647   if (TI->getNumOperands() == 1) {
8648     // If this is a non-volatile load or a cast from the same type,
8649     // merge.
8650     if (TI->isCast()) {
8651       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8652         return 0;
8653     } else {
8654       return 0;  // unknown unary op.
8655     }
8656
8657     // Fold this by inserting a select from the input values.
8658     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8659                                            FI->getOperand(0), SI.getName()+".v");
8660     InsertNewInstBefore(NewSI, SI);
8661     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8662                             TI->getType());
8663   }
8664
8665   // Only handle binary operators here.
8666   if (!isa<BinaryOperator>(TI))
8667     return 0;
8668
8669   // Figure out if the operations have any operands in common.
8670   Value *MatchOp, *OtherOpT, *OtherOpF;
8671   bool MatchIsOpZero;
8672   if (TI->getOperand(0) == FI->getOperand(0)) {
8673     MatchOp  = TI->getOperand(0);
8674     OtherOpT = TI->getOperand(1);
8675     OtherOpF = FI->getOperand(1);
8676     MatchIsOpZero = true;
8677   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8678     MatchOp  = TI->getOperand(1);
8679     OtherOpT = TI->getOperand(0);
8680     OtherOpF = FI->getOperand(0);
8681     MatchIsOpZero = false;
8682   } else if (!TI->isCommutative()) {
8683     return 0;
8684   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8685     MatchOp  = TI->getOperand(0);
8686     OtherOpT = TI->getOperand(1);
8687     OtherOpF = FI->getOperand(0);
8688     MatchIsOpZero = true;
8689   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8690     MatchOp  = TI->getOperand(1);
8691     OtherOpT = TI->getOperand(0);
8692     OtherOpF = FI->getOperand(1);
8693     MatchIsOpZero = true;
8694   } else {
8695     return 0;
8696   }
8697
8698   // If we reach here, they do have operations in common.
8699   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8700                                          OtherOpF, SI.getName()+".v");
8701   InsertNewInstBefore(NewSI, SI);
8702
8703   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8704     if (MatchIsOpZero)
8705       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8706     else
8707       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8708   }
8709   assert(0 && "Shouldn't get here");
8710   return 0;
8711 }
8712
8713 /// visitSelectInstWithICmp - Visit a SelectInst that has an
8714 /// ICmpInst as its first operand.
8715 ///
8716 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8717                                                    ICmpInst *ICI) {
8718   bool Changed = false;
8719   ICmpInst::Predicate Pred = ICI->getPredicate();
8720   Value *CmpLHS = ICI->getOperand(0);
8721   Value *CmpRHS = ICI->getOperand(1);
8722   Value *TrueVal = SI.getTrueValue();
8723   Value *FalseVal = SI.getFalseValue();
8724
8725   // Check cases where the comparison is with a constant that
8726   // can be adjusted to fit the min/max idiom. We may edit ICI in
8727   // place here, so make sure the select is the only user.
8728   if (ICI->hasOneUse())
8729     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
8730       switch (Pred) {
8731       default: break;
8732       case ICmpInst::ICMP_ULT:
8733       case ICmpInst::ICMP_SLT: {
8734         // X < MIN ? T : F  -->  F
8735         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8736           return ReplaceInstUsesWith(SI, FalseVal);
8737         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
8738         Constant *AdjustedRHS = SubOne(CI);
8739         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8740             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8741           Pred = ICmpInst::getSwappedPredicate(Pred);
8742           CmpRHS = AdjustedRHS;
8743           std::swap(FalseVal, TrueVal);
8744           ICI->setPredicate(Pred);
8745           ICI->setOperand(1, CmpRHS);
8746           SI.setOperand(1, TrueVal);
8747           SI.setOperand(2, FalseVal);
8748           Changed = true;
8749         }
8750         break;
8751       }
8752       case ICmpInst::ICMP_UGT:
8753       case ICmpInst::ICMP_SGT: {
8754         // X > MAX ? T : F  -->  F
8755         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8756           return ReplaceInstUsesWith(SI, FalseVal);
8757         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
8758         Constant *AdjustedRHS = AddOne(CI);
8759         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8760             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8761           Pred = ICmpInst::getSwappedPredicate(Pred);
8762           CmpRHS = AdjustedRHS;
8763           std::swap(FalseVal, TrueVal);
8764           ICI->setPredicate(Pred);
8765           ICI->setOperand(1, CmpRHS);
8766           SI.setOperand(1, TrueVal);
8767           SI.setOperand(2, FalseVal);
8768           Changed = true;
8769         }
8770         break;
8771       }
8772       }
8773
8774       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
8775       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
8776       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
8777       if (match(TrueVal, m_ConstantInt<-1>()) &&
8778           match(FalseVal, m_ConstantInt<0>()))
8779         Pred = ICI->getPredicate();
8780       else if (match(TrueVal, m_ConstantInt<0>()) &&
8781                match(FalseVal, m_ConstantInt<-1>()))
8782         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8783       
8784       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8785         // If we are just checking for a icmp eq of a single bit and zext'ing it
8786         // to an integer, then shift the bit to the appropriate place and then
8787         // cast to integer to avoid the comparison.
8788         const APInt &Op1CV = CI->getValue();
8789     
8790         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
8791         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
8792         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8793             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
8794           Value *In = ICI->getOperand(0);
8795           Value *Sh = ConstantInt::get(In->getType(),
8796                                        In->getType()->getPrimitiveSizeInBits()-1);
8797           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8798                                                           In->getName()+".lobit"),
8799                                    *ICI);
8800           if (In->getType() != SI.getType())
8801             In = CastInst::CreateIntegerCast(In, SI.getType(),
8802                                              true/*SExt*/, "tmp", ICI);
8803     
8804           if (Pred == ICmpInst::ICMP_SGT)
8805             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8806                                        In->getName()+".not"), *ICI);
8807     
8808           return ReplaceInstUsesWith(SI, In);
8809         }
8810       }
8811     }
8812
8813   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8814     // Transform (X == Y) ? X : Y  -> Y
8815     if (Pred == ICmpInst::ICMP_EQ)
8816       return ReplaceInstUsesWith(SI, FalseVal);
8817     // Transform (X != Y) ? X : Y  -> X
8818     if (Pred == ICmpInst::ICMP_NE)
8819       return ReplaceInstUsesWith(SI, TrueVal);
8820     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8821
8822   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8823     // Transform (X == Y) ? Y : X  -> X
8824     if (Pred == ICmpInst::ICMP_EQ)
8825       return ReplaceInstUsesWith(SI, FalseVal);
8826     // Transform (X != Y) ? Y : X  -> Y
8827     if (Pred == ICmpInst::ICMP_NE)
8828       return ReplaceInstUsesWith(SI, TrueVal);
8829     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8830   }
8831
8832   /// NOTE: if we wanted to, this is where to detect integer ABS
8833
8834   return Changed ? &SI : 0;
8835 }
8836
8837 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8838   Value *CondVal = SI.getCondition();
8839   Value *TrueVal = SI.getTrueValue();
8840   Value *FalseVal = SI.getFalseValue();
8841
8842   // select true, X, Y  -> X
8843   // select false, X, Y -> Y
8844   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8845     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8846
8847   // select C, X, X -> X
8848   if (TrueVal == FalseVal)
8849     return ReplaceInstUsesWith(SI, TrueVal);
8850
8851   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8852     return ReplaceInstUsesWith(SI, FalseVal);
8853   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8854     return ReplaceInstUsesWith(SI, TrueVal);
8855   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8856     if (isa<Constant>(TrueVal))
8857       return ReplaceInstUsesWith(SI, TrueVal);
8858     else
8859       return ReplaceInstUsesWith(SI, FalseVal);
8860   }
8861
8862   if (SI.getType() == Type::Int1Ty) {
8863     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8864       if (C->getZExtValue()) {
8865         // Change: A = select B, true, C --> A = or B, C
8866         return BinaryOperator::CreateOr(CondVal, FalseVal);
8867       } else {
8868         // Change: A = select B, false, C --> A = and !B, C
8869         Value *NotCond =
8870           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8871                                              "not."+CondVal->getName()), SI);
8872         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8873       }
8874     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8875       if (C->getZExtValue() == false) {
8876         // Change: A = select B, C, false --> A = and B, C
8877         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8878       } else {
8879         // Change: A = select B, C, true --> A = or !B, C
8880         Value *NotCond =
8881           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8882                                              "not."+CondVal->getName()), SI);
8883         return BinaryOperator::CreateOr(NotCond, TrueVal);
8884       }
8885     }
8886     
8887     // select a, b, a  -> a&b
8888     // select a, a, b  -> a|b
8889     if (CondVal == TrueVal)
8890       return BinaryOperator::CreateOr(CondVal, FalseVal);
8891     else if (CondVal == FalseVal)
8892       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8893   }
8894
8895   // Selecting between two integer constants?
8896   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8897     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8898       // select C, 1, 0 -> zext C to int
8899       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8900         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8901       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8902         // select C, 0, 1 -> zext !C to int
8903         Value *NotCond =
8904           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8905                                                "not."+CondVal->getName()), SI);
8906         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8907       }
8908
8909       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8910
8911         // (x <s 0) ? -1 : 0 -> ashr x, 31
8912         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8913           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8914             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8915               // The comparison constant and the result are not neccessarily the
8916               // same width. Make an all-ones value by inserting a AShr.
8917               Value *X = IC->getOperand(0);
8918               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8919               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8920               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8921                                                         ShAmt, "ones");
8922               InsertNewInstBefore(SRA, SI);
8923
8924               // Then cast to the appropriate width.
8925               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
8926             }
8927           }
8928
8929
8930         // If one of the constants is zero (we know they can't both be) and we
8931         // have an icmp instruction with zero, and we have an 'and' with the
8932         // non-constant value, eliminate this whole mess.  This corresponds to
8933         // cases like this: ((X & 27) ? 27 : 0)
8934         if (TrueValC->isZero() || FalseValC->isZero())
8935           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8936               cast<Constant>(IC->getOperand(1))->isNullValue())
8937             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8938               if (ICA->getOpcode() == Instruction::And &&
8939                   isa<ConstantInt>(ICA->getOperand(1)) &&
8940                   (ICA->getOperand(1) == TrueValC ||
8941                    ICA->getOperand(1) == FalseValC) &&
8942                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8943                 // Okay, now we know that everything is set up, we just don't
8944                 // know whether we have a icmp_ne or icmp_eq and whether the 
8945                 // true or false val is the zero.
8946                 bool ShouldNotVal = !TrueValC->isZero();
8947                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8948                 Value *V = ICA;
8949                 if (ShouldNotVal)
8950                   V = InsertNewInstBefore(BinaryOperator::Create(
8951                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8952                 return ReplaceInstUsesWith(SI, V);
8953               }
8954       }
8955     }
8956
8957   // See if we are selecting two values based on a comparison of the two values.
8958   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8959     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8960       // Transform (X == Y) ? X : Y  -> Y
8961       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8962         // This is not safe in general for floating point:  
8963         // consider X== -0, Y== +0.
8964         // It becomes safe if either operand is a nonzero constant.
8965         ConstantFP *CFPt, *CFPf;
8966         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8967               !CFPt->getValueAPF().isZero()) ||
8968             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8969              !CFPf->getValueAPF().isZero()))
8970         return ReplaceInstUsesWith(SI, FalseVal);
8971       }
8972       // Transform (X != Y) ? X : Y  -> X
8973       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8974         return ReplaceInstUsesWith(SI, TrueVal);
8975       // NOTE: if we wanted to, this is where to detect MIN/MAX
8976
8977     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8978       // Transform (X == Y) ? Y : X  -> X
8979       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8980         // This is not safe in general for floating point:  
8981         // consider X== -0, Y== +0.
8982         // It becomes safe if either operand is a nonzero constant.
8983         ConstantFP *CFPt, *CFPf;
8984         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8985               !CFPt->getValueAPF().isZero()) ||
8986             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8987              !CFPf->getValueAPF().isZero()))
8988           return ReplaceInstUsesWith(SI, FalseVal);
8989       }
8990       // Transform (X != Y) ? Y : X  -> Y
8991       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8992         return ReplaceInstUsesWith(SI, TrueVal);
8993       // NOTE: if we wanted to, this is where to detect MIN/MAX
8994     }
8995     // NOTE: if we wanted to, this is where to detect ABS
8996   }
8997
8998   // See if we are selecting two values based on a comparison of the two values.
8999   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9000     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9001       return Result;
9002
9003   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9004     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9005       if (TI->hasOneUse() && FI->hasOneUse()) {
9006         Instruction *AddOp = 0, *SubOp = 0;
9007
9008         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9009         if (TI->getOpcode() == FI->getOpcode())
9010           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9011             return IV;
9012
9013         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9014         // even legal for FP.
9015         if (TI->getOpcode() == Instruction::Sub &&
9016             FI->getOpcode() == Instruction::Add) {
9017           AddOp = FI; SubOp = TI;
9018         } else if (FI->getOpcode() == Instruction::Sub &&
9019                    TI->getOpcode() == Instruction::Add) {
9020           AddOp = TI; SubOp = FI;
9021         }
9022
9023         if (AddOp) {
9024           Value *OtherAddOp = 0;
9025           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9026             OtherAddOp = AddOp->getOperand(1);
9027           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9028             OtherAddOp = AddOp->getOperand(0);
9029           }
9030
9031           if (OtherAddOp) {
9032             // So at this point we know we have (Y -> OtherAddOp):
9033             //        select C, (add X, Y), (sub X, Z)
9034             Value *NegVal;  // Compute -Z
9035             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9036               NegVal = ConstantExpr::getNeg(C);
9037             } else {
9038               NegVal = InsertNewInstBefore(
9039                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9040             }
9041
9042             Value *NewTrueOp = OtherAddOp;
9043             Value *NewFalseOp = NegVal;
9044             if (AddOp != TI)
9045               std::swap(NewTrueOp, NewFalseOp);
9046             Instruction *NewSel =
9047               SelectInst::Create(CondVal, NewTrueOp,
9048                                  NewFalseOp, SI.getName() + ".p");
9049
9050             NewSel = InsertNewInstBefore(NewSel, SI);
9051             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9052           }
9053         }
9054       }
9055
9056   // See if we can fold the select into one of our operands.
9057   if (SI.getType()->isInteger()) {
9058     // See the comment above GetSelectFoldableOperands for a description of the
9059     // transformation we are doing here.
9060     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9061       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9062           !isa<Constant>(FalseVal))
9063         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9064           unsigned OpToFold = 0;
9065           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9066             OpToFold = 1;
9067           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9068             OpToFold = 2;
9069           }
9070
9071           if (OpToFold) {
9072             Constant *C = GetSelectFoldableConstant(TVI);
9073             Instruction *NewSel =
9074               SelectInst::Create(SI.getCondition(),
9075                                  TVI->getOperand(2-OpToFold), C);
9076             InsertNewInstBefore(NewSel, SI);
9077             NewSel->takeName(TVI);
9078             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9079               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9080             else {
9081               assert(0 && "Unknown instruction!!");
9082             }
9083           }
9084         }
9085
9086     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9087       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9088           !isa<Constant>(TrueVal))
9089         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9090           unsigned OpToFold = 0;
9091           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9092             OpToFold = 1;
9093           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9094             OpToFold = 2;
9095           }
9096
9097           if (OpToFold) {
9098             Constant *C = GetSelectFoldableConstant(FVI);
9099             Instruction *NewSel =
9100               SelectInst::Create(SI.getCondition(), C,
9101                                  FVI->getOperand(2-OpToFold));
9102             InsertNewInstBefore(NewSel, SI);
9103             NewSel->takeName(FVI);
9104             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9105               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9106             else
9107               assert(0 && "Unknown instruction!!");
9108           }
9109         }
9110   }
9111
9112   if (BinaryOperator::isNot(CondVal)) {
9113     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9114     SI.setOperand(1, FalseVal);
9115     SI.setOperand(2, TrueVal);
9116     return &SI;
9117   }
9118
9119   return 0;
9120 }
9121
9122 /// EnforceKnownAlignment - If the specified pointer points to an object that
9123 /// we control, modify the object's alignment to PrefAlign. This isn't
9124 /// often possible though. If alignment is important, a more reliable approach
9125 /// is to simply align all global variables and allocation instructions to
9126 /// their preferred alignment from the beginning.
9127 ///
9128 static unsigned EnforceKnownAlignment(Value *V,
9129                                       unsigned Align, unsigned PrefAlign) {
9130
9131   User *U = dyn_cast<User>(V);
9132   if (!U) return Align;
9133
9134   switch (getOpcode(U)) {
9135   default: break;
9136   case Instruction::BitCast:
9137     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9138   case Instruction::GetElementPtr: {
9139     // If all indexes are zero, it is just the alignment of the base pointer.
9140     bool AllZeroOperands = true;
9141     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9142       if (!isa<Constant>(*i) ||
9143           !cast<Constant>(*i)->isNullValue()) {
9144         AllZeroOperands = false;
9145         break;
9146       }
9147
9148     if (AllZeroOperands) {
9149       // Treat this like a bitcast.
9150       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9151     }
9152     break;
9153   }
9154   }
9155
9156   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9157     // If there is a large requested alignment and we can, bump up the alignment
9158     // of the global.
9159     if (!GV->isDeclaration()) {
9160       GV->setAlignment(PrefAlign);
9161       Align = PrefAlign;
9162     }
9163   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9164     // If there is a requested alignment and if this is an alloca, round up.  We
9165     // don't do this for malloc, because some systems can't respect the request.
9166     if (isa<AllocaInst>(AI)) {
9167       AI->setAlignment(PrefAlign);
9168       Align = PrefAlign;
9169     }
9170   }
9171
9172   return Align;
9173 }
9174
9175 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9176 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9177 /// and it is more than the alignment of the ultimate object, see if we can
9178 /// increase the alignment of the ultimate object, making this check succeed.
9179 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9180                                                   unsigned PrefAlign) {
9181   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9182                       sizeof(PrefAlign) * CHAR_BIT;
9183   APInt Mask = APInt::getAllOnesValue(BitWidth);
9184   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9185   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9186   unsigned TrailZ = KnownZero.countTrailingOnes();
9187   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9188
9189   if (PrefAlign > Align)
9190     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9191   
9192     // We don't need to make any adjustment.
9193   return Align;
9194 }
9195
9196 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9197   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9198   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9199   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9200   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9201
9202   if (CopyAlign < MinAlign) {
9203     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9204     return MI;
9205   }
9206   
9207   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9208   // load/store.
9209   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9210   if (MemOpLength == 0) return 0;
9211   
9212   // Source and destination pointer types are always "i8*" for intrinsic.  See
9213   // if the size is something we can handle with a single primitive load/store.
9214   // A single load+store correctly handles overlapping memory in the memmove
9215   // case.
9216   unsigned Size = MemOpLength->getZExtValue();
9217   if (Size == 0) return MI;  // Delete this mem transfer.
9218   
9219   if (Size > 8 || (Size&(Size-1)))
9220     return 0;  // If not 1/2/4/8 bytes, exit.
9221   
9222   // Use an integer load+store unless we can find something better.
9223   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9224   
9225   // Memcpy forces the use of i8* for the source and destination.  That means
9226   // that if you're using memcpy to move one double around, you'll get a cast
9227   // from double* to i8*.  We'd much rather use a double load+store rather than
9228   // an i64 load+store, here because this improves the odds that the source or
9229   // dest address will be promotable.  See if we can find a better type than the
9230   // integer datatype.
9231   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9232     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9233     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9234       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9235       // down through these levels if so.
9236       while (!SrcETy->isSingleValueType()) {
9237         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9238           if (STy->getNumElements() == 1)
9239             SrcETy = STy->getElementType(0);
9240           else
9241             break;
9242         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9243           if (ATy->getNumElements() == 1)
9244             SrcETy = ATy->getElementType();
9245           else
9246             break;
9247         } else
9248           break;
9249       }
9250       
9251       if (SrcETy->isSingleValueType())
9252         NewPtrTy = PointerType::getUnqual(SrcETy);
9253     }
9254   }
9255   
9256   
9257   // If the memcpy/memmove provides better alignment info than we can
9258   // infer, use it.
9259   SrcAlign = std::max(SrcAlign, CopyAlign);
9260   DstAlign = std::max(DstAlign, CopyAlign);
9261   
9262   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9263   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9264   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9265   InsertNewInstBefore(L, *MI);
9266   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9267
9268   // Set the size of the copy to 0, it will be deleted on the next iteration.
9269   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9270   return MI;
9271 }
9272
9273 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9274   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9275   if (MI->getAlignment()->getZExtValue() < Alignment) {
9276     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9277     return MI;
9278   }
9279   
9280   // Extract the length and alignment and fill if they are constant.
9281   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9282   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9283   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9284     return 0;
9285   uint64_t Len = LenC->getZExtValue();
9286   Alignment = MI->getAlignment()->getZExtValue();
9287   
9288   // If the length is zero, this is a no-op
9289   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9290   
9291   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9292   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9293     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9294     
9295     Value *Dest = MI->getDest();
9296     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9297
9298     // Alignment 0 is identity for alignment 1 for memset, but not store.
9299     if (Alignment == 0) Alignment = 1;
9300     
9301     // Extract the fill value and store.
9302     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9303     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9304                                       Alignment), *MI);
9305     
9306     // Set the size of the copy to 0, it will be deleted on the next iteration.
9307     MI->setLength(Constant::getNullValue(LenC->getType()));
9308     return MI;
9309   }
9310
9311   return 0;
9312 }
9313
9314
9315 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9316 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9317 /// the heavy lifting.
9318 ///
9319 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9320   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9321   if (!II) return visitCallSite(&CI);
9322   
9323   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9324   // visitCallSite.
9325   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9326     bool Changed = false;
9327
9328     // memmove/cpy/set of zero bytes is a noop.
9329     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9330       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9331
9332       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9333         if (CI->getZExtValue() == 1) {
9334           // Replace the instruction with just byte operations.  We would
9335           // transform other cases to loads/stores, but we don't know if
9336           // alignment is sufficient.
9337         }
9338     }
9339
9340     // If we have a memmove and the source operation is a constant global,
9341     // then the source and dest pointers can't alias, so we can change this
9342     // into a call to memcpy.
9343     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9344       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9345         if (GVSrc->isConstant()) {
9346           Module *M = CI.getParent()->getParent()->getParent();
9347           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9348           const Type *Tys[1];
9349           Tys[0] = CI.getOperand(3)->getType();
9350           CI.setOperand(0, 
9351                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9352           Changed = true;
9353         }
9354
9355       // memmove(x,x,size) -> noop.
9356       if (MMI->getSource() == MMI->getDest())
9357         return EraseInstFromFunction(CI);
9358     }
9359
9360     // If we can determine a pointer alignment that is bigger than currently
9361     // set, update the alignment.
9362     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9363       if (Instruction *I = SimplifyMemTransfer(MI))
9364         return I;
9365     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9366       if (Instruction *I = SimplifyMemSet(MSI))
9367         return I;
9368     }
9369           
9370     if (Changed) return II;
9371   }
9372   
9373   switch (II->getIntrinsicID()) {
9374   default: break;
9375   case Intrinsic::bswap:
9376     // bswap(bswap(x)) -> x
9377     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9378       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9379         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9380     break;
9381   case Intrinsic::ppc_altivec_lvx:
9382   case Intrinsic::ppc_altivec_lvxl:
9383   case Intrinsic::x86_sse_loadu_ps:
9384   case Intrinsic::x86_sse2_loadu_pd:
9385   case Intrinsic::x86_sse2_loadu_dq:
9386     // Turn PPC lvx     -> load if the pointer is known aligned.
9387     // Turn X86 loadups -> load if the pointer is known aligned.
9388     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9389       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9390                                        PointerType::getUnqual(II->getType()),
9391                                        CI);
9392       return new LoadInst(Ptr);
9393     }
9394     break;
9395   case Intrinsic::ppc_altivec_stvx:
9396   case Intrinsic::ppc_altivec_stvxl:
9397     // Turn stvx -> store if the pointer is known aligned.
9398     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9399       const Type *OpPtrTy = 
9400         PointerType::getUnqual(II->getOperand(1)->getType());
9401       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9402       return new StoreInst(II->getOperand(1), Ptr);
9403     }
9404     break;
9405   case Intrinsic::x86_sse_storeu_ps:
9406   case Intrinsic::x86_sse2_storeu_pd:
9407   case Intrinsic::x86_sse2_storeu_dq:
9408     // Turn X86 storeu -> store if the pointer is known aligned.
9409     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9410       const Type *OpPtrTy = 
9411         PointerType::getUnqual(II->getOperand(2)->getType());
9412       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9413       return new StoreInst(II->getOperand(2), Ptr);
9414     }
9415     break;
9416     
9417   case Intrinsic::x86_sse_cvttss2si: {
9418     // These intrinsics only demands the 0th element of its input vector.  If
9419     // we can simplify the input based on that, do so now.
9420     uint64_t UndefElts;
9421     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
9422                                               UndefElts)) {
9423       II->setOperand(1, V);
9424       return II;
9425     }
9426     break;
9427   }
9428     
9429   case Intrinsic::ppc_altivec_vperm:
9430     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9431     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9432       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9433       
9434       // Check that all of the elements are integer constants or undefs.
9435       bool AllEltsOk = true;
9436       for (unsigned i = 0; i != 16; ++i) {
9437         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9438             !isa<UndefValue>(Mask->getOperand(i))) {
9439           AllEltsOk = false;
9440           break;
9441         }
9442       }
9443       
9444       if (AllEltsOk) {
9445         // Cast the input vectors to byte vectors.
9446         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9447         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9448         Value *Result = UndefValue::get(Op0->getType());
9449         
9450         // Only extract each element once.
9451         Value *ExtractedElts[32];
9452         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9453         
9454         for (unsigned i = 0; i != 16; ++i) {
9455           if (isa<UndefValue>(Mask->getOperand(i)))
9456             continue;
9457           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9458           Idx &= 31;  // Match the hardware behavior.
9459           
9460           if (ExtractedElts[Idx] == 0) {
9461             Instruction *Elt = 
9462               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9463             InsertNewInstBefore(Elt, CI);
9464             ExtractedElts[Idx] = Elt;
9465           }
9466         
9467           // Insert this value into the result vector.
9468           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9469                                              i, "tmp");
9470           InsertNewInstBefore(cast<Instruction>(Result), CI);
9471         }
9472         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9473       }
9474     }
9475     break;
9476
9477   case Intrinsic::stackrestore: {
9478     // If the save is right next to the restore, remove the restore.  This can
9479     // happen when variable allocas are DCE'd.
9480     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9481       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9482         BasicBlock::iterator BI = SS;
9483         if (&*++BI == II)
9484           return EraseInstFromFunction(CI);
9485       }
9486     }
9487     
9488     // Scan down this block to see if there is another stack restore in the
9489     // same block without an intervening call/alloca.
9490     BasicBlock::iterator BI = II;
9491     TerminatorInst *TI = II->getParent()->getTerminator();
9492     bool CannotRemove = false;
9493     for (++BI; &*BI != TI; ++BI) {
9494       if (isa<AllocaInst>(BI)) {
9495         CannotRemove = true;
9496         break;
9497       }
9498       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9499         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9500           // If there is a stackrestore below this one, remove this one.
9501           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9502             return EraseInstFromFunction(CI);
9503           // Otherwise, ignore the intrinsic.
9504         } else {
9505           // If we found a non-intrinsic call, we can't remove the stack
9506           // restore.
9507           CannotRemove = true;
9508           break;
9509         }
9510       }
9511     }
9512     
9513     // If the stack restore is in a return/unwind block and if there are no
9514     // allocas or calls between the restore and the return, nuke the restore.
9515     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9516       return EraseInstFromFunction(CI);
9517     break;
9518   }
9519   }
9520
9521   return visitCallSite(II);
9522 }
9523
9524 // InvokeInst simplification
9525 //
9526 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9527   return visitCallSite(&II);
9528 }
9529
9530 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9531 /// passed through the varargs area, we can eliminate the use of the cast.
9532 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9533                                          const CastInst * const CI,
9534                                          const TargetData * const TD,
9535                                          const int ix) {
9536   if (!CI->isLosslessCast())
9537     return false;
9538
9539   // The size of ByVal arguments is derived from the type, so we
9540   // can't change to a type with a different size.  If the size were
9541   // passed explicitly we could avoid this check.
9542   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9543     return true;
9544
9545   const Type* SrcTy = 
9546             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9547   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9548   if (!SrcTy->isSized() || !DstTy->isSized())
9549     return false;
9550   if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
9551     return false;
9552   return true;
9553 }
9554
9555 // visitCallSite - Improvements for call and invoke instructions.
9556 //
9557 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9558   bool Changed = false;
9559
9560   // If the callee is a constexpr cast of a function, attempt to move the cast
9561   // to the arguments of the call/invoke.
9562   if (transformConstExprCastCall(CS)) return 0;
9563
9564   Value *Callee = CS.getCalledValue();
9565
9566   if (Function *CalleeF = dyn_cast<Function>(Callee))
9567     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9568       Instruction *OldCall = CS.getInstruction();
9569       // If the call and callee calling conventions don't match, this call must
9570       // be unreachable, as the call is undefined.
9571       new StoreInst(ConstantInt::getTrue(),
9572                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9573                                     OldCall);
9574       if (!OldCall->use_empty())
9575         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9576       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9577         return EraseInstFromFunction(*OldCall);
9578       return 0;
9579     }
9580
9581   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9582     // This instruction is not reachable, just remove it.  We insert a store to
9583     // undef so that we know that this code is not reachable, despite the fact
9584     // that we can't modify the CFG here.
9585     new StoreInst(ConstantInt::getTrue(),
9586                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9587                   CS.getInstruction());
9588
9589     if (!CS.getInstruction()->use_empty())
9590       CS.getInstruction()->
9591         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9592
9593     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9594       // Don't break the CFG, insert a dummy cond branch.
9595       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9596                          ConstantInt::getTrue(), II);
9597     }
9598     return EraseInstFromFunction(*CS.getInstruction());
9599   }
9600
9601   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9602     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9603       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9604         return transformCallThroughTrampoline(CS);
9605
9606   const PointerType *PTy = cast<PointerType>(Callee->getType());
9607   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9608   if (FTy->isVarArg()) {
9609     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9610     // See if we can optimize any arguments passed through the varargs area of
9611     // the call.
9612     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9613            E = CS.arg_end(); I != E; ++I, ++ix) {
9614       CastInst *CI = dyn_cast<CastInst>(*I);
9615       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9616         *I = CI->getOperand(0);
9617         Changed = true;
9618       }
9619     }
9620   }
9621
9622   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9623     // Inline asm calls cannot throw - mark them 'nounwind'.
9624     CS.setDoesNotThrow();
9625     Changed = true;
9626   }
9627
9628   return Changed ? CS.getInstruction() : 0;
9629 }
9630
9631 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9632 // attempt to move the cast to the arguments of the call/invoke.
9633 //
9634 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9635   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9636   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9637   if (CE->getOpcode() != Instruction::BitCast || 
9638       !isa<Function>(CE->getOperand(0)))
9639     return false;
9640   Function *Callee = cast<Function>(CE->getOperand(0));
9641   Instruction *Caller = CS.getInstruction();
9642   const AttrListPtr &CallerPAL = CS.getAttributes();
9643
9644   // Okay, this is a cast from a function to a different type.  Unless doing so
9645   // would cause a type conversion of one of our arguments, change this call to
9646   // be a direct call with arguments casted to the appropriate types.
9647   //
9648   const FunctionType *FT = Callee->getFunctionType();
9649   const Type *OldRetTy = Caller->getType();
9650   const Type *NewRetTy = FT->getReturnType();
9651
9652   if (isa<StructType>(NewRetTy))
9653     return false; // TODO: Handle multiple return values.
9654
9655   // Check to see if we are changing the return type...
9656   if (OldRetTy != NewRetTy) {
9657     if (Callee->isDeclaration() &&
9658         // Conversion is ok if changing from one pointer type to another or from
9659         // a pointer to an integer of the same size.
9660         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9661           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9662       return false;   // Cannot transform this return value.
9663
9664     if (!Caller->use_empty() &&
9665         // void -> non-void is handled specially
9666         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9667       return false;   // Cannot transform this return value.
9668
9669     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9670       Attributes RAttrs = CallerPAL.getRetAttributes();
9671       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9672         return false;   // Attribute not compatible with transformed value.
9673     }
9674
9675     // If the callsite is an invoke instruction, and the return value is used by
9676     // a PHI node in a successor, we cannot change the return type of the call
9677     // because there is no place to put the cast instruction (without breaking
9678     // the critical edge).  Bail out in this case.
9679     if (!Caller->use_empty())
9680       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9681         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9682              UI != E; ++UI)
9683           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9684             if (PN->getParent() == II->getNormalDest() ||
9685                 PN->getParent() == II->getUnwindDest())
9686               return false;
9687   }
9688
9689   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9690   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9691
9692   CallSite::arg_iterator AI = CS.arg_begin();
9693   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9694     const Type *ParamTy = FT->getParamType(i);
9695     const Type *ActTy = (*AI)->getType();
9696
9697     if (!CastInst::isCastable(ActTy, ParamTy))
9698       return false;   // Cannot transform this parameter value.
9699
9700     if (CallerPAL.getParamAttributes(i + 1) 
9701         & Attribute::typeIncompatible(ParamTy))
9702       return false;   // Attribute not compatible with transformed value.
9703
9704     // Converting from one pointer type to another or between a pointer and an
9705     // integer of the same size is safe even if we do not have a body.
9706     bool isConvertible = ActTy == ParamTy ||
9707       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9708        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9709     if (Callee->isDeclaration() && !isConvertible) return false;
9710   }
9711
9712   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9713       Callee->isDeclaration())
9714     return false;   // Do not delete arguments unless we have a function body.
9715
9716   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9717       !CallerPAL.isEmpty())
9718     // In this case we have more arguments than the new function type, but we
9719     // won't be dropping them.  Check that these extra arguments have attributes
9720     // that are compatible with being a vararg call argument.
9721     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9722       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9723         break;
9724       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9725       if (PAttrs & Attribute::VarArgsIncompatible)
9726         return false;
9727     }
9728
9729   // Okay, we decided that this is a safe thing to do: go ahead and start
9730   // inserting cast instructions as necessary...
9731   std::vector<Value*> Args;
9732   Args.reserve(NumActualArgs);
9733   SmallVector<AttributeWithIndex, 8> attrVec;
9734   attrVec.reserve(NumCommonArgs);
9735
9736   // Get any return attributes.
9737   Attributes RAttrs = CallerPAL.getRetAttributes();
9738
9739   // If the return value is not being used, the type may not be compatible
9740   // with the existing attributes.  Wipe out any problematic attributes.
9741   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
9742
9743   // Add the new return attributes.
9744   if (RAttrs)
9745     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
9746
9747   AI = CS.arg_begin();
9748   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9749     const Type *ParamTy = FT->getParamType(i);
9750     if ((*AI)->getType() == ParamTy) {
9751       Args.push_back(*AI);
9752     } else {
9753       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9754           false, ParamTy, false);
9755       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9756       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9757     }
9758
9759     // Add any parameter attributes.
9760     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9761       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9762   }
9763
9764   // If the function takes more arguments than the call was taking, add them
9765   // now...
9766   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9767     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9768
9769   // If we are removing arguments to the function, emit an obnoxious warning...
9770   if (FT->getNumParams() < NumActualArgs) {
9771     if (!FT->isVarArg()) {
9772       cerr << "WARNING: While resolving call to function '"
9773            << Callee->getName() << "' arguments were dropped!\n";
9774     } else {
9775       // Add all of the arguments in their promoted form to the arg list...
9776       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9777         const Type *PTy = getPromotedType((*AI)->getType());
9778         if (PTy != (*AI)->getType()) {
9779           // Must promote to pass through va_arg area!
9780           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9781                                                                 PTy, false);
9782           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9783           InsertNewInstBefore(Cast, *Caller);
9784           Args.push_back(Cast);
9785         } else {
9786           Args.push_back(*AI);
9787         }
9788
9789         // Add any parameter attributes.
9790         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9791           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9792       }
9793     }
9794   }
9795
9796   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
9797     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9798
9799   if (NewRetTy == Type::VoidTy)
9800     Caller->setName("");   // Void type should not have a name.
9801
9802   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
9803
9804   Instruction *NC;
9805   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9806     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9807                             Args.begin(), Args.end(),
9808                             Caller->getName(), Caller);
9809     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9810     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
9811   } else {
9812     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9813                           Caller->getName(), Caller);
9814     CallInst *CI = cast<CallInst>(Caller);
9815     if (CI->isTailCall())
9816       cast<CallInst>(NC)->setTailCall();
9817     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9818     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
9819   }
9820
9821   // Insert a cast of the return type as necessary.
9822   Value *NV = NC;
9823   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9824     if (NV->getType() != Type::VoidTy) {
9825       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9826                                                             OldRetTy, false);
9827       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9828
9829       // If this is an invoke instruction, we should insert it after the first
9830       // non-phi, instruction in the normal successor block.
9831       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9832         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9833         InsertNewInstBefore(NC, *I);
9834       } else {
9835         // Otherwise, it's a call, just insert cast right after the call instr
9836         InsertNewInstBefore(NC, *Caller);
9837       }
9838       AddUsersToWorkList(*Caller);
9839     } else {
9840       NV = UndefValue::get(Caller->getType());
9841     }
9842   }
9843
9844   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9845     Caller->replaceAllUsesWith(NV);
9846   Caller->eraseFromParent();
9847   RemoveFromWorkList(Caller);
9848   return true;
9849 }
9850
9851 // transformCallThroughTrampoline - Turn a call to a function created by the
9852 // init_trampoline intrinsic into a direct call to the underlying function.
9853 //
9854 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9855   Value *Callee = CS.getCalledValue();
9856   const PointerType *PTy = cast<PointerType>(Callee->getType());
9857   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9858   const AttrListPtr &Attrs = CS.getAttributes();
9859
9860   // If the call already has the 'nest' attribute somewhere then give up -
9861   // otherwise 'nest' would occur twice after splicing in the chain.
9862   if (Attrs.hasAttrSomewhere(Attribute::Nest))
9863     return 0;
9864
9865   IntrinsicInst *Tramp =
9866     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9867
9868   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9869   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9870   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9871
9872   const AttrListPtr &NestAttrs = NestF->getAttributes();
9873   if (!NestAttrs.isEmpty()) {
9874     unsigned NestIdx = 1;
9875     const Type *NestTy = 0;
9876     Attributes NestAttr = Attribute::None;
9877
9878     // Look for a parameter marked with the 'nest' attribute.
9879     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9880          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9881       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
9882         // Record the parameter type and any other attributes.
9883         NestTy = *I;
9884         NestAttr = NestAttrs.getParamAttributes(NestIdx);
9885         break;
9886       }
9887
9888     if (NestTy) {
9889       Instruction *Caller = CS.getInstruction();
9890       std::vector<Value*> NewArgs;
9891       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9892
9893       SmallVector<AttributeWithIndex, 8> NewAttrs;
9894       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9895
9896       // Insert the nest argument into the call argument list, which may
9897       // mean appending it.  Likewise for attributes.
9898
9899       // Add any result attributes.
9900       if (Attributes Attr = Attrs.getRetAttributes())
9901         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
9902
9903       {
9904         unsigned Idx = 1;
9905         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9906         do {
9907           if (Idx == NestIdx) {
9908             // Add the chain argument and attributes.
9909             Value *NestVal = Tramp->getOperand(3);
9910             if (NestVal->getType() != NestTy)
9911               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9912             NewArgs.push_back(NestVal);
9913             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
9914           }
9915
9916           if (I == E)
9917             break;
9918
9919           // Add the original argument and attributes.
9920           NewArgs.push_back(*I);
9921           if (Attributes Attr = Attrs.getParamAttributes(Idx))
9922             NewAttrs.push_back
9923               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9924
9925           ++Idx, ++I;
9926         } while (1);
9927       }
9928
9929       // Add any function attributes.
9930       if (Attributes Attr = Attrs.getFnAttributes())
9931         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9932
9933       // The trampoline may have been bitcast to a bogus type (FTy).
9934       // Handle this by synthesizing a new function type, equal to FTy
9935       // with the chain parameter inserted.
9936
9937       std::vector<const Type*> NewTypes;
9938       NewTypes.reserve(FTy->getNumParams()+1);
9939
9940       // Insert the chain's type into the list of parameter types, which may
9941       // mean appending it.
9942       {
9943         unsigned Idx = 1;
9944         FunctionType::param_iterator I = FTy->param_begin(),
9945           E = FTy->param_end();
9946
9947         do {
9948           if (Idx == NestIdx)
9949             // Add the chain's type.
9950             NewTypes.push_back(NestTy);
9951
9952           if (I == E)
9953             break;
9954
9955           // Add the original type.
9956           NewTypes.push_back(*I);
9957
9958           ++Idx, ++I;
9959         } while (1);
9960       }
9961
9962       // Replace the trampoline call with a direct call.  Let the generic
9963       // code sort out any function type mismatches.
9964       FunctionType *NewFTy =
9965         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9966       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9967         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9968       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
9969
9970       Instruction *NewCaller;
9971       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9972         NewCaller = InvokeInst::Create(NewCallee,
9973                                        II->getNormalDest(), II->getUnwindDest(),
9974                                        NewArgs.begin(), NewArgs.end(),
9975                                        Caller->getName(), Caller);
9976         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9977         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
9978       } else {
9979         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9980                                      Caller->getName(), Caller);
9981         if (cast<CallInst>(Caller)->isTailCall())
9982           cast<CallInst>(NewCaller)->setTailCall();
9983         cast<CallInst>(NewCaller)->
9984           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9985         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
9986       }
9987       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9988         Caller->replaceAllUsesWith(NewCaller);
9989       Caller->eraseFromParent();
9990       RemoveFromWorkList(Caller);
9991       return 0;
9992     }
9993   }
9994
9995   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9996   // parameter, there is no need to adjust the argument list.  Let the generic
9997   // code sort out any function type mismatches.
9998   Constant *NewCallee =
9999     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10000   CS.setCalledFunction(NewCallee);
10001   return CS.getInstruction();
10002 }
10003
10004 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10005 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10006 /// and a single binop.
10007 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10008   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10009   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10010   unsigned Opc = FirstInst->getOpcode();
10011   Value *LHSVal = FirstInst->getOperand(0);
10012   Value *RHSVal = FirstInst->getOperand(1);
10013     
10014   const Type *LHSType = LHSVal->getType();
10015   const Type *RHSType = RHSVal->getType();
10016   
10017   // Scan to see if all operands are the same opcode, all have one use, and all
10018   // kill their operands (i.e. the operands have one use).
10019   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10020     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10021     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10022         // Verify type of the LHS matches so we don't fold cmp's of different
10023         // types or GEP's with different index types.
10024         I->getOperand(0)->getType() != LHSType ||
10025         I->getOperand(1)->getType() != RHSType)
10026       return 0;
10027
10028     // If they are CmpInst instructions, check their predicates
10029     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10030       if (cast<CmpInst>(I)->getPredicate() !=
10031           cast<CmpInst>(FirstInst)->getPredicate())
10032         return 0;
10033     
10034     // Keep track of which operand needs a phi node.
10035     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10036     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10037   }
10038   
10039   // Otherwise, this is safe to transform!
10040   
10041   Value *InLHS = FirstInst->getOperand(0);
10042   Value *InRHS = FirstInst->getOperand(1);
10043   PHINode *NewLHS = 0, *NewRHS = 0;
10044   if (LHSVal == 0) {
10045     NewLHS = PHINode::Create(LHSType,
10046                              FirstInst->getOperand(0)->getName() + ".pn");
10047     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10048     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10049     InsertNewInstBefore(NewLHS, PN);
10050     LHSVal = NewLHS;
10051   }
10052   
10053   if (RHSVal == 0) {
10054     NewRHS = PHINode::Create(RHSType,
10055                              FirstInst->getOperand(1)->getName() + ".pn");
10056     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10057     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10058     InsertNewInstBefore(NewRHS, PN);
10059     RHSVal = NewRHS;
10060   }
10061   
10062   // Add all operands to the new PHIs.
10063   if (NewLHS || NewRHS) {
10064     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10065       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10066       if (NewLHS) {
10067         Value *NewInLHS = InInst->getOperand(0);
10068         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10069       }
10070       if (NewRHS) {
10071         Value *NewInRHS = InInst->getOperand(1);
10072         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10073       }
10074     }
10075   }
10076     
10077   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10078     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10079   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10080   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10081                          RHSVal);
10082 }
10083
10084 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10085   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10086   
10087   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10088                                         FirstInst->op_end());
10089   
10090   // Scan to see if all operands are the same opcode, all have one use, and all
10091   // kill their operands (i.e. the operands have one use).
10092   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10093     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10094     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10095       GEP->getNumOperands() != FirstInst->getNumOperands())
10096       return 0;
10097
10098     // Compare the operand lists.
10099     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10100       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10101         continue;
10102       
10103       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10104       // if one of the PHIs has a constant for the index.  The index may be
10105       // substantially cheaper to compute for the constants, so making it a
10106       // variable index could pessimize the path.  This also handles the case
10107       // for struct indices, which must always be constant.
10108       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10109           isa<ConstantInt>(GEP->getOperand(op)))
10110         return 0;
10111       
10112       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10113         return 0;
10114       FixedOperands[op] = 0;  // Needs a PHI.
10115     }
10116   }
10117   
10118   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10119   // that is variable.
10120   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10121   
10122   bool HasAnyPHIs = false;
10123   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10124     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10125     Value *FirstOp = FirstInst->getOperand(i);
10126     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10127                                      FirstOp->getName()+".pn");
10128     InsertNewInstBefore(NewPN, PN);
10129     
10130     NewPN->reserveOperandSpace(e);
10131     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10132     OperandPhis[i] = NewPN;
10133     FixedOperands[i] = NewPN;
10134     HasAnyPHIs = true;
10135   }
10136
10137   
10138   // Add all operands to the new PHIs.
10139   if (HasAnyPHIs) {
10140     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10141       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10142       BasicBlock *InBB = PN.getIncomingBlock(i);
10143       
10144       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10145         if (PHINode *OpPhi = OperandPhis[op])
10146           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10147     }
10148   }
10149   
10150   Value *Base = FixedOperands[0];
10151   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10152                                    FixedOperands.end());
10153 }
10154
10155
10156 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
10157 /// of the block that defines it.  This means that it must be obvious the value
10158 /// of the load is not changed from the point of the load to the end of the
10159 /// block it is in.
10160 ///
10161 /// Finally, it is safe, but not profitable, to sink a load targetting a
10162 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10163 /// to a register.
10164 static bool isSafeToSinkLoad(LoadInst *L) {
10165   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10166   
10167   for (++BBI; BBI != E; ++BBI)
10168     if (BBI->mayWriteToMemory())
10169       return false;
10170   
10171   // Check for non-address taken alloca.  If not address-taken already, it isn't
10172   // profitable to do this xform.
10173   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10174     bool isAddressTaken = false;
10175     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10176          UI != E; ++UI) {
10177       if (isa<LoadInst>(UI)) continue;
10178       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10179         // If storing TO the alloca, then the address isn't taken.
10180         if (SI->getOperand(1) == AI) continue;
10181       }
10182       isAddressTaken = true;
10183       break;
10184     }
10185     
10186     if (!isAddressTaken)
10187       return false;
10188   }
10189   
10190   return true;
10191 }
10192
10193
10194 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10195 // operator and they all are only used by the PHI, PHI together their
10196 // inputs, and do the operation once, to the result of the PHI.
10197 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10198   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10199
10200   // Scan the instruction, looking for input operations that can be folded away.
10201   // If all input operands to the phi are the same instruction (e.g. a cast from
10202   // the same type or "+42") we can pull the operation through the PHI, reducing
10203   // code size and simplifying code.
10204   Constant *ConstantOp = 0;
10205   const Type *CastSrcTy = 0;
10206   bool isVolatile = false;
10207   if (isa<CastInst>(FirstInst)) {
10208     CastSrcTy = FirstInst->getOperand(0)->getType();
10209   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10210     // Can fold binop, compare or shift here if the RHS is a constant, 
10211     // otherwise call FoldPHIArgBinOpIntoPHI.
10212     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10213     if (ConstantOp == 0)
10214       return FoldPHIArgBinOpIntoPHI(PN);
10215   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10216     isVolatile = LI->isVolatile();
10217     // We can't sink the load if the loaded value could be modified between the
10218     // load and the PHI.
10219     if (LI->getParent() != PN.getIncomingBlock(0) ||
10220         !isSafeToSinkLoad(LI))
10221       return 0;
10222     
10223     // If the PHI is of volatile loads and the load block has multiple
10224     // successors, sinking it would remove a load of the volatile value from
10225     // the path through the other successor.
10226     if (isVolatile &&
10227         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10228       return 0;
10229     
10230   } else if (isa<GetElementPtrInst>(FirstInst)) {
10231     return FoldPHIArgGEPIntoPHI(PN);
10232   } else {
10233     return 0;  // Cannot fold this operation.
10234   }
10235
10236   // Check to see if all arguments are the same operation.
10237   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10238     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10239     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10240     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10241       return 0;
10242     if (CastSrcTy) {
10243       if (I->getOperand(0)->getType() != CastSrcTy)
10244         return 0;  // Cast operation must match.
10245     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10246       // We can't sink the load if the loaded value could be modified between 
10247       // the load and the PHI.
10248       if (LI->isVolatile() != isVolatile ||
10249           LI->getParent() != PN.getIncomingBlock(i) ||
10250           !isSafeToSinkLoad(LI))
10251         return 0;
10252       
10253       // If the PHI is of volatile loads and the load block has multiple
10254       // successors, sinking it would remove a load of the volatile value from
10255       // the path through the other successor.
10256       if (isVolatile &&
10257           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10258         return 0;
10259
10260       
10261     } else if (I->getOperand(1) != ConstantOp) {
10262       return 0;
10263     }
10264   }
10265
10266   // Okay, they are all the same operation.  Create a new PHI node of the
10267   // correct type, and PHI together all of the LHS's of the instructions.
10268   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10269                                    PN.getName()+".in");
10270   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10271
10272   Value *InVal = FirstInst->getOperand(0);
10273   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10274
10275   // Add all operands to the new PHI.
10276   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10277     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10278     if (NewInVal != InVal)
10279       InVal = 0;
10280     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10281   }
10282
10283   Value *PhiVal;
10284   if (InVal) {
10285     // The new PHI unions all of the same values together.  This is really
10286     // common, so we handle it intelligently here for compile-time speed.
10287     PhiVal = InVal;
10288     delete NewPN;
10289   } else {
10290     InsertNewInstBefore(NewPN, PN);
10291     PhiVal = NewPN;
10292   }
10293
10294   // Insert and return the new operation.
10295   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10296     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10297   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10298     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10299   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10300     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10301                            PhiVal, ConstantOp);
10302   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10303   
10304   // If this was a volatile load that we are merging, make sure to loop through
10305   // and mark all the input loads as non-volatile.  If we don't do this, we will
10306   // insert a new volatile load and the old ones will not be deletable.
10307   if (isVolatile)
10308     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10309       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10310   
10311   return new LoadInst(PhiVal, "", isVolatile);
10312 }
10313
10314 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10315 /// that is dead.
10316 static bool DeadPHICycle(PHINode *PN,
10317                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10318   if (PN->use_empty()) return true;
10319   if (!PN->hasOneUse()) return false;
10320
10321   // Remember this node, and if we find the cycle, return.
10322   if (!PotentiallyDeadPHIs.insert(PN))
10323     return true;
10324   
10325   // Don't scan crazily complex things.
10326   if (PotentiallyDeadPHIs.size() == 16)
10327     return false;
10328
10329   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10330     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10331
10332   return false;
10333 }
10334
10335 /// PHIsEqualValue - Return true if this phi node is always equal to
10336 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10337 ///   z = some value; x = phi (y, z); y = phi (x, z)
10338 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10339                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10340   // See if we already saw this PHI node.
10341   if (!ValueEqualPHIs.insert(PN))
10342     return true;
10343   
10344   // Don't scan crazily complex things.
10345   if (ValueEqualPHIs.size() == 16)
10346     return false;
10347  
10348   // Scan the operands to see if they are either phi nodes or are equal to
10349   // the value.
10350   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10351     Value *Op = PN->getIncomingValue(i);
10352     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10353       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10354         return false;
10355     } else if (Op != NonPhiInVal)
10356       return false;
10357   }
10358   
10359   return true;
10360 }
10361
10362
10363 // PHINode simplification
10364 //
10365 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10366   // If LCSSA is around, don't mess with Phi nodes
10367   if (MustPreserveLCSSA) return 0;
10368   
10369   if (Value *V = PN.hasConstantValue())
10370     return ReplaceInstUsesWith(PN, V);
10371
10372   // If all PHI operands are the same operation, pull them through the PHI,
10373   // reducing code size.
10374   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10375       isa<Instruction>(PN.getIncomingValue(1)) &&
10376       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10377       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10378       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10379       // than themselves more than once.
10380       PN.getIncomingValue(0)->hasOneUse())
10381     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10382       return Result;
10383
10384   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10385   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10386   // PHI)... break the cycle.
10387   if (PN.hasOneUse()) {
10388     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10389     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10390       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10391       PotentiallyDeadPHIs.insert(&PN);
10392       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10393         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10394     }
10395    
10396     // If this phi has a single use, and if that use just computes a value for
10397     // the next iteration of a loop, delete the phi.  This occurs with unused
10398     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10399     // common case here is good because the only other things that catch this
10400     // are induction variable analysis (sometimes) and ADCE, which is only run
10401     // late.
10402     if (PHIUser->hasOneUse() &&
10403         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10404         PHIUser->use_back() == &PN) {
10405       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10406     }
10407   }
10408
10409   // We sometimes end up with phi cycles that non-obviously end up being the
10410   // same value, for example:
10411   //   z = some value; x = phi (y, z); y = phi (x, z)
10412   // where the phi nodes don't necessarily need to be in the same block.  Do a
10413   // quick check to see if the PHI node only contains a single non-phi value, if
10414   // so, scan to see if the phi cycle is actually equal to that value.
10415   {
10416     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10417     // Scan for the first non-phi operand.
10418     while (InValNo != NumOperandVals && 
10419            isa<PHINode>(PN.getIncomingValue(InValNo)))
10420       ++InValNo;
10421
10422     if (InValNo != NumOperandVals) {
10423       Value *NonPhiInVal = PN.getOperand(InValNo);
10424       
10425       // Scan the rest of the operands to see if there are any conflicts, if so
10426       // there is no need to recursively scan other phis.
10427       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10428         Value *OpVal = PN.getIncomingValue(InValNo);
10429         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10430           break;
10431       }
10432       
10433       // If we scanned over all operands, then we have one unique value plus
10434       // phi values.  Scan PHI nodes to see if they all merge in each other or
10435       // the value.
10436       if (InValNo == NumOperandVals) {
10437         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10438         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10439           return ReplaceInstUsesWith(PN, NonPhiInVal);
10440       }
10441     }
10442   }
10443   return 0;
10444 }
10445
10446 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10447                                    Instruction *InsertPoint,
10448                                    InstCombiner *IC) {
10449   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10450   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10451   // We must cast correctly to the pointer type. Ensure that we
10452   // sign extend the integer value if it is smaller as this is
10453   // used for address computation.
10454   Instruction::CastOps opcode = 
10455      (VTySize < PtrSize ? Instruction::SExt :
10456       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10457   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10458 }
10459
10460
10461 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10462   Value *PtrOp = GEP.getOperand(0);
10463   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10464   // If so, eliminate the noop.
10465   if (GEP.getNumOperands() == 1)
10466     return ReplaceInstUsesWith(GEP, PtrOp);
10467
10468   if (isa<UndefValue>(GEP.getOperand(0)))
10469     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10470
10471   bool HasZeroPointerIndex = false;
10472   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10473     HasZeroPointerIndex = C->isNullValue();
10474
10475   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10476     return ReplaceInstUsesWith(GEP, PtrOp);
10477
10478   // Eliminate unneeded casts for indices.
10479   bool MadeChange = false;
10480   
10481   gep_type_iterator GTI = gep_type_begin(GEP);
10482   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10483        i != e; ++i, ++GTI) {
10484     if (isa<SequentialType>(*GTI)) {
10485       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10486         if (CI->getOpcode() == Instruction::ZExt ||
10487             CI->getOpcode() == Instruction::SExt) {
10488           const Type *SrcTy = CI->getOperand(0)->getType();
10489           // We can eliminate a cast from i32 to i64 iff the target 
10490           // is a 32-bit pointer target.
10491           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10492             MadeChange = true;
10493             *i = CI->getOperand(0);
10494           }
10495         }
10496       }
10497       // If we are using a wider index than needed for this platform, shrink it
10498       // to what we need.  If narrower, sign-extend it to what we need.
10499       // If the incoming value needs a cast instruction,
10500       // insert it.  This explicit cast can make subsequent optimizations more
10501       // obvious.
10502       Value *Op = *i;
10503       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10504         if (Constant *C = dyn_cast<Constant>(Op)) {
10505           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10506           MadeChange = true;
10507         } else {
10508           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10509                                 GEP);
10510           *i = Op;
10511           MadeChange = true;
10512         }
10513       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10514         if (Constant *C = dyn_cast<Constant>(Op)) {
10515           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10516           MadeChange = true;
10517         } else {
10518           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10519                                 GEP);
10520           *i = Op;
10521           MadeChange = true;
10522         }
10523       }
10524     }
10525   }
10526   if (MadeChange) return &GEP;
10527
10528   // Combine Indices - If the source pointer to this getelementptr instruction
10529   // is a getelementptr instruction, combine the indices of the two
10530   // getelementptr instructions into a single instruction.
10531   //
10532   SmallVector<Value*, 8> SrcGEPOperands;
10533   if (User *Src = dyn_castGetElementPtr(PtrOp))
10534     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10535
10536   if (!SrcGEPOperands.empty()) {
10537     // Note that if our source is a gep chain itself that we wait for that
10538     // chain to be resolved before we perform this transformation.  This
10539     // avoids us creating a TON of code in some cases.
10540     //
10541     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10542         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10543       return 0;   // Wait until our source is folded to completion.
10544
10545     SmallVector<Value*, 8> Indices;
10546
10547     // Find out whether the last index in the source GEP is a sequential idx.
10548     bool EndsWithSequential = false;
10549     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10550            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10551       EndsWithSequential = !isa<StructType>(*I);
10552
10553     // Can we combine the two pointer arithmetics offsets?
10554     if (EndsWithSequential) {
10555       // Replace: gep (gep %P, long B), long A, ...
10556       // With:    T = long A+B; gep %P, T, ...
10557       //
10558       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10559       if (SO1 == Constant::getNullValue(SO1->getType())) {
10560         Sum = GO1;
10561       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10562         Sum = SO1;
10563       } else {
10564         // If they aren't the same type, convert both to an integer of the
10565         // target's pointer size.
10566         if (SO1->getType() != GO1->getType()) {
10567           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10568             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10569           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10570             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10571           } else {
10572             unsigned PS = TD->getPointerSizeInBits();
10573             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10574               // Convert GO1 to SO1's type.
10575               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10576
10577             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10578               // Convert SO1 to GO1's type.
10579               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10580             } else {
10581               const Type *PT = TD->getIntPtrType();
10582               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10583               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10584             }
10585           }
10586         }
10587         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10588           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10589         else {
10590           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10591           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10592         }
10593       }
10594
10595       // Recycle the GEP we already have if possible.
10596       if (SrcGEPOperands.size() == 2) {
10597         GEP.setOperand(0, SrcGEPOperands[0]);
10598         GEP.setOperand(1, Sum);
10599         return &GEP;
10600       } else {
10601         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10602                        SrcGEPOperands.end()-1);
10603         Indices.push_back(Sum);
10604         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10605       }
10606     } else if (isa<Constant>(*GEP.idx_begin()) &&
10607                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10608                SrcGEPOperands.size() != 1) {
10609       // Otherwise we can do the fold if the first index of the GEP is a zero
10610       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10611                      SrcGEPOperands.end());
10612       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10613     }
10614
10615     if (!Indices.empty())
10616       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10617                                        Indices.end(), GEP.getName());
10618
10619   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10620     // GEP of global variable.  If all of the indices for this GEP are
10621     // constants, we can promote this to a constexpr instead of an instruction.
10622
10623     // Scan for nonconstants...
10624     SmallVector<Constant*, 8> Indices;
10625     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10626     for (; I != E && isa<Constant>(*I); ++I)
10627       Indices.push_back(cast<Constant>(*I));
10628
10629     if (I == E) {  // If they are all constants...
10630       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10631                                                     &Indices[0],Indices.size());
10632
10633       // Replace all uses of the GEP with the new constexpr...
10634       return ReplaceInstUsesWith(GEP, CE);
10635     }
10636   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10637     if (!isa<PointerType>(X->getType())) {
10638       // Not interesting.  Source pointer must be a cast from pointer.
10639     } else if (HasZeroPointerIndex) {
10640       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10641       // into     : GEP [10 x i8]* X, i32 0, ...
10642       //
10643       // This occurs when the program declares an array extern like "int X[];"
10644       //
10645       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10646       const PointerType *XTy = cast<PointerType>(X->getType());
10647       if (const ArrayType *XATy =
10648           dyn_cast<ArrayType>(XTy->getElementType()))
10649         if (const ArrayType *CATy =
10650             dyn_cast<ArrayType>(CPTy->getElementType()))
10651           if (CATy->getElementType() == XATy->getElementType()) {
10652             // At this point, we know that the cast source type is a pointer
10653             // to an array of the same type as the destination pointer
10654             // array.  Because the array type is never stepped over (there
10655             // is a leading zero) we can fold the cast into this GEP.
10656             GEP.setOperand(0, X);
10657             return &GEP;
10658           }
10659     } else if (GEP.getNumOperands() == 2) {
10660       // Transform things like:
10661       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10662       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10663       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10664       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10665       if (isa<ArrayType>(SrcElTy) &&
10666           TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10667           TD->getTypePaddedSize(ResElTy)) {
10668         Value *Idx[2];
10669         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10670         Idx[1] = GEP.getOperand(1);
10671         Value *V = InsertNewInstBefore(
10672                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10673         // V and GEP are both pointer types --> BitCast
10674         return new BitCastInst(V, GEP.getType());
10675       }
10676       
10677       // Transform things like:
10678       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10679       //   (where tmp = 8*tmp2) into:
10680       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10681       
10682       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10683         uint64_t ArrayEltSize =
10684             TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
10685         
10686         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10687         // allow either a mul, shift, or constant here.
10688         Value *NewIdx = 0;
10689         ConstantInt *Scale = 0;
10690         if (ArrayEltSize == 1) {
10691           NewIdx = GEP.getOperand(1);
10692           Scale = ConstantInt::get(NewIdx->getType(), 1);
10693         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10694           NewIdx = ConstantInt::get(CI->getType(), 1);
10695           Scale = CI;
10696         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10697           if (Inst->getOpcode() == Instruction::Shl &&
10698               isa<ConstantInt>(Inst->getOperand(1))) {
10699             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10700             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10701             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10702             NewIdx = Inst->getOperand(0);
10703           } else if (Inst->getOpcode() == Instruction::Mul &&
10704                      isa<ConstantInt>(Inst->getOperand(1))) {
10705             Scale = cast<ConstantInt>(Inst->getOperand(1));
10706             NewIdx = Inst->getOperand(0);
10707           }
10708         }
10709         
10710         // If the index will be to exactly the right offset with the scale taken
10711         // out, perform the transformation. Note, we don't know whether Scale is
10712         // signed or not. We'll use unsigned version of division/modulo
10713         // operation after making sure Scale doesn't have the sign bit set.
10714         if (Scale && Scale->getSExtValue() >= 0LL &&
10715             Scale->getZExtValue() % ArrayEltSize == 0) {
10716           Scale = ConstantInt::get(Scale->getType(),
10717                                    Scale->getZExtValue() / ArrayEltSize);
10718           if (Scale->getZExtValue() != 1) {
10719             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10720                                                        false /*ZExt*/);
10721             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10722             NewIdx = InsertNewInstBefore(Sc, GEP);
10723           }
10724
10725           // Insert the new GEP instruction.
10726           Value *Idx[2];
10727           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10728           Idx[1] = NewIdx;
10729           Instruction *NewGEP =
10730             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10731           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10732           // The NewGEP must be pointer typed, so must the old one -> BitCast
10733           return new BitCastInst(NewGEP, GEP.getType());
10734         }
10735       }
10736     }
10737   }
10738   
10739   /// See if we can simplify:
10740   ///   X = bitcast A to B*
10741   ///   Y = gep X, <...constant indices...>
10742   /// into a gep of the original struct.  This is important for SROA and alias
10743   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
10744   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
10745     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10746       // Determine how much the GEP moves the pointer.  We are guaranteed to get
10747       // a constant back from EmitGEPOffset.
10748       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10749       int64_t Offset = OffsetV->getSExtValue();
10750       
10751       // If this GEP instruction doesn't move the pointer, just replace the GEP
10752       // with a bitcast of the real input to the dest type.
10753       if (Offset == 0) {
10754         // If the bitcast is of an allocation, and the allocation will be
10755         // converted to match the type of the cast, don't touch this.
10756         if (isa<AllocationInst>(BCI->getOperand(0))) {
10757           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10758           if (Instruction *I = visitBitCast(*BCI)) {
10759             if (I != BCI) {
10760               I->takeName(BCI);
10761               BCI->getParent()->getInstList().insert(BCI, I);
10762               ReplaceInstUsesWith(*BCI, I);
10763             }
10764             return &GEP;
10765           }
10766         }
10767         return new BitCastInst(BCI->getOperand(0), GEP.getType());
10768       }
10769       
10770       // Otherwise, if the offset is non-zero, we need to find out if there is a
10771       // field at Offset in 'A's type.  If so, we can pull the cast through the
10772       // GEP.
10773       SmallVector<Value*, 8> NewIndices;
10774       const Type *InTy =
10775         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10776       if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10777         Instruction *NGEP =
10778            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10779                                      NewIndices.end());
10780         if (NGEP->getType() == GEP.getType()) return NGEP;
10781         InsertNewInstBefore(NGEP, GEP);
10782         NGEP->takeName(&GEP);
10783         return new BitCastInst(NGEP, GEP.getType());
10784       }
10785     }
10786   }    
10787     
10788   return 0;
10789 }
10790
10791 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10792   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10793   if (AI.isArrayAllocation()) {  // Check C != 1
10794     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10795       const Type *NewTy = 
10796         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10797       AllocationInst *New = 0;
10798
10799       // Create and insert the replacement instruction...
10800       if (isa<MallocInst>(AI))
10801         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10802       else {
10803         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10804         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10805       }
10806
10807       InsertNewInstBefore(New, AI);
10808
10809       // Scan to the end of the allocation instructions, to skip over a block of
10810       // allocas if possible...
10811       //
10812       BasicBlock::iterator It = New;
10813       while (isa<AllocationInst>(*It)) ++It;
10814
10815       // Now that I is pointing to the first non-allocation-inst in the block,
10816       // insert our getelementptr instruction...
10817       //
10818       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10819       Value *Idx[2];
10820       Idx[0] = NullIdx;
10821       Idx[1] = NullIdx;
10822       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10823                                            New->getName()+".sub", It);
10824
10825       // Now make everything use the getelementptr instead of the original
10826       // allocation.
10827       return ReplaceInstUsesWith(AI, V);
10828     } else if (isa<UndefValue>(AI.getArraySize())) {
10829       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10830     }
10831   }
10832
10833   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
10834     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10835     // Note that we only do this for alloca's, because malloc should allocate and
10836     // return a unique pointer, even for a zero byte allocation.
10837     if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
10838       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10839
10840     // If the alignment is 0 (unspecified), assign it the preferred alignment.
10841     if (AI.getAlignment() == 0)
10842       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
10843   }
10844
10845   return 0;
10846 }
10847
10848 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10849   Value *Op = FI.getOperand(0);
10850
10851   // free undef -> unreachable.
10852   if (isa<UndefValue>(Op)) {
10853     // Insert a new store to null because we cannot modify the CFG here.
10854     new StoreInst(ConstantInt::getTrue(),
10855                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10856     return EraseInstFromFunction(FI);
10857   }
10858   
10859   // If we have 'free null' delete the instruction.  This can happen in stl code
10860   // when lots of inlining happens.
10861   if (isa<ConstantPointerNull>(Op))
10862     return EraseInstFromFunction(FI);
10863   
10864   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10865   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10866     FI.setOperand(0, CI->getOperand(0));
10867     return &FI;
10868   }
10869   
10870   // Change free (gep X, 0,0,0,0) into free(X)
10871   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10872     if (GEPI->hasAllZeroIndices()) {
10873       AddToWorkList(GEPI);
10874       FI.setOperand(0, GEPI->getOperand(0));
10875       return &FI;
10876     }
10877   }
10878   
10879   // Change free(malloc) into nothing, if the malloc has a single use.
10880   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10881     if (MI->hasOneUse()) {
10882       EraseInstFromFunction(FI);
10883       return EraseInstFromFunction(*MI);
10884     }
10885
10886   return 0;
10887 }
10888
10889
10890 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10891 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10892                                         const TargetData *TD) {
10893   User *CI = cast<User>(LI.getOperand(0));
10894   Value *CastOp = CI->getOperand(0);
10895
10896   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10897     // Instead of loading constant c string, use corresponding integer value
10898     // directly if string length is small enough.
10899     std::string Str;
10900     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10901       unsigned len = Str.length();
10902       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10903       unsigned numBits = Ty->getPrimitiveSizeInBits();
10904       // Replace LI with immediate integer store.
10905       if ((numBits >> 3) == len + 1) {
10906         APInt StrVal(numBits, 0);
10907         APInt SingleChar(numBits, 0);
10908         if (TD->isLittleEndian()) {
10909           for (signed i = len-1; i >= 0; i--) {
10910             SingleChar = (uint64_t) Str[i];
10911             StrVal = (StrVal << 8) | SingleChar;
10912           }
10913         } else {
10914           for (unsigned i = 0; i < len; i++) {
10915             SingleChar = (uint64_t) Str[i];
10916             StrVal = (StrVal << 8) | SingleChar;
10917           }
10918           // Append NULL at the end.
10919           SingleChar = 0;
10920           StrVal = (StrVal << 8) | SingleChar;
10921         }
10922         Value *NL = ConstantInt::get(StrVal);
10923         return IC.ReplaceInstUsesWith(LI, NL);
10924       }
10925     }
10926   }
10927
10928   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10929   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10930     const Type *SrcPTy = SrcTy->getElementType();
10931
10932     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10933          isa<VectorType>(DestPTy)) {
10934       // If the source is an array, the code below will not succeed.  Check to
10935       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10936       // constants.
10937       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10938         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10939           if (ASrcTy->getNumElements() != 0) {
10940             Value *Idxs[2];
10941             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10942             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10943             SrcTy = cast<PointerType>(CastOp->getType());
10944             SrcPTy = SrcTy->getElementType();
10945           }
10946
10947       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10948             isa<VectorType>(SrcPTy)) &&
10949           // Do not allow turning this into a load of an integer, which is then
10950           // casted to a pointer, this pessimizes pointer analysis a lot.
10951           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10952           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10953                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10954
10955         // Okay, we are casting from one integer or pointer type to another of
10956         // the same size.  Instead of casting the pointer before the load, cast
10957         // the result of the loaded value.
10958         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10959                                                              CI->getName(),
10960                                                          LI.isVolatile()),LI);
10961         // Now cast the result of the load.
10962         return new BitCastInst(NewLoad, LI.getType());
10963       }
10964     }
10965   }
10966   return 0;
10967 }
10968
10969 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10970 /// from this value cannot trap.  If it is not obviously safe to load from the
10971 /// specified pointer, we do a quick local scan of the basic block containing
10972 /// ScanFrom, to determine if the address is already accessed.
10973 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10974   // If it is an alloca it is always safe to load from.
10975   if (isa<AllocaInst>(V)) return true;
10976
10977   // If it is a global variable it is mostly safe to load from.
10978   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10979     // Don't try to evaluate aliases.  External weak GV can be null.
10980     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10981
10982   // Otherwise, be a little bit agressive by scanning the local block where we
10983   // want to check to see if the pointer is already being loaded or stored
10984   // from/to.  If so, the previous load or store would have already trapped,
10985   // so there is no harm doing an extra load (also, CSE will later eliminate
10986   // the load entirely).
10987   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10988
10989   while (BBI != E) {
10990     --BBI;
10991
10992     // If we see a free or a call (which might do a free) the pointer could be
10993     // marked invalid.
10994     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10995       return false;
10996     
10997     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10998       if (LI->getOperand(0) == V) return true;
10999     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
11000       if (SI->getOperand(1) == V) return true;
11001     }
11002
11003   }
11004   return false;
11005 }
11006
11007 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11008   Value *Op = LI.getOperand(0);
11009
11010   // Attempt to improve the alignment.
11011   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
11012   if (KnownAlign >
11013       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11014                                 LI.getAlignment()))
11015     LI.setAlignment(KnownAlign);
11016
11017   // load (cast X) --> cast (load X) iff safe
11018   if (isa<CastInst>(Op))
11019     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11020       return Res;
11021
11022   // None of the following transforms are legal for volatile loads.
11023   if (LI.isVolatile()) return 0;
11024   
11025   // Do really simple store-to-load forwarding and load CSE, to catch cases
11026   // where there are several consequtive memory accesses to the same location,
11027   // separated by a few arithmetic operations.
11028   BasicBlock::iterator BBI = &LI;
11029   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11030     return ReplaceInstUsesWith(LI, AvailableVal);
11031
11032   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11033     const Value *GEPI0 = GEPI->getOperand(0);
11034     // TODO: Consider a target hook for valid address spaces for this xform.
11035     if (isa<ConstantPointerNull>(GEPI0) &&
11036         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11037       // Insert a new store to null instruction before the load to indicate
11038       // that this code is not reachable.  We do this instead of inserting
11039       // an unreachable instruction directly because we cannot modify the
11040       // CFG.
11041       new StoreInst(UndefValue::get(LI.getType()),
11042                     Constant::getNullValue(Op->getType()), &LI);
11043       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11044     }
11045   } 
11046
11047   if (Constant *C = dyn_cast<Constant>(Op)) {
11048     // load null/undef -> undef
11049     // TODO: Consider a target hook for valid address spaces for this xform.
11050     if (isa<UndefValue>(C) || (C->isNullValue() && 
11051         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11052       // Insert a new store to null instruction before the load to indicate that
11053       // this code is not reachable.  We do this instead of inserting an
11054       // unreachable instruction directly because we cannot modify the CFG.
11055       new StoreInst(UndefValue::get(LI.getType()),
11056                     Constant::getNullValue(Op->getType()), &LI);
11057       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11058     }
11059
11060     // Instcombine load (constant global) into the value loaded.
11061     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11062       if (GV->isConstant() && !GV->isDeclaration())
11063         return ReplaceInstUsesWith(LI, GV->getInitializer());
11064
11065     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11066     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11067       if (CE->getOpcode() == Instruction::GetElementPtr) {
11068         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11069           if (GV->isConstant() && !GV->isDeclaration())
11070             if (Constant *V = 
11071                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11072               return ReplaceInstUsesWith(LI, V);
11073         if (CE->getOperand(0)->isNullValue()) {
11074           // Insert a new store to null instruction before the load to indicate
11075           // that this code is not reachable.  We do this instead of inserting
11076           // an unreachable instruction directly because we cannot modify the
11077           // CFG.
11078           new StoreInst(UndefValue::get(LI.getType()),
11079                         Constant::getNullValue(Op->getType()), &LI);
11080           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11081         }
11082
11083       } else if (CE->isCast()) {
11084         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11085           return Res;
11086       }
11087     }
11088   }
11089     
11090   // If this load comes from anywhere in a constant global, and if the global
11091   // is all undef or zero, we know what it loads.
11092   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11093     if (GV->isConstant() && GV->hasInitializer()) {
11094       if (GV->getInitializer()->isNullValue())
11095         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11096       else if (isa<UndefValue>(GV->getInitializer()))
11097         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11098     }
11099   }
11100
11101   if (Op->hasOneUse()) {
11102     // Change select and PHI nodes to select values instead of addresses: this
11103     // helps alias analysis out a lot, allows many others simplifications, and
11104     // exposes redundancy in the code.
11105     //
11106     // Note that we cannot do the transformation unless we know that the
11107     // introduced loads cannot trap!  Something like this is valid as long as
11108     // the condition is always false: load (select bool %C, int* null, int* %G),
11109     // but it would not be valid if we transformed it to load from null
11110     // unconditionally.
11111     //
11112     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11113       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11114       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11115           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11116         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11117                                      SI->getOperand(1)->getName()+".val"), LI);
11118         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11119                                      SI->getOperand(2)->getName()+".val"), LI);
11120         return SelectInst::Create(SI->getCondition(), V1, V2);
11121       }
11122
11123       // load (select (cond, null, P)) -> load P
11124       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11125         if (C->isNullValue()) {
11126           LI.setOperand(0, SI->getOperand(2));
11127           return &LI;
11128         }
11129
11130       // load (select (cond, P, null)) -> load P
11131       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11132         if (C->isNullValue()) {
11133           LI.setOperand(0, SI->getOperand(1));
11134           return &LI;
11135         }
11136     }
11137   }
11138   return 0;
11139 }
11140
11141 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11142 /// when possible.
11143 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11144   User *CI = cast<User>(SI.getOperand(1));
11145   Value *CastOp = CI->getOperand(0);
11146
11147   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11148   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11149   if (SrcTy == 0) return 0;
11150   
11151   const Type *SrcPTy = SrcTy->getElementType();
11152
11153   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11154     return 0;
11155   
11156   // If the source is an array, the code below will not succeed.  Check to
11157   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11158   // constants.
11159   if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11160     if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11161       if (ASrcTy->getNumElements() != 0) {
11162         Value* Idxs[2];
11163         Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11164         CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11165         SrcTy = cast<PointerType>(CastOp->getType());
11166         SrcPTy = SrcTy->getElementType();
11167       }
11168
11169   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11170     return 0;
11171   
11172   // If the pointers point into different address spaces or if they point to
11173   // values with different sizes, we can't do the transformation.
11174   if (SrcTy->getAddressSpace() != 
11175         cast<PointerType>(CI->getType())->getAddressSpace() ||
11176       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11177       IC.getTargetData().getTypeSizeInBits(DestPTy))
11178     return 0;
11179
11180   // Okay, we are casting from one integer or pointer type to another of
11181   // the same size.  Instead of casting the pointer before 
11182   // the store, cast the value to be stored.
11183   Value *NewCast;
11184   Value *SIOp0 = SI.getOperand(0);
11185   Instruction::CastOps opcode = Instruction::BitCast;
11186   const Type* CastSrcTy = SIOp0->getType();
11187   const Type* CastDstTy = SrcPTy;
11188   if (isa<PointerType>(CastDstTy)) {
11189     if (CastSrcTy->isInteger())
11190       opcode = Instruction::IntToPtr;
11191   } else if (isa<IntegerType>(CastDstTy)) {
11192     if (isa<PointerType>(SIOp0->getType()))
11193       opcode = Instruction::PtrToInt;
11194   }
11195   if (Constant *C = dyn_cast<Constant>(SIOp0))
11196     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11197   else
11198     NewCast = IC.InsertNewInstBefore(
11199       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11200       SI);
11201   return new StoreInst(NewCast, CastOp);
11202 }
11203
11204 /// equivalentAddressValues - Test if A and B will obviously have the same
11205 /// value. This includes recognizing that %t0 and %t1 will have the same
11206 /// value in code like this:
11207 ///   %t0 = getelementptr @a, 0, 3
11208 ///   store i32 0, i32* %t0
11209 ///   %t1 = getelementptr @a, 0, 3
11210 ///   %t2 = load i32* %t1
11211 ///
11212 static bool equivalentAddressValues(Value *A, Value *B) {
11213   // Test if the values are trivially equivalent.
11214   if (A == B) return true;
11215   
11216   // Test if the values come form identical arithmetic instructions.
11217   if (isa<BinaryOperator>(A) ||
11218       isa<CastInst>(A) ||
11219       isa<PHINode>(A) ||
11220       isa<GetElementPtrInst>(A))
11221     if (Instruction *BI = dyn_cast<Instruction>(B))
11222       if (cast<Instruction>(A)->isIdenticalTo(BI))
11223         return true;
11224   
11225   // Otherwise they may not be equivalent.
11226   return false;
11227 }
11228
11229 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11230   Value *Val = SI.getOperand(0);
11231   Value *Ptr = SI.getOperand(1);
11232
11233   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11234     EraseInstFromFunction(SI);
11235     ++NumCombined;
11236     return 0;
11237   }
11238   
11239   // If the RHS is an alloca with a single use, zapify the store, making the
11240   // alloca dead.
11241   if (Ptr->hasOneUse() && !SI.isVolatile()) {
11242     if (isa<AllocaInst>(Ptr)) {
11243       EraseInstFromFunction(SI);
11244       ++NumCombined;
11245       return 0;
11246     }
11247     
11248     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11249       if (isa<AllocaInst>(GEP->getOperand(0)) &&
11250           GEP->getOperand(0)->hasOneUse()) {
11251         EraseInstFromFunction(SI);
11252         ++NumCombined;
11253         return 0;
11254       }
11255   }
11256
11257   // Attempt to improve the alignment.
11258   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11259   if (KnownAlign >
11260       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11261                                 SI.getAlignment()))
11262     SI.setAlignment(KnownAlign);
11263
11264   // Do really simple DSE, to catch cases where there are several consequtive
11265   // stores to the same location, separated by a few arithmetic operations. This
11266   // situation often occurs with bitfield accesses.
11267   BasicBlock::iterator BBI = &SI;
11268   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11269        --ScanInsts) {
11270     --BBI;
11271     
11272     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11273       // Prev store isn't volatile, and stores to the same location?
11274       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11275                                                           SI.getOperand(1))) {
11276         ++NumDeadStore;
11277         ++BBI;
11278         EraseInstFromFunction(*PrevSI);
11279         continue;
11280       }
11281       break;
11282     }
11283     
11284     // If this is a load, we have to stop.  However, if the loaded value is from
11285     // the pointer we're loading and is producing the pointer we're storing,
11286     // then *this* store is dead (X = load P; store X -> P).
11287     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11288       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11289           !SI.isVolatile()) {
11290         EraseInstFromFunction(SI);
11291         ++NumCombined;
11292         return 0;
11293       }
11294       // Otherwise, this is a load from some other location.  Stores before it
11295       // may not be dead.
11296       break;
11297     }
11298     
11299     // Don't skip over loads or things that can modify memory.
11300     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11301       break;
11302   }
11303   
11304   
11305   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11306
11307   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11308   if (isa<ConstantPointerNull>(Ptr)) {
11309     if (!isa<UndefValue>(Val)) {
11310       SI.setOperand(0, UndefValue::get(Val->getType()));
11311       if (Instruction *U = dyn_cast<Instruction>(Val))
11312         AddToWorkList(U);  // Dropped a use.
11313       ++NumCombined;
11314     }
11315     return 0;  // Do not modify these!
11316   }
11317
11318   // store undef, Ptr -> noop
11319   if (isa<UndefValue>(Val)) {
11320     EraseInstFromFunction(SI);
11321     ++NumCombined;
11322     return 0;
11323   }
11324
11325   // If the pointer destination is a cast, see if we can fold the cast into the
11326   // source instead.
11327   if (isa<CastInst>(Ptr))
11328     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11329       return Res;
11330   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11331     if (CE->isCast())
11332       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11333         return Res;
11334
11335   
11336   // If this store is the last instruction in the basic block, and if the block
11337   // ends with an unconditional branch, try to move it to the successor block.
11338   BBI = &SI; ++BBI;
11339   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11340     if (BI->isUnconditional())
11341       if (SimplifyStoreAtEndOfBlock(SI))
11342         return 0;  // xform done!
11343   
11344   return 0;
11345 }
11346
11347 /// SimplifyStoreAtEndOfBlock - Turn things like:
11348 ///   if () { *P = v1; } else { *P = v2 }
11349 /// into a phi node with a store in the successor.
11350 ///
11351 /// Simplify things like:
11352 ///   *P = v1; if () { *P = v2; }
11353 /// into a phi node with a store in the successor.
11354 ///
11355 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11356   BasicBlock *StoreBB = SI.getParent();
11357   
11358   // Check to see if the successor block has exactly two incoming edges.  If
11359   // so, see if the other predecessor contains a store to the same location.
11360   // if so, insert a PHI node (if needed) and move the stores down.
11361   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11362   
11363   // Determine whether Dest has exactly two predecessors and, if so, compute
11364   // the other predecessor.
11365   pred_iterator PI = pred_begin(DestBB);
11366   BasicBlock *OtherBB = 0;
11367   if (*PI != StoreBB)
11368     OtherBB = *PI;
11369   ++PI;
11370   if (PI == pred_end(DestBB))
11371     return false;
11372   
11373   if (*PI != StoreBB) {
11374     if (OtherBB)
11375       return false;
11376     OtherBB = *PI;
11377   }
11378   if (++PI != pred_end(DestBB))
11379     return false;
11380
11381   // Bail out if all the relevant blocks aren't distinct (this can happen,
11382   // for example, if SI is in an infinite loop)
11383   if (StoreBB == DestBB || OtherBB == DestBB)
11384     return false;
11385
11386   // Verify that the other block ends in a branch and is not otherwise empty.
11387   BasicBlock::iterator BBI = OtherBB->getTerminator();
11388   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11389   if (!OtherBr || BBI == OtherBB->begin())
11390     return false;
11391   
11392   // If the other block ends in an unconditional branch, check for the 'if then
11393   // else' case.  there is an instruction before the branch.
11394   StoreInst *OtherStore = 0;
11395   if (OtherBr->isUnconditional()) {
11396     // If this isn't a store, or isn't a store to the same location, bail out.
11397     --BBI;
11398     OtherStore = dyn_cast<StoreInst>(BBI);
11399     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11400       return false;
11401   } else {
11402     // Otherwise, the other block ended with a conditional branch. If one of the
11403     // destinations is StoreBB, then we have the if/then case.
11404     if (OtherBr->getSuccessor(0) != StoreBB && 
11405         OtherBr->getSuccessor(1) != StoreBB)
11406       return false;
11407     
11408     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11409     // if/then triangle.  See if there is a store to the same ptr as SI that
11410     // lives in OtherBB.
11411     for (;; --BBI) {
11412       // Check to see if we find the matching store.
11413       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11414         if (OtherStore->getOperand(1) != SI.getOperand(1))
11415           return false;
11416         break;
11417       }
11418       // If we find something that may be using or overwriting the stored
11419       // value, or if we run out of instructions, we can't do the xform.
11420       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11421           BBI == OtherBB->begin())
11422         return false;
11423     }
11424     
11425     // In order to eliminate the store in OtherBr, we have to
11426     // make sure nothing reads or overwrites the stored value in
11427     // StoreBB.
11428     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11429       // FIXME: This should really be AA driven.
11430       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11431         return false;
11432     }
11433   }
11434   
11435   // Insert a PHI node now if we need it.
11436   Value *MergedVal = OtherStore->getOperand(0);
11437   if (MergedVal != SI.getOperand(0)) {
11438     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11439     PN->reserveOperandSpace(2);
11440     PN->addIncoming(SI.getOperand(0), SI.getParent());
11441     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11442     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11443   }
11444   
11445   // Advance to a place where it is safe to insert the new store and
11446   // insert it.
11447   BBI = DestBB->getFirstNonPHI();
11448   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11449                                     OtherStore->isVolatile()), *BBI);
11450   
11451   // Nuke the old stores.
11452   EraseInstFromFunction(SI);
11453   EraseInstFromFunction(*OtherStore);
11454   ++NumCombined;
11455   return true;
11456 }
11457
11458
11459 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11460   // Change br (not X), label True, label False to: br X, label False, True
11461   Value *X = 0;
11462   BasicBlock *TrueDest;
11463   BasicBlock *FalseDest;
11464   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11465       !isa<Constant>(X)) {
11466     // Swap Destinations and condition...
11467     BI.setCondition(X);
11468     BI.setSuccessor(0, FalseDest);
11469     BI.setSuccessor(1, TrueDest);
11470     return &BI;
11471   }
11472
11473   // Cannonicalize fcmp_one -> fcmp_oeq
11474   FCmpInst::Predicate FPred; Value *Y;
11475   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11476                              TrueDest, FalseDest)))
11477     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11478          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11479       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11480       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11481       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11482       NewSCC->takeName(I);
11483       // Swap Destinations and condition...
11484       BI.setCondition(NewSCC);
11485       BI.setSuccessor(0, FalseDest);
11486       BI.setSuccessor(1, TrueDest);
11487       RemoveFromWorkList(I);
11488       I->eraseFromParent();
11489       AddToWorkList(NewSCC);
11490       return &BI;
11491     }
11492
11493   // Cannonicalize icmp_ne -> icmp_eq
11494   ICmpInst::Predicate IPred;
11495   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11496                       TrueDest, FalseDest)))
11497     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11498          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11499          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11500       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11501       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11502       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11503       NewSCC->takeName(I);
11504       // Swap Destinations and condition...
11505       BI.setCondition(NewSCC);
11506       BI.setSuccessor(0, FalseDest);
11507       BI.setSuccessor(1, TrueDest);
11508       RemoveFromWorkList(I);
11509       I->eraseFromParent();;
11510       AddToWorkList(NewSCC);
11511       return &BI;
11512     }
11513
11514   return 0;
11515 }
11516
11517 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11518   Value *Cond = SI.getCondition();
11519   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11520     if (I->getOpcode() == Instruction::Add)
11521       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11522         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11523         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11524           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11525                                                 AddRHS));
11526         SI.setOperand(0, I->getOperand(0));
11527         AddToWorkList(I);
11528         return &SI;
11529       }
11530   }
11531   return 0;
11532 }
11533
11534 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11535   Value *Agg = EV.getAggregateOperand();
11536
11537   if (!EV.hasIndices())
11538     return ReplaceInstUsesWith(EV, Agg);
11539
11540   if (Constant *C = dyn_cast<Constant>(Agg)) {
11541     if (isa<UndefValue>(C))
11542       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11543       
11544     if (isa<ConstantAggregateZero>(C))
11545       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11546
11547     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11548       // Extract the element indexed by the first index out of the constant
11549       Value *V = C->getOperand(*EV.idx_begin());
11550       if (EV.getNumIndices() > 1)
11551         // Extract the remaining indices out of the constant indexed by the
11552         // first index
11553         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11554       else
11555         return ReplaceInstUsesWith(EV, V);
11556     }
11557     return 0; // Can't handle other constants
11558   } 
11559   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11560     // We're extracting from an insertvalue instruction, compare the indices
11561     const unsigned *exti, *exte, *insi, *inse;
11562     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11563          exte = EV.idx_end(), inse = IV->idx_end();
11564          exti != exte && insi != inse;
11565          ++exti, ++insi) {
11566       if (*insi != *exti)
11567         // The insert and extract both reference distinctly different elements.
11568         // This means the extract is not influenced by the insert, and we can
11569         // replace the aggregate operand of the extract with the aggregate
11570         // operand of the insert. i.e., replace
11571         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11572         // %E = extractvalue { i32, { i32 } } %I, 0
11573         // with
11574         // %E = extractvalue { i32, { i32 } } %A, 0
11575         return ExtractValueInst::Create(IV->getAggregateOperand(),
11576                                         EV.idx_begin(), EV.idx_end());
11577     }
11578     if (exti == exte && insi == inse)
11579       // Both iterators are at the end: Index lists are identical. Replace
11580       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11581       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11582       // with "i32 42"
11583       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11584     if (exti == exte) {
11585       // The extract list is a prefix of the insert list. i.e. replace
11586       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11587       // %E = extractvalue { i32, { i32 } } %I, 1
11588       // with
11589       // %X = extractvalue { i32, { i32 } } %A, 1
11590       // %E = insertvalue { i32 } %X, i32 42, 0
11591       // by switching the order of the insert and extract (though the
11592       // insertvalue should be left in, since it may have other uses).
11593       Value *NewEV = InsertNewInstBefore(
11594         ExtractValueInst::Create(IV->getAggregateOperand(),
11595                                  EV.idx_begin(), EV.idx_end()),
11596         EV);
11597       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11598                                      insi, inse);
11599     }
11600     if (insi == inse)
11601       // The insert list is a prefix of the extract list
11602       // We can simply remove the common indices from the extract and make it
11603       // operate on the inserted value instead of the insertvalue result.
11604       // i.e., replace
11605       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11606       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11607       // with
11608       // %E extractvalue { i32 } { i32 42 }, 0
11609       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11610                                       exti, exte);
11611   }
11612   // Can't simplify extracts from other values. Note that nested extracts are
11613   // already simplified implicitely by the above (extract ( extract (insert) )
11614   // will be translated into extract ( insert ( extract ) ) first and then just
11615   // the value inserted, if appropriate).
11616   return 0;
11617 }
11618
11619 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11620 /// is to leave as a vector operation.
11621 static bool CheapToScalarize(Value *V, bool isConstant) {
11622   if (isa<ConstantAggregateZero>(V)) 
11623     return true;
11624   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11625     if (isConstant) return true;
11626     // If all elts are the same, we can extract.
11627     Constant *Op0 = C->getOperand(0);
11628     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11629       if (C->getOperand(i) != Op0)
11630         return false;
11631     return true;
11632   }
11633   Instruction *I = dyn_cast<Instruction>(V);
11634   if (!I) return false;
11635   
11636   // Insert element gets simplified to the inserted element or is deleted if
11637   // this is constant idx extract element and its a constant idx insertelt.
11638   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11639       isa<ConstantInt>(I->getOperand(2)))
11640     return true;
11641   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11642     return true;
11643   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11644     if (BO->hasOneUse() &&
11645         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11646          CheapToScalarize(BO->getOperand(1), isConstant)))
11647       return true;
11648   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11649     if (CI->hasOneUse() &&
11650         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11651          CheapToScalarize(CI->getOperand(1), isConstant)))
11652       return true;
11653   
11654   return false;
11655 }
11656
11657 /// Read and decode a shufflevector mask.
11658 ///
11659 /// It turns undef elements into values that are larger than the number of
11660 /// elements in the input.
11661 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11662   unsigned NElts = SVI->getType()->getNumElements();
11663   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11664     return std::vector<unsigned>(NElts, 0);
11665   if (isa<UndefValue>(SVI->getOperand(2)))
11666     return std::vector<unsigned>(NElts, 2*NElts);
11667
11668   std::vector<unsigned> Result;
11669   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11670   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11671     if (isa<UndefValue>(*i))
11672       Result.push_back(NElts*2);  // undef -> 8
11673     else
11674       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
11675   return Result;
11676 }
11677
11678 /// FindScalarElement - Given a vector and an element number, see if the scalar
11679 /// value is already around as a register, for example if it were inserted then
11680 /// extracted from the vector.
11681 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11682   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11683   const VectorType *PTy = cast<VectorType>(V->getType());
11684   unsigned Width = PTy->getNumElements();
11685   if (EltNo >= Width)  // Out of range access.
11686     return UndefValue::get(PTy->getElementType());
11687   
11688   if (isa<UndefValue>(V))
11689     return UndefValue::get(PTy->getElementType());
11690   else if (isa<ConstantAggregateZero>(V))
11691     return Constant::getNullValue(PTy->getElementType());
11692   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11693     return CP->getOperand(EltNo);
11694   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11695     // If this is an insert to a variable element, we don't know what it is.
11696     if (!isa<ConstantInt>(III->getOperand(2))) 
11697       return 0;
11698     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11699     
11700     // If this is an insert to the element we are looking for, return the
11701     // inserted value.
11702     if (EltNo == IIElt) 
11703       return III->getOperand(1);
11704     
11705     // Otherwise, the insertelement doesn't modify the value, recurse on its
11706     // vector input.
11707     return FindScalarElement(III->getOperand(0), EltNo);
11708   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11709     unsigned LHSWidth =
11710       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11711     unsigned InEl = getShuffleMask(SVI)[EltNo];
11712     if (InEl < LHSWidth)
11713       return FindScalarElement(SVI->getOperand(0), InEl);
11714     else if (InEl < LHSWidth*2)
11715       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
11716     else
11717       return UndefValue::get(PTy->getElementType());
11718   }
11719   
11720   // Otherwise, we don't know.
11721   return 0;
11722 }
11723
11724 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11725   // If vector val is undef, replace extract with scalar undef.
11726   if (isa<UndefValue>(EI.getOperand(0)))
11727     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11728
11729   // If vector val is constant 0, replace extract with scalar 0.
11730   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11731     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11732   
11733   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11734     // If vector val is constant with all elements the same, replace EI with
11735     // that element. When the elements are not identical, we cannot replace yet
11736     // (we do that below, but only when the index is constant).
11737     Constant *op0 = C->getOperand(0);
11738     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11739       if (C->getOperand(i) != op0) {
11740         op0 = 0; 
11741         break;
11742       }
11743     if (op0)
11744       return ReplaceInstUsesWith(EI, op0);
11745   }
11746   
11747   // If extracting a specified index from the vector, see if we can recursively
11748   // find a previously computed scalar that was inserted into the vector.
11749   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11750     unsigned IndexVal = IdxC->getZExtValue();
11751     unsigned VectorWidth = 
11752       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11753       
11754     // If this is extracting an invalid index, turn this into undef, to avoid
11755     // crashing the code below.
11756     if (IndexVal >= VectorWidth)
11757       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11758     
11759     // This instruction only demands the single element from the input vector.
11760     // If the input vector has a single use, simplify it based on this use
11761     // property.
11762     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11763       uint64_t UndefElts;
11764       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11765                                                 1 << IndexVal,
11766                                                 UndefElts)) {
11767         EI.setOperand(0, V);
11768         return &EI;
11769       }
11770     }
11771     
11772     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11773       return ReplaceInstUsesWith(EI, Elt);
11774     
11775     // If the this extractelement is directly using a bitcast from a vector of
11776     // the same number of elements, see if we can find the source element from
11777     // it.  In this case, we will end up needing to bitcast the scalars.
11778     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11779       if (const VectorType *VT = 
11780               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11781         if (VT->getNumElements() == VectorWidth)
11782           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11783             return new BitCastInst(Elt, EI.getType());
11784     }
11785   }
11786   
11787   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11788     if (I->hasOneUse()) {
11789       // Push extractelement into predecessor operation if legal and
11790       // profitable to do so
11791       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11792         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11793         if (CheapToScalarize(BO, isConstantElt)) {
11794           ExtractElementInst *newEI0 = 
11795             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11796                                    EI.getName()+".lhs");
11797           ExtractElementInst *newEI1 =
11798             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11799                                    EI.getName()+".rhs");
11800           InsertNewInstBefore(newEI0, EI);
11801           InsertNewInstBefore(newEI1, EI);
11802           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11803         }
11804       } else if (isa<LoadInst>(I)) {
11805         unsigned AS = 
11806           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11807         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11808                                          PointerType::get(EI.getType(), AS),EI);
11809         GetElementPtrInst *GEP =
11810           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11811         InsertNewInstBefore(GEP, EI);
11812         return new LoadInst(GEP);
11813       }
11814     }
11815     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11816       // Extracting the inserted element?
11817       if (IE->getOperand(2) == EI.getOperand(1))
11818         return ReplaceInstUsesWith(EI, IE->getOperand(1));
11819       // If the inserted and extracted elements are constants, they must not
11820       // be the same value, extract from the pre-inserted value instead.
11821       if (isa<Constant>(IE->getOperand(2)) &&
11822           isa<Constant>(EI.getOperand(1))) {
11823         AddUsesToWorkList(EI);
11824         EI.setOperand(0, IE->getOperand(0));
11825         return &EI;
11826       }
11827     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11828       // If this is extracting an element from a shufflevector, figure out where
11829       // it came from and extract from the appropriate input element instead.
11830       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11831         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11832         Value *Src;
11833         unsigned LHSWidth =
11834           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11835
11836         if (SrcIdx < LHSWidth)
11837           Src = SVI->getOperand(0);
11838         else if (SrcIdx < LHSWidth*2) {
11839           SrcIdx -= LHSWidth;
11840           Src = SVI->getOperand(1);
11841         } else {
11842           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11843         }
11844         return new ExtractElementInst(Src, SrcIdx);
11845       }
11846     }
11847   }
11848   return 0;
11849 }
11850
11851 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11852 /// elements from either LHS or RHS, return the shuffle mask and true. 
11853 /// Otherwise, return false.
11854 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11855                                          std::vector<Constant*> &Mask) {
11856   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11857          "Invalid CollectSingleShuffleElements");
11858   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11859
11860   if (isa<UndefValue>(V)) {
11861     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11862     return true;
11863   } else if (V == LHS) {
11864     for (unsigned i = 0; i != NumElts; ++i)
11865       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11866     return true;
11867   } else if (V == RHS) {
11868     for (unsigned i = 0; i != NumElts; ++i)
11869       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11870     return true;
11871   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11872     // If this is an insert of an extract from some other vector, include it.
11873     Value *VecOp    = IEI->getOperand(0);
11874     Value *ScalarOp = IEI->getOperand(1);
11875     Value *IdxOp    = IEI->getOperand(2);
11876     
11877     if (!isa<ConstantInt>(IdxOp))
11878       return false;
11879     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11880     
11881     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
11882       // Okay, we can handle this if the vector we are insertinting into is
11883       // transitively ok.
11884       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11885         // If so, update the mask to reflect the inserted undef.
11886         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11887         return true;
11888       }      
11889     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11890       if (isa<ConstantInt>(EI->getOperand(1)) &&
11891           EI->getOperand(0)->getType() == V->getType()) {
11892         unsigned ExtractedIdx =
11893           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11894         
11895         // This must be extracting from either LHS or RHS.
11896         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11897           // Okay, we can handle this if the vector we are insertinting into is
11898           // transitively ok.
11899           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11900             // If so, update the mask to reflect the inserted value.
11901             if (EI->getOperand(0) == LHS) {
11902               Mask[InsertedIdx % NumElts] = 
11903                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11904             } else {
11905               assert(EI->getOperand(0) == RHS);
11906               Mask[InsertedIdx % NumElts] = 
11907                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11908               
11909             }
11910             return true;
11911           }
11912         }
11913       }
11914     }
11915   }
11916   // TODO: Handle shufflevector here!
11917   
11918   return false;
11919 }
11920
11921 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11922 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
11923 /// that computes V and the LHS value of the shuffle.
11924 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11925                                      Value *&RHS) {
11926   assert(isa<VectorType>(V->getType()) && 
11927          (RHS == 0 || V->getType() == RHS->getType()) &&
11928          "Invalid shuffle!");
11929   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11930
11931   if (isa<UndefValue>(V)) {
11932     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11933     return V;
11934   } else if (isa<ConstantAggregateZero>(V)) {
11935     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11936     return V;
11937   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11938     // If this is an insert of an extract from some other vector, include it.
11939     Value *VecOp    = IEI->getOperand(0);
11940     Value *ScalarOp = IEI->getOperand(1);
11941     Value *IdxOp    = IEI->getOperand(2);
11942     
11943     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11944       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11945           EI->getOperand(0)->getType() == V->getType()) {
11946         unsigned ExtractedIdx =
11947           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11948         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11949         
11950         // Either the extracted from or inserted into vector must be RHSVec,
11951         // otherwise we'd end up with a shuffle of three inputs.
11952         if (EI->getOperand(0) == RHS || RHS == 0) {
11953           RHS = EI->getOperand(0);
11954           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11955           Mask[InsertedIdx % NumElts] = 
11956             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11957           return V;
11958         }
11959         
11960         if (VecOp == RHS) {
11961           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11962           // Everything but the extracted element is replaced with the RHS.
11963           for (unsigned i = 0; i != NumElts; ++i) {
11964             if (i != InsertedIdx)
11965               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11966           }
11967           return V;
11968         }
11969         
11970         // If this insertelement is a chain that comes from exactly these two
11971         // vectors, return the vector and the effective shuffle.
11972         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11973           return EI->getOperand(0);
11974         
11975       }
11976     }
11977   }
11978   // TODO: Handle shufflevector here!
11979   
11980   // Otherwise, can't do anything fancy.  Return an identity vector.
11981   for (unsigned i = 0; i != NumElts; ++i)
11982     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11983   return V;
11984 }
11985
11986 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11987   Value *VecOp    = IE.getOperand(0);
11988   Value *ScalarOp = IE.getOperand(1);
11989   Value *IdxOp    = IE.getOperand(2);
11990   
11991   // Inserting an undef or into an undefined place, remove this.
11992   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11993     ReplaceInstUsesWith(IE, VecOp);
11994   
11995   // If the inserted element was extracted from some other vector, and if the 
11996   // indexes are constant, try to turn this into a shufflevector operation.
11997   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11998     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11999         EI->getOperand(0)->getType() == IE.getType()) {
12000       unsigned NumVectorElts = IE.getType()->getNumElements();
12001       unsigned ExtractedIdx =
12002         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12003       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12004       
12005       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12006         return ReplaceInstUsesWith(IE, VecOp);
12007       
12008       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12009         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12010       
12011       // If we are extracting a value from a vector, then inserting it right
12012       // back into the same place, just use the input vector.
12013       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12014         return ReplaceInstUsesWith(IE, VecOp);      
12015       
12016       // We could theoretically do this for ANY input.  However, doing so could
12017       // turn chains of insertelement instructions into a chain of shufflevector
12018       // instructions, and right now we do not merge shufflevectors.  As such,
12019       // only do this in a situation where it is clear that there is benefit.
12020       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12021         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12022         // the values of VecOp, except then one read from EIOp0.
12023         // Build a new shuffle mask.
12024         std::vector<Constant*> Mask;
12025         if (isa<UndefValue>(VecOp))
12026           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12027         else {
12028           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12029           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12030                                                        NumVectorElts));
12031         } 
12032         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12033         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12034                                      ConstantVector::get(Mask));
12035       }
12036       
12037       // If this insertelement isn't used by some other insertelement, turn it
12038       // (and any insertelements it points to), into one big shuffle.
12039       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12040         std::vector<Constant*> Mask;
12041         Value *RHS = 0;
12042         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12043         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12044         // We now have a shuffle of LHS, RHS, Mask.
12045         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12046       }
12047     }
12048   }
12049
12050   return 0;
12051 }
12052
12053
12054 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12055   Value *LHS = SVI.getOperand(0);
12056   Value *RHS = SVI.getOperand(1);
12057   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12058
12059   bool MadeChange = false;
12060
12061   // Undefined shuffle mask -> undefined value.
12062   if (isa<UndefValue>(SVI.getOperand(2)))
12063     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12064
12065   uint64_t UndefElts;
12066   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12067
12068   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12069     return 0;
12070
12071   uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
12072   if (VWidth <= 64 &&
12073       SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12074     LHS = SVI.getOperand(0);
12075     RHS = SVI.getOperand(1);
12076     MadeChange = true;
12077   }
12078   
12079   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12080   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12081   if (LHS == RHS || isa<UndefValue>(LHS)) {
12082     if (isa<UndefValue>(LHS) && LHS == RHS) {
12083       // shuffle(undef,undef,mask) -> undef.
12084       return ReplaceInstUsesWith(SVI, LHS);
12085     }
12086     
12087     // Remap any references to RHS to use LHS.
12088     std::vector<Constant*> Elts;
12089     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12090       if (Mask[i] >= 2*e)
12091         Elts.push_back(UndefValue::get(Type::Int32Ty));
12092       else {
12093         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12094             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12095           Mask[i] = 2*e;     // Turn into undef.
12096           Elts.push_back(UndefValue::get(Type::Int32Ty));
12097         } else {
12098           Mask[i] = Mask[i] % e;  // Force to LHS.
12099           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12100         }
12101       }
12102     }
12103     SVI.setOperand(0, SVI.getOperand(1));
12104     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12105     SVI.setOperand(2, ConstantVector::get(Elts));
12106     LHS = SVI.getOperand(0);
12107     RHS = SVI.getOperand(1);
12108     MadeChange = true;
12109   }
12110   
12111   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12112   bool isLHSID = true, isRHSID = true;
12113     
12114   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12115     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12116     // Is this an identity shuffle of the LHS value?
12117     isLHSID &= (Mask[i] == i);
12118       
12119     // Is this an identity shuffle of the RHS value?
12120     isRHSID &= (Mask[i]-e == i);
12121   }
12122
12123   // Eliminate identity shuffles.
12124   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12125   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12126   
12127   // If the LHS is a shufflevector itself, see if we can combine it with this
12128   // one without producing an unusual shuffle.  Here we are really conservative:
12129   // we are absolutely afraid of producing a shuffle mask not in the input
12130   // program, because the code gen may not be smart enough to turn a merged
12131   // shuffle into two specific shuffles: it may produce worse code.  As such,
12132   // we only merge two shuffles if the result is one of the two input shuffle
12133   // masks.  In this case, merging the shuffles just removes one instruction,
12134   // which we know is safe.  This is good for things like turning:
12135   // (splat(splat)) -> splat.
12136   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12137     if (isa<UndefValue>(RHS)) {
12138       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12139
12140       std::vector<unsigned> NewMask;
12141       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12142         if (Mask[i] >= 2*e)
12143           NewMask.push_back(2*e);
12144         else
12145           NewMask.push_back(LHSMask[Mask[i]]);
12146       
12147       // If the result mask is equal to the src shuffle or this shuffle mask, do
12148       // the replacement.
12149       if (NewMask == LHSMask || NewMask == Mask) {
12150         std::vector<Constant*> Elts;
12151         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12152           if (NewMask[i] >= e*2) {
12153             Elts.push_back(UndefValue::get(Type::Int32Ty));
12154           } else {
12155             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12156           }
12157         }
12158         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12159                                      LHSSVI->getOperand(1),
12160                                      ConstantVector::get(Elts));
12161       }
12162     }
12163   }
12164
12165   return MadeChange ? &SVI : 0;
12166 }
12167
12168
12169
12170
12171 /// TryToSinkInstruction - Try to move the specified instruction from its
12172 /// current block into the beginning of DestBlock, which can only happen if it's
12173 /// safe to move the instruction past all of the instructions between it and the
12174 /// end of its block.
12175 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12176   assert(I->hasOneUse() && "Invariants didn't hold!");
12177
12178   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12179   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12180     return false;
12181
12182   // Do not sink alloca instructions out of the entry block.
12183   if (isa<AllocaInst>(I) && I->getParent() ==
12184         &DestBlock->getParent()->getEntryBlock())
12185     return false;
12186
12187   // We can only sink load instructions if there is nothing between the load and
12188   // the end of block that could change the value.
12189   if (I->mayReadFromMemory()) {
12190     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12191          Scan != E; ++Scan)
12192       if (Scan->mayWriteToMemory())
12193         return false;
12194   }
12195
12196   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12197
12198   I->moveBefore(InsertPos);
12199   ++NumSunkInst;
12200   return true;
12201 }
12202
12203
12204 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12205 /// all reachable code to the worklist.
12206 ///
12207 /// This has a couple of tricks to make the code faster and more powerful.  In
12208 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12209 /// them to the worklist (this significantly speeds up instcombine on code where
12210 /// many instructions are dead or constant).  Additionally, if we find a branch
12211 /// whose condition is a known constant, we only visit the reachable successors.
12212 ///
12213 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12214                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12215                                        InstCombiner &IC,
12216                                        const TargetData *TD) {
12217   SmallVector<BasicBlock*, 256> Worklist;
12218   Worklist.push_back(BB);
12219
12220   while (!Worklist.empty()) {
12221     BB = Worklist.back();
12222     Worklist.pop_back();
12223     
12224     // We have now visited this block!  If we've already been here, ignore it.
12225     if (!Visited.insert(BB)) continue;
12226
12227     DbgInfoIntrinsic *DBI_Prev = NULL;
12228     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12229       Instruction *Inst = BBI++;
12230       
12231       // DCE instruction if trivially dead.
12232       if (isInstructionTriviallyDead(Inst)) {
12233         ++NumDeadInst;
12234         DOUT << "IC: DCE: " << *Inst;
12235         Inst->eraseFromParent();
12236         continue;
12237       }
12238       
12239       // ConstantProp instruction if trivially constant.
12240       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12241         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12242         Inst->replaceAllUsesWith(C);
12243         ++NumConstProp;
12244         Inst->eraseFromParent();
12245         continue;
12246       }
12247      
12248       // If there are two consecutive llvm.dbg.stoppoint calls then
12249       // it is likely that the optimizer deleted code in between these
12250       // two intrinsics. 
12251       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12252       if (DBI_Next) {
12253         if (DBI_Prev
12254             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12255             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12256           IC.RemoveFromWorkList(DBI_Prev);
12257           DBI_Prev->eraseFromParent();
12258         }
12259         DBI_Prev = DBI_Next;
12260       }
12261
12262       IC.AddToWorkList(Inst);
12263     }
12264
12265     // Recursively visit successors.  If this is a branch or switch on a
12266     // constant, only visit the reachable successor.
12267     TerminatorInst *TI = BB->getTerminator();
12268     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12269       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12270         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12271         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12272         Worklist.push_back(ReachableBB);
12273         continue;
12274       }
12275     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12276       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12277         // See if this is an explicit destination.
12278         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12279           if (SI->getCaseValue(i) == Cond) {
12280             BasicBlock *ReachableBB = SI->getSuccessor(i);
12281             Worklist.push_back(ReachableBB);
12282             continue;
12283           }
12284         
12285         // Otherwise it is the default destination.
12286         Worklist.push_back(SI->getSuccessor(0));
12287         continue;
12288       }
12289     }
12290     
12291     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12292       Worklist.push_back(TI->getSuccessor(i));
12293   }
12294 }
12295
12296 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12297   bool Changed = false;
12298   TD = &getAnalysis<TargetData>();
12299   
12300   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12301              << F.getNameStr() << "\n");
12302
12303   {
12304     // Do a depth-first traversal of the function, populate the worklist with
12305     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12306     // track of which blocks we visit.
12307     SmallPtrSet<BasicBlock*, 64> Visited;
12308     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12309
12310     // Do a quick scan over the function.  If we find any blocks that are
12311     // unreachable, remove any instructions inside of them.  This prevents
12312     // the instcombine code from having to deal with some bad special cases.
12313     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12314       if (!Visited.count(BB)) {
12315         Instruction *Term = BB->getTerminator();
12316         while (Term != BB->begin()) {   // Remove instrs bottom-up
12317           BasicBlock::iterator I = Term; --I;
12318
12319           DOUT << "IC: DCE: " << *I;
12320           ++NumDeadInst;
12321
12322           if (!I->use_empty())
12323             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12324           I->eraseFromParent();
12325         }
12326       }
12327   }
12328
12329   while (!Worklist.empty()) {
12330     Instruction *I = RemoveOneFromWorkList();
12331     if (I == 0) continue;  // skip null values.
12332
12333     // Check to see if we can DCE the instruction.
12334     if (isInstructionTriviallyDead(I)) {
12335       // Add operands to the worklist.
12336       if (I->getNumOperands() < 4)
12337         AddUsesToWorkList(*I);
12338       ++NumDeadInst;
12339
12340       DOUT << "IC: DCE: " << *I;
12341
12342       I->eraseFromParent();
12343       RemoveFromWorkList(I);
12344       continue;
12345     }
12346
12347     // Instruction isn't dead, see if we can constant propagate it.
12348     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12349       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12350
12351       // Add operands to the worklist.
12352       AddUsesToWorkList(*I);
12353       ReplaceInstUsesWith(*I, C);
12354
12355       ++NumConstProp;
12356       I->eraseFromParent();
12357       RemoveFromWorkList(I);
12358       continue;
12359     }
12360
12361     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12362       // See if we can constant fold its operands.
12363       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
12364         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
12365           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12366             i->set(NewC);
12367         }
12368       }
12369     }
12370
12371     // See if we can trivially sink this instruction to a successor basic block.
12372     if (I->hasOneUse()) {
12373       BasicBlock *BB = I->getParent();
12374       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12375       if (UserParent != BB) {
12376         bool UserIsSuccessor = false;
12377         // See if the user is one of our successors.
12378         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12379           if (*SI == UserParent) {
12380             UserIsSuccessor = true;
12381             break;
12382           }
12383
12384         // If the user is one of our immediate successors, and if that successor
12385         // only has us as a predecessors (we'd have to split the critical edge
12386         // otherwise), we can keep going.
12387         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12388             next(pred_begin(UserParent)) == pred_end(UserParent))
12389           // Okay, the CFG is simple enough, try to sink this instruction.
12390           Changed |= TryToSinkInstruction(I, UserParent);
12391       }
12392     }
12393
12394     // Now that we have an instruction, try combining it to simplify it...
12395 #ifndef NDEBUG
12396     std::string OrigI;
12397 #endif
12398     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12399     if (Instruction *Result = visit(*I)) {
12400       ++NumCombined;
12401       // Should we replace the old instruction with a new one?
12402       if (Result != I) {
12403         DOUT << "IC: Old = " << *I
12404              << "    New = " << *Result;
12405
12406         // Everything uses the new instruction now.
12407         I->replaceAllUsesWith(Result);
12408
12409         // Push the new instruction and any users onto the worklist.
12410         AddToWorkList(Result);
12411         AddUsersToWorkList(*Result);
12412
12413         // Move the name to the new instruction first.
12414         Result->takeName(I);
12415
12416         // Insert the new instruction into the basic block...
12417         BasicBlock *InstParent = I->getParent();
12418         BasicBlock::iterator InsertPos = I;
12419
12420         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12421           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12422             ++InsertPos;
12423
12424         InstParent->getInstList().insert(InsertPos, Result);
12425
12426         // Make sure that we reprocess all operands now that we reduced their
12427         // use counts.
12428         AddUsesToWorkList(*I);
12429
12430         // Instructions can end up on the worklist more than once.  Make sure
12431         // we do not process an instruction that has been deleted.
12432         RemoveFromWorkList(I);
12433
12434         // Erase the old instruction.
12435         InstParent->getInstList().erase(I);
12436       } else {
12437 #ifndef NDEBUG
12438         DOUT << "IC: Mod = " << OrigI
12439              << "    New = " << *I;
12440 #endif
12441
12442         // If the instruction was modified, it's possible that it is now dead.
12443         // if so, remove it.
12444         if (isInstructionTriviallyDead(I)) {
12445           // Make sure we process all operands now that we are reducing their
12446           // use counts.
12447           AddUsesToWorkList(*I);
12448
12449           // Instructions may end up in the worklist more than once.  Erase all
12450           // occurrences of this instruction.
12451           RemoveFromWorkList(I);
12452           I->eraseFromParent();
12453         } else {
12454           AddToWorkList(I);
12455           AddUsersToWorkList(*I);
12456         }
12457       }
12458       Changed = true;
12459     }
12460   }
12461
12462   assert(WorklistMap.empty() && "Worklist empty, but map not?");
12463     
12464   // Do an explicit clear, this shrinks the map if needed.
12465   WorklistMap.clear();
12466   return Changed;
12467 }
12468
12469
12470 bool InstCombiner::runOnFunction(Function &F) {
12471   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12472   
12473   bool EverMadeChange = false;
12474
12475   // Iterate while there is work to do.
12476   unsigned Iteration = 0;
12477   while (DoOneIteration(F, Iteration++))
12478     EverMadeChange = true;
12479   return EverMadeChange;
12480 }
12481
12482 FunctionPass *llvm::createInstructionCombiningPass() {
12483   return new InstCombiner();
12484 }