Make all the vector elements positive in an srem of constant vector.
[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,
398                                     int &NumCastsRemoved);
399     unsigned GetOrEnforceKnownAlignment(Value *V,
400                                         unsigned PrefAlign = 0);
401
402   };
403 }
404
405 char InstCombiner::ID = 0;
406 static RegisterPass<InstCombiner>
407 X("instcombine", "Combine redundant instructions");
408
409 // getComplexity:  Assign a complexity or rank value to LLVM Values...
410 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
411 static unsigned getComplexity(Value *V) {
412   if (isa<Instruction>(V)) {
413     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
414       return 3;
415     return 4;
416   }
417   if (isa<Argument>(V)) return 3;
418   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
419 }
420
421 // isOnlyUse - Return true if this instruction will be deleted if we stop using
422 // it.
423 static bool isOnlyUse(Value *V) {
424   return V->hasOneUse() || isa<Constant>(V);
425 }
426
427 // getPromotedType - Return the specified type promoted as it would be to pass
428 // though a va_arg area...
429 static const Type *getPromotedType(const Type *Ty) {
430   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
431     if (ITy->getBitWidth() < 32)
432       return Type::Int32Ty;
433   }
434   return Ty;
435 }
436
437 /// getBitCastOperand - If the specified operand is a CastInst, a constant
438 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
439 /// operand value, otherwise return null.
440 static Value *getBitCastOperand(Value *V) {
441   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
442     // BitCastInst?
443     return I->getOperand(0);
444   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
445     // GetElementPtrInst?
446     if (GEP->hasAllZeroIndices())
447       return GEP->getOperand(0);
448   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
449     if (CE->getOpcode() == Instruction::BitCast)
450       // BitCast ConstantExp?
451       return CE->getOperand(0);
452     else if (CE->getOpcode() == Instruction::GetElementPtr) {
453       // GetElementPtr ConstantExp?
454       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
455            I != E; ++I) {
456         ConstantInt *CI = dyn_cast<ConstantInt>(I);
457         if (!CI || !CI->isZero())
458           // Any non-zero indices? Not cast-like.
459           return 0;
460       }
461       // All-zero indices? This is just like casting.
462       return CE->getOperand(0);
463     }
464   }
465   return 0;
466 }
467
468 /// This function is a wrapper around CastInst::isEliminableCastPair. It
469 /// simply extracts arguments and returns what that function returns.
470 static Instruction::CastOps 
471 isEliminableCastPair(
472   const CastInst *CI, ///< The first cast instruction
473   unsigned opcode,       ///< The opcode of the second cast instruction
474   const Type *DstTy,     ///< The target type for the second cast instruction
475   TargetData *TD         ///< The target data for pointer size
476 ) {
477   
478   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
479   const Type *MidTy = CI->getType();                  // B from above
480
481   // Get the opcodes of the two Cast instructions
482   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
483   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
484
485   return Instruction::CastOps(
486       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
487                                      DstTy, TD->getIntPtrType()));
488 }
489
490 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
491 /// in any code being generated.  It does not require codegen if V is simple
492 /// enough or if the cast can be folded into other casts.
493 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
494                               const Type *Ty, TargetData *TD) {
495   if (V->getType() == Ty || isa<Constant>(V)) return false;
496   
497   // If this is another cast that can be eliminated, it isn't codegen either.
498   if (const CastInst *CI = dyn_cast<CastInst>(V))
499     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
500       return false;
501   return true;
502 }
503
504 // SimplifyCommutative - This performs a few simplifications for commutative
505 // operators:
506 //
507 //  1. Order operands such that they are listed from right (least complex) to
508 //     left (most complex).  This puts constants before unary operators before
509 //     binary operators.
510 //
511 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
512 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
513 //
514 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
515   bool Changed = false;
516   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
517     Changed = !I.swapOperands();
518
519   if (!I.isAssociative()) return Changed;
520   Instruction::BinaryOps Opcode = I.getOpcode();
521   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
522     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
523       if (isa<Constant>(I.getOperand(1))) {
524         Constant *Folded = ConstantExpr::get(I.getOpcode(),
525                                              cast<Constant>(I.getOperand(1)),
526                                              cast<Constant>(Op->getOperand(1)));
527         I.setOperand(0, Op->getOperand(0));
528         I.setOperand(1, Folded);
529         return true;
530       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
531         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
532             isOnlyUse(Op) && isOnlyUse(Op1)) {
533           Constant *C1 = cast<Constant>(Op->getOperand(1));
534           Constant *C2 = cast<Constant>(Op1->getOperand(1));
535
536           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
537           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
538           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
539                                                     Op1->getOperand(0),
540                                                     Op1->getName(), &I);
541           AddToWorkList(New);
542           I.setOperand(0, New);
543           I.setOperand(1, Folded);
544           return true;
545         }
546     }
547   return Changed;
548 }
549
550 /// SimplifyCompare - For a CmpInst this function just orders the operands
551 /// so that theyare listed from right (least complex) to left (most complex).
552 /// This puts constants before unary operators before binary operators.
553 bool InstCombiner::SimplifyCompare(CmpInst &I) {
554   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
555     return false;
556   I.swapOperands();
557   // Compare instructions are not associative so there's nothing else we can do.
558   return true;
559 }
560
561 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
562 // if the LHS is a constant zero (which is the 'negate' form).
563 //
564 static inline Value *dyn_castNegVal(Value *V) {
565   if (BinaryOperator::isNeg(V))
566     return BinaryOperator::getNegArgument(V);
567
568   // Constants can be considered to be negated values if they can be folded.
569   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
570     return ConstantExpr::getNeg(C);
571
572   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
573     if (C->getType()->getElementType()->isInteger())
574       return ConstantExpr::getNeg(C);
575
576   return 0;
577 }
578
579 static inline Value *dyn_castNotVal(Value *V) {
580   if (BinaryOperator::isNot(V))
581     return BinaryOperator::getNotArgument(V);
582
583   // Constants can be considered to be not'ed values...
584   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
585     return ConstantInt::get(~C->getValue());
586   return 0;
587 }
588
589 // dyn_castFoldableMul - If this value is a multiply that can be folded into
590 // other computations (because it has a constant operand), return the
591 // non-constant operand of the multiply, and set CST to point to the multiplier.
592 // Otherwise, return null.
593 //
594 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
595   if (V->hasOneUse() && V->getType()->isInteger())
596     if (Instruction *I = dyn_cast<Instruction>(V)) {
597       if (I->getOpcode() == Instruction::Mul)
598         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
599           return I->getOperand(0);
600       if (I->getOpcode() == Instruction::Shl)
601         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
602           // The multiplier is really 1 << CST.
603           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
604           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
605           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
606           return I->getOperand(0);
607         }
608     }
609   return 0;
610 }
611
612 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
613 /// expression, return it.
614 static User *dyn_castGetElementPtr(Value *V) {
615   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
616   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
617     if (CE->getOpcode() == Instruction::GetElementPtr)
618       return cast<User>(V);
619   return false;
620 }
621
622 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
623 /// opcode value. Otherwise return UserOp1.
624 static unsigned getOpcode(const Value *V) {
625   if (const Instruction *I = dyn_cast<Instruction>(V))
626     return I->getOpcode();
627   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
628     return CE->getOpcode();
629   // Use UserOp1 to mean there's no opcode.
630   return Instruction::UserOp1;
631 }
632
633 /// AddOne - Add one to a ConstantInt
634 static ConstantInt *AddOne(ConstantInt *C) {
635   APInt Val(C->getValue());
636   return ConstantInt::get(++Val);
637 }
638 /// SubOne - Subtract one from a ConstantInt
639 static ConstantInt *SubOne(ConstantInt *C) {
640   APInt Val(C->getValue());
641   return ConstantInt::get(--Val);
642 }
643 /// Add - Add two ConstantInts together
644 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
645   return ConstantInt::get(C1->getValue() + C2->getValue());
646 }
647 /// And - Bitwise AND two ConstantInts together
648 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
649   return ConstantInt::get(C1->getValue() & C2->getValue());
650 }
651 /// Subtract - Subtract one ConstantInt from another
652 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
653   return ConstantInt::get(C1->getValue() - C2->getValue());
654 }
655 /// Multiply - Multiply two ConstantInts together
656 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
657   return ConstantInt::get(C1->getValue() * C2->getValue());
658 }
659 /// MultiplyOverflows - True if the multiply can not be expressed in an int
660 /// this size.
661 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
662   uint32_t W = C1->getBitWidth();
663   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
664   if (sign) {
665     LHSExt.sext(W * 2);
666     RHSExt.sext(W * 2);
667   } else {
668     LHSExt.zext(W * 2);
669     RHSExt.zext(W * 2);
670   }
671
672   APInt MulExt = LHSExt * RHSExt;
673
674   if (sign) {
675     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
676     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
677     return MulExt.slt(Min) || MulExt.sgt(Max);
678   } else 
679     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
680 }
681
682
683 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
684 /// specified instruction is a constant integer.  If so, check to see if there
685 /// are any bits set in the constant that are not demanded.  If so, shrink the
686 /// constant and return true.
687 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
688                                    APInt Demanded) {
689   assert(I && "No instruction?");
690   assert(OpNo < I->getNumOperands() && "Operand index too large");
691
692   // If the operand is not a constant integer, nothing to do.
693   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
694   if (!OpC) return false;
695
696   // If there are no bits set that aren't demanded, nothing to do.
697   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
698   if ((~Demanded & OpC->getValue()) == 0)
699     return false;
700
701   // This instruction is producing bits that are not demanded. Shrink the RHS.
702   Demanded &= OpC->getValue();
703   I->setOperand(OpNo, ConstantInt::get(Demanded));
704   return true;
705 }
706
707 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
708 // set of known zero and one bits, compute the maximum and minimum values that
709 // could have the specified known zero and known one bits, returning them in
710 // min/max.
711 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
712                                                    const APInt& KnownZero,
713                                                    const APInt& KnownOne,
714                                                    APInt& Min, APInt& Max) {
715   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
716   assert(KnownZero.getBitWidth() == BitWidth && 
717          KnownOne.getBitWidth() == BitWidth &&
718          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
719          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
720   APInt UnknownBits = ~(KnownZero|KnownOne);
721
722   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
723   // bit if it is unknown.
724   Min = KnownOne;
725   Max = KnownOne|UnknownBits;
726   
727   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
728     Min.set(BitWidth-1);
729     Max.clear(BitWidth-1);
730   }
731 }
732
733 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
734 // a set of known zero and one bits, compute the maximum and minimum values that
735 // could have the specified known zero and known one bits, returning them in
736 // min/max.
737 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
738                                                      const APInt &KnownZero,
739                                                      const APInt &KnownOne,
740                                                      APInt &Min, APInt &Max) {
741   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
742   assert(KnownZero.getBitWidth() == BitWidth && 
743          KnownOne.getBitWidth() == BitWidth &&
744          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
745          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
746   APInt UnknownBits = ~(KnownZero|KnownOne);
747   
748   // The minimum value is when the unknown bits are all zeros.
749   Min = KnownOne;
750   // The maximum value is when the unknown bits are all ones.
751   Max = KnownOne|UnknownBits;
752 }
753
754 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
755 /// value based on the demanded bits. When this function is called, it is known
756 /// that only the bits set in DemandedMask of the result of V are ever used
757 /// downstream. Consequently, depending on the mask and V, it may be possible
758 /// to replace V with a constant or one of its operands. In such cases, this
759 /// function does the replacement and returns true. In all other cases, it
760 /// returns false after analyzing the expression and setting KnownOne and known
761 /// to be one in the expression. KnownZero contains all the bits that are known
762 /// to be zero in the expression. These are provided to potentially allow the
763 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
764 /// the expression. KnownOne and KnownZero always follow the invariant that 
765 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
766 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
767 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
768 /// and KnownOne must all be the same.
769 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
770                                         APInt& KnownZero, APInt& KnownOne,
771                                         unsigned Depth) {
772   assert(V != 0 && "Null pointer of Value???");
773   assert(Depth <= 6 && "Limit Search Depth");
774   uint32_t BitWidth = DemandedMask.getBitWidth();
775   const IntegerType *VTy = cast<IntegerType>(V->getType());
776   assert(VTy->getBitWidth() == BitWidth && 
777          KnownZero.getBitWidth() == BitWidth && 
778          KnownOne.getBitWidth() == BitWidth &&
779          "Value *V, DemandedMask, KnownZero and KnownOne \
780           must have same BitWidth");
781   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
782     // We know all of the bits for a constant!
783     KnownOne = CI->getValue() & DemandedMask;
784     KnownZero = ~KnownOne & DemandedMask;
785     return false;
786   }
787   
788   KnownZero.clear(); 
789   KnownOne.clear();
790   if (!V->hasOneUse()) {    // Other users may use these bits.
791     if (Depth != 0) {       // Not at the root.
792       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
793       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
794       return false;
795     }
796     // If this is the root being simplified, allow it to have multiple uses,
797     // just set the DemandedMask to all bits.
798     DemandedMask = APInt::getAllOnesValue(BitWidth);
799   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
800     if (V != UndefValue::get(VTy))
801       return UpdateValueUsesWith(V, UndefValue::get(VTy));
802     return false;
803   } else if (Depth == 6) {        // Limit search depth.
804     return false;
805   }
806   
807   Instruction *I = dyn_cast<Instruction>(V);
808   if (!I) return false;        // Only analyze instructions.
809
810   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
811   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
812   switch (I->getOpcode()) {
813   default:
814     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
815     break;
816   case Instruction::And:
817     // If either the LHS or the RHS are Zero, the result is zero.
818     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
819                              RHSKnownZero, RHSKnownOne, Depth+1))
820       return true;
821     assert((RHSKnownZero & RHSKnownOne) == 0 && 
822            "Bits known to be one AND zero?"); 
823
824     // If something is known zero on the RHS, the bits aren't demanded on the
825     // LHS.
826     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
827                              LHSKnownZero, LHSKnownOne, Depth+1))
828       return true;
829     assert((LHSKnownZero & LHSKnownOne) == 0 && 
830            "Bits known to be one AND zero?"); 
831
832     // If all of the demanded bits are known 1 on one side, return the other.
833     // These bits cannot contribute to the result of the 'and'.
834     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
835         (DemandedMask & ~LHSKnownZero))
836       return UpdateValueUsesWith(I, I->getOperand(0));
837     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
838         (DemandedMask & ~RHSKnownZero))
839       return UpdateValueUsesWith(I, I->getOperand(1));
840     
841     // If all of the demanded bits in the inputs are known zeros, return zero.
842     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
843       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
844       
845     // If the RHS is a constant, see if we can simplify it.
846     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
847       return UpdateValueUsesWith(I, I);
848       
849     // Output known-1 bits are only known if set in both the LHS & RHS.
850     RHSKnownOne &= LHSKnownOne;
851     // Output known-0 are known to be clear if zero in either the LHS | RHS.
852     RHSKnownZero |= LHSKnownZero;
853     break;
854   case Instruction::Or:
855     // If either the LHS or the RHS are One, the result is One.
856     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
857                              RHSKnownZero, RHSKnownOne, Depth+1))
858       return true;
859     assert((RHSKnownZero & RHSKnownOne) == 0 && 
860            "Bits known to be one AND zero?"); 
861     // If something is known one on the RHS, the bits aren't demanded on the
862     // LHS.
863     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
864                              LHSKnownZero, LHSKnownOne, Depth+1))
865       return true;
866     assert((LHSKnownZero & LHSKnownOne) == 0 && 
867            "Bits known to be one AND zero?"); 
868     
869     // If all of the demanded bits are known zero on one side, return the other.
870     // These bits cannot contribute to the result of the 'or'.
871     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
872         (DemandedMask & ~LHSKnownOne))
873       return UpdateValueUsesWith(I, I->getOperand(0));
874     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
875         (DemandedMask & ~RHSKnownOne))
876       return UpdateValueUsesWith(I, I->getOperand(1));
877
878     // If all of the potentially set bits on one side are known to be set on
879     // the other side, just use the 'other' side.
880     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
881         (DemandedMask & (~RHSKnownZero)))
882       return UpdateValueUsesWith(I, I->getOperand(0));
883     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
884         (DemandedMask & (~LHSKnownZero)))
885       return UpdateValueUsesWith(I, I->getOperand(1));
886         
887     // If the RHS is a constant, see if we can simplify it.
888     if (ShrinkDemandedConstant(I, 1, DemandedMask))
889       return UpdateValueUsesWith(I, I);
890           
891     // Output known-0 bits are only known if clear in both the LHS & RHS.
892     RHSKnownZero &= LHSKnownZero;
893     // Output known-1 are known to be set if set in either the LHS | RHS.
894     RHSKnownOne |= LHSKnownOne;
895     break;
896   case Instruction::Xor: {
897     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
898                              RHSKnownZero, RHSKnownOne, Depth+1))
899       return true;
900     assert((RHSKnownZero & RHSKnownOne) == 0 && 
901            "Bits known to be one AND zero?"); 
902     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
903                              LHSKnownZero, LHSKnownOne, Depth+1))
904       return true;
905     assert((LHSKnownZero & LHSKnownOne) == 0 && 
906            "Bits known to be one AND zero?"); 
907     
908     // If all of the demanded bits are known zero on one side, return the other.
909     // These bits cannot contribute to the result of the 'xor'.
910     if ((DemandedMask & RHSKnownZero) == DemandedMask)
911       return UpdateValueUsesWith(I, I->getOperand(0));
912     if ((DemandedMask & LHSKnownZero) == DemandedMask)
913       return UpdateValueUsesWith(I, I->getOperand(1));
914     
915     // Output known-0 bits are known if clear or set in both the LHS & RHS.
916     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
917                          (RHSKnownOne & LHSKnownOne);
918     // Output known-1 are known to be set if set in only one of the LHS, RHS.
919     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
920                         (RHSKnownOne & LHSKnownZero);
921     
922     // If all of the demanded bits are known to be zero on one side or the
923     // other, turn this into an *inclusive* or.
924     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
925     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
926       Instruction *Or =
927         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
928                                  I->getName());
929       InsertNewInstBefore(Or, *I);
930       return UpdateValueUsesWith(I, Or);
931     }
932     
933     // If all of the demanded bits on one side are known, and all of the set
934     // bits on that side are also known to be set on the other side, turn this
935     // into an AND, as we know the bits will be cleared.
936     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
937     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
938       // all known
939       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
940         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
941         Instruction *And = 
942           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
943         InsertNewInstBefore(And, *I);
944         return UpdateValueUsesWith(I, And);
945       }
946     }
947     
948     // If the RHS is a constant, see if we can simplify it.
949     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
950     if (ShrinkDemandedConstant(I, 1, DemandedMask))
951       return UpdateValueUsesWith(I, I);
952     
953     RHSKnownZero = KnownZeroOut;
954     RHSKnownOne  = KnownOneOut;
955     break;
956   }
957   case Instruction::Select:
958     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
959                              RHSKnownZero, RHSKnownOne, Depth+1))
960       return true;
961     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
962                              LHSKnownZero, LHSKnownOne, Depth+1))
963       return true;
964     assert((RHSKnownZero & RHSKnownOne) == 0 && 
965            "Bits known to be one AND zero?"); 
966     assert((LHSKnownZero & LHSKnownOne) == 0 && 
967            "Bits known to be one AND zero?"); 
968     
969     // If the operands are constants, see if we can simplify them.
970     if (ShrinkDemandedConstant(I, 1, DemandedMask))
971       return UpdateValueUsesWith(I, I);
972     if (ShrinkDemandedConstant(I, 2, DemandedMask))
973       return UpdateValueUsesWith(I, I);
974     
975     // Only known if known in both the LHS and RHS.
976     RHSKnownOne &= LHSKnownOne;
977     RHSKnownZero &= LHSKnownZero;
978     break;
979   case Instruction::Trunc: {
980     uint32_t truncBf = 
981       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
982     DemandedMask.zext(truncBf);
983     RHSKnownZero.zext(truncBf);
984     RHSKnownOne.zext(truncBf);
985     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
986                              RHSKnownZero, RHSKnownOne, Depth+1))
987       return true;
988     DemandedMask.trunc(BitWidth);
989     RHSKnownZero.trunc(BitWidth);
990     RHSKnownOne.trunc(BitWidth);
991     assert((RHSKnownZero & RHSKnownOne) == 0 && 
992            "Bits known to be one AND zero?"); 
993     break;
994   }
995   case Instruction::BitCast:
996     if (!I->getOperand(0)->getType()->isInteger())
997       return false;
998       
999     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1000                              RHSKnownZero, RHSKnownOne, Depth+1))
1001       return true;
1002     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1003            "Bits known to be one AND zero?"); 
1004     break;
1005   case Instruction::ZExt: {
1006     // Compute the bits in the result that are not present in the input.
1007     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1008     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1009     
1010     DemandedMask.trunc(SrcBitWidth);
1011     RHSKnownZero.trunc(SrcBitWidth);
1012     RHSKnownOne.trunc(SrcBitWidth);
1013     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1014                              RHSKnownZero, RHSKnownOne, Depth+1))
1015       return true;
1016     DemandedMask.zext(BitWidth);
1017     RHSKnownZero.zext(BitWidth);
1018     RHSKnownOne.zext(BitWidth);
1019     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1020            "Bits known to be one AND zero?"); 
1021     // The top bits are known to be zero.
1022     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1023     break;
1024   }
1025   case Instruction::SExt: {
1026     // Compute the bits in the result that are not present in the input.
1027     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1028     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1029     
1030     APInt InputDemandedBits = DemandedMask & 
1031                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1032
1033     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1034     // If any of the sign extended bits are demanded, we know that the sign
1035     // bit is demanded.
1036     if ((NewBits & DemandedMask) != 0)
1037       InputDemandedBits.set(SrcBitWidth-1);
1038       
1039     InputDemandedBits.trunc(SrcBitWidth);
1040     RHSKnownZero.trunc(SrcBitWidth);
1041     RHSKnownOne.trunc(SrcBitWidth);
1042     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1043                              RHSKnownZero, RHSKnownOne, Depth+1))
1044       return true;
1045     InputDemandedBits.zext(BitWidth);
1046     RHSKnownZero.zext(BitWidth);
1047     RHSKnownOne.zext(BitWidth);
1048     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1049            "Bits known to be one AND zero?"); 
1050       
1051     // If the sign bit of the input is known set or clear, then we know the
1052     // top bits of the result.
1053
1054     // If the input sign bit is known zero, or if the NewBits are not demanded
1055     // convert this into a zero extension.
1056     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1057     {
1058       // Convert to ZExt cast
1059       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1060       return UpdateValueUsesWith(I, NewCast);
1061     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1062       RHSKnownOne |= NewBits;
1063     }
1064     break;
1065   }
1066   case Instruction::Add: {
1067     // Figure out what the input bits are.  If the top bits of the and result
1068     // are not demanded, then the add doesn't demand them from its input
1069     // either.
1070     uint32_t NLZ = DemandedMask.countLeadingZeros();
1071       
1072     // If there is a constant on the RHS, there are a variety of xformations
1073     // we can do.
1074     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1075       // If null, this should be simplified elsewhere.  Some of the xforms here
1076       // won't work if the RHS is zero.
1077       if (RHS->isZero())
1078         break;
1079       
1080       // If the top bit of the output is demanded, demand everything from the
1081       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1082       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1083
1084       // Find information about known zero/one bits in the input.
1085       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1086                                LHSKnownZero, LHSKnownOne, Depth+1))
1087         return true;
1088
1089       // If the RHS of the add has bits set that can't affect the input, reduce
1090       // the constant.
1091       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1092         return UpdateValueUsesWith(I, I);
1093       
1094       // Avoid excess work.
1095       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1096         break;
1097       
1098       // Turn it into OR if input bits are zero.
1099       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1100         Instruction *Or =
1101           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1102                                    I->getName());
1103         InsertNewInstBefore(Or, *I);
1104         return UpdateValueUsesWith(I, Or);
1105       }
1106       
1107       // We can say something about the output known-zero and known-one bits,
1108       // depending on potential carries from the input constant and the
1109       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1110       // bits set and the RHS constant is 0x01001, then we know we have a known
1111       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1112       
1113       // To compute this, we first compute the potential carry bits.  These are
1114       // the bits which may be modified.  I'm not aware of a better way to do
1115       // this scan.
1116       const APInt& RHSVal = RHS->getValue();
1117       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1118       
1119       // Now that we know which bits have carries, compute the known-1/0 sets.
1120       
1121       // Bits are known one if they are known zero in one operand and one in the
1122       // other, and there is no input carry.
1123       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1124                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1125       
1126       // Bits are known zero if they are known zero in both operands and there
1127       // is no input carry.
1128       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1129     } else {
1130       // If the high-bits of this ADD are not demanded, then it does not demand
1131       // the high bits of its LHS or RHS.
1132       if (DemandedMask[BitWidth-1] == 0) {
1133         // Right fill the mask of bits for this ADD to demand the most
1134         // significant bit and all those below it.
1135         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1136         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1137                                  LHSKnownZero, LHSKnownOne, Depth+1))
1138           return true;
1139         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1140                                  LHSKnownZero, LHSKnownOne, Depth+1))
1141           return true;
1142       }
1143     }
1144     break;
1145   }
1146   case Instruction::Sub:
1147     // If the high-bits of this SUB are not demanded, then it does not demand
1148     // the high bits of its LHS or RHS.
1149     if (DemandedMask[BitWidth-1] == 0) {
1150       // Right fill the mask of bits for this SUB to demand the most
1151       // significant bit and all those below it.
1152       uint32_t NLZ = DemandedMask.countLeadingZeros();
1153       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1154       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1155                                LHSKnownZero, LHSKnownOne, Depth+1))
1156         return true;
1157       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1158                                LHSKnownZero, LHSKnownOne, Depth+1))
1159         return true;
1160     }
1161     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1162     // the known zeros and ones.
1163     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1164     break;
1165   case Instruction::Shl:
1166     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1167       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1168       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1169       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1170                                RHSKnownZero, RHSKnownOne, Depth+1))
1171         return true;
1172       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1173              "Bits known to be one AND zero?"); 
1174       RHSKnownZero <<= ShiftAmt;
1175       RHSKnownOne  <<= ShiftAmt;
1176       // low bits known zero.
1177       if (ShiftAmt)
1178         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1179     }
1180     break;
1181   case Instruction::LShr:
1182     // For a logical shift right
1183     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1184       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1185       
1186       // Unsigned shift right.
1187       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1188       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1189                                RHSKnownZero, RHSKnownOne, Depth+1))
1190         return true;
1191       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1192              "Bits known to be one AND zero?"); 
1193       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1194       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1195       if (ShiftAmt) {
1196         // Compute the new bits that are at the top now.
1197         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1198         RHSKnownZero |= HighBits;  // high bits known zero.
1199       }
1200     }
1201     break;
1202   case Instruction::AShr:
1203     // If this is an arithmetic shift right and only the low-bit is set, we can
1204     // always convert this into a logical shr, even if the shift amount is
1205     // variable.  The low bit of the shift cannot be an input sign bit unless
1206     // the shift amount is >= the size of the datatype, which is undefined.
1207     if (DemandedMask == 1) {
1208       // Perform the logical shift right.
1209       Value *NewVal = BinaryOperator::CreateLShr(
1210                         I->getOperand(0), I->getOperand(1), I->getName());
1211       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1212       return UpdateValueUsesWith(I, NewVal);
1213     }    
1214
1215     // If the sign bit is the only bit demanded by this ashr, then there is no
1216     // need to do it, the shift doesn't change the high bit.
1217     if (DemandedMask.isSignBit())
1218       return UpdateValueUsesWith(I, I->getOperand(0));
1219     
1220     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1221       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1222       
1223       // Signed shift right.
1224       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1225       // If any of the "high bits" are demanded, we should set the sign bit as
1226       // demanded.
1227       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1228         DemandedMaskIn.set(BitWidth-1);
1229       if (SimplifyDemandedBits(I->getOperand(0),
1230                                DemandedMaskIn,
1231                                RHSKnownZero, RHSKnownOne, Depth+1))
1232         return true;
1233       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1234              "Bits known to be one AND zero?"); 
1235       // Compute the new bits that are at the top now.
1236       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1237       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1238       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1239         
1240       // Handle the sign bits.
1241       APInt SignBit(APInt::getSignBit(BitWidth));
1242       // Adjust to where it is now in the mask.
1243       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1244         
1245       // If the input sign bit is known to be zero, or if none of the top bits
1246       // are demanded, turn this into an unsigned shift right.
1247       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1248           (HighBits & ~DemandedMask) == HighBits) {
1249         // Perform the logical shift right.
1250         Value *NewVal = BinaryOperator::CreateLShr(
1251                           I->getOperand(0), SA, I->getName());
1252         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1253         return UpdateValueUsesWith(I, NewVal);
1254       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1255         RHSKnownOne |= HighBits;
1256       }
1257     }
1258     break;
1259   case Instruction::SRem:
1260     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1261       APInt RA = Rem->getValue().abs();
1262       if (RA.isPowerOf2()) {
1263         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1264           return UpdateValueUsesWith(I, I->getOperand(0));
1265
1266         APInt LowBits = RA - 1;
1267         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1268         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1269                                  LHSKnownZero, LHSKnownOne, Depth+1))
1270           return true;
1271
1272         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1273           LHSKnownZero |= ~LowBits;
1274
1275         KnownZero |= LHSKnownZero & DemandedMask;
1276
1277         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1278       }
1279     }
1280     break;
1281   case Instruction::URem: {
1282     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1283     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1284     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1285                              KnownZero2, KnownOne2, Depth+1))
1286       return true;
1287
1288     uint32_t Leaders = KnownZero2.countLeadingOnes();
1289     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1290                              KnownZero2, KnownOne2, Depth+1))
1291       return true;
1292
1293     Leaders = std::max(Leaders,
1294                        KnownZero2.countLeadingOnes());
1295     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1296     break;
1297   }
1298   case Instruction::Call:
1299     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1300       switch (II->getIntrinsicID()) {
1301       default: break;
1302       case Intrinsic::bswap: {
1303         // If the only bits demanded come from one byte of the bswap result,
1304         // just shift the input byte into position to eliminate the bswap.
1305         unsigned NLZ = DemandedMask.countLeadingZeros();
1306         unsigned NTZ = DemandedMask.countTrailingZeros();
1307           
1308         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1309         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1310         // have 14 leading zeros, round to 8.
1311         NLZ &= ~7;
1312         NTZ &= ~7;
1313         // If we need exactly one byte, we can do this transformation.
1314         if (BitWidth-NLZ-NTZ == 8) {
1315           unsigned ResultBit = NTZ;
1316           unsigned InputBit = BitWidth-NTZ-8;
1317           
1318           // Replace this with either a left or right shift to get the byte into
1319           // the right place.
1320           Instruction *NewVal;
1321           if (InputBit > ResultBit)
1322             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1323                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1324           else
1325             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1326                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1327           NewVal->takeName(I);
1328           InsertNewInstBefore(NewVal, *I);
1329           return UpdateValueUsesWith(I, NewVal);
1330         }
1331           
1332         // TODO: Could compute known zero/one bits based on the input.
1333         break;
1334       }
1335       }
1336     }
1337     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1338     break;
1339   }
1340   
1341   // If the client is only demanding bits that we know, return the known
1342   // constant.
1343   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1344     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1345   return false;
1346 }
1347
1348
1349 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1350 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1351 /// actually used by the caller.  This method analyzes which elements of the
1352 /// operand are undef and returns that information in UndefElts.
1353 ///
1354 /// If the information about demanded elements can be used to simplify the
1355 /// operation, the operation is simplified, then the resultant value is
1356 /// returned.  This returns null if no change was made.
1357 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1358                                                 uint64_t &UndefElts,
1359                                                 unsigned Depth) {
1360   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1361   assert(VWidth <= 64 && "Vector too wide to analyze!");
1362   uint64_t EltMask = ~0ULL >> (64-VWidth);
1363   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1364
1365   if (isa<UndefValue>(V)) {
1366     // If the entire vector is undefined, just return this info.
1367     UndefElts = EltMask;
1368     return 0;
1369   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1370     UndefElts = EltMask;
1371     return UndefValue::get(V->getType());
1372   }
1373
1374   UndefElts = 0;
1375   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1376     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1377     Constant *Undef = UndefValue::get(EltTy);
1378
1379     std::vector<Constant*> Elts;
1380     for (unsigned i = 0; i != VWidth; ++i)
1381       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1382         Elts.push_back(Undef);
1383         UndefElts |= (1ULL << i);
1384       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1385         Elts.push_back(Undef);
1386         UndefElts |= (1ULL << i);
1387       } else {                               // Otherwise, defined.
1388         Elts.push_back(CP->getOperand(i));
1389       }
1390
1391     // If we changed the constant, return it.
1392     Constant *NewCP = ConstantVector::get(Elts);
1393     return NewCP != CP ? NewCP : 0;
1394   } else if (isa<ConstantAggregateZero>(V)) {
1395     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1396     // set to undef.
1397     
1398     // Check if this is identity. If so, return 0 since we are not simplifying
1399     // anything.
1400     if (DemandedElts == ((1ULL << VWidth) -1))
1401       return 0;
1402     
1403     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1404     Constant *Zero = Constant::getNullValue(EltTy);
1405     Constant *Undef = UndefValue::get(EltTy);
1406     std::vector<Constant*> Elts;
1407     for (unsigned i = 0; i != VWidth; ++i)
1408       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1409     UndefElts = DemandedElts ^ EltMask;
1410     return ConstantVector::get(Elts);
1411   }
1412   
1413   // Limit search depth.
1414   if (Depth == 10)
1415     return false;
1416
1417   // If multiple users are using the root value, procede with
1418   // simplification conservatively assuming that all elements
1419   // are needed.
1420   if (!V->hasOneUse()) {
1421     // Quit if we find multiple users of a non-root value though.
1422     // They'll be handled when it's their turn to be visited by
1423     // the main instcombine process.
1424     if (Depth != 0)
1425       // TODO: Just compute the UndefElts information recursively.
1426       return false;
1427
1428     // Conservatively assume that all elements are needed.
1429     DemandedElts = EltMask;
1430   }
1431   
1432   Instruction *I = dyn_cast<Instruction>(V);
1433   if (!I) return false;        // Only analyze instructions.
1434   
1435   bool MadeChange = false;
1436   uint64_t UndefElts2;
1437   Value *TmpV;
1438   switch (I->getOpcode()) {
1439   default: break;
1440     
1441   case Instruction::InsertElement: {
1442     // If this is a variable index, we don't know which element it overwrites.
1443     // demand exactly the same input as we produce.
1444     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1445     if (Idx == 0) {
1446       // Note that we can't propagate undef elt info, because we don't know
1447       // which elt is getting updated.
1448       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1449                                         UndefElts2, Depth+1);
1450       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1451       break;
1452     }
1453     
1454     // If this is inserting an element that isn't demanded, remove this
1455     // insertelement.
1456     unsigned IdxNo = Idx->getZExtValue();
1457     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1458       return AddSoonDeadInstToWorklist(*I, 0);
1459     
1460     // Otherwise, the element inserted overwrites whatever was there, so the
1461     // input demanded set is simpler than the output set.
1462     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1463                                       DemandedElts & ~(1ULL << IdxNo),
1464                                       UndefElts, Depth+1);
1465     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1466
1467     // The inserted element is defined.
1468     UndefElts &= ~(1ULL << IdxNo);
1469     break;
1470   }
1471   case Instruction::ShuffleVector: {
1472     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1473     uint64_t LHSVWidth =
1474       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1475     uint64_t LeftDemanded = 0, RightDemanded = 0;
1476     for (unsigned i = 0; i < VWidth; i++) {
1477       if (DemandedElts & (1ULL << i)) {
1478         unsigned MaskVal = Shuffle->getMaskValue(i);
1479         if (MaskVal != -1u) {
1480           assert(MaskVal < LHSVWidth * 2 &&
1481                  "shufflevector mask index out of range!");
1482           if (MaskVal < LHSVWidth)
1483             LeftDemanded |= 1ULL << MaskVal;
1484           else
1485             RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
1486         }
1487       }
1488     }
1489
1490     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1491                                       UndefElts2, Depth+1);
1492     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1493
1494     uint64_t UndefElts3;
1495     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1496                                       UndefElts3, Depth+1);
1497     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1498
1499     bool NewUndefElts = false;
1500     for (unsigned i = 0; i < VWidth; i++) {
1501       unsigned MaskVal = Shuffle->getMaskValue(i);
1502       if (MaskVal == -1u) {
1503         uint64_t NewBit = 1ULL << i;
1504         UndefElts |= NewBit;
1505       } else if (MaskVal < LHSVWidth) {
1506         uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1507         NewUndefElts |= NewBit;
1508         UndefElts |= NewBit;
1509       } else {
1510         uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
1511         NewUndefElts |= NewBit;
1512         UndefElts |= NewBit;
1513       }
1514     }
1515
1516     if (NewUndefElts) {
1517       // Add additional discovered undefs.
1518       std::vector<Constant*> Elts;
1519       for (unsigned i = 0; i < VWidth; ++i) {
1520         if (UndefElts & (1ULL << i))
1521           Elts.push_back(UndefValue::get(Type::Int32Ty));
1522         else
1523           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1524                                           Shuffle->getMaskValue(i)));
1525       }
1526       I->setOperand(2, ConstantVector::get(Elts));
1527       MadeChange = true;
1528     }
1529     break;
1530   }
1531   case Instruction::BitCast: {
1532     // Vector->vector casts only.
1533     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1534     if (!VTy) break;
1535     unsigned InVWidth = VTy->getNumElements();
1536     uint64_t InputDemandedElts = 0;
1537     unsigned Ratio;
1538
1539     if (VWidth == InVWidth) {
1540       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1541       // elements as are demanded of us.
1542       Ratio = 1;
1543       InputDemandedElts = DemandedElts;
1544     } else if (VWidth > InVWidth) {
1545       // Untested so far.
1546       break;
1547       
1548       // If there are more elements in the result than there are in the source,
1549       // then an input element is live if any of the corresponding output
1550       // elements are live.
1551       Ratio = VWidth/InVWidth;
1552       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1553         if (DemandedElts & (1ULL << OutIdx))
1554           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1555       }
1556     } else {
1557       // Untested so far.
1558       break;
1559       
1560       // If there are more elements in the source than there are in the result,
1561       // then an input element is live if the corresponding output element is
1562       // live.
1563       Ratio = InVWidth/VWidth;
1564       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1565         if (DemandedElts & (1ULL << InIdx/Ratio))
1566           InputDemandedElts |= 1ULL << InIdx;
1567     }
1568     
1569     // div/rem demand all inputs, because they don't want divide by zero.
1570     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1571                                       UndefElts2, Depth+1);
1572     if (TmpV) {
1573       I->setOperand(0, TmpV);
1574       MadeChange = true;
1575     }
1576     
1577     UndefElts = UndefElts2;
1578     if (VWidth > InVWidth) {
1579       assert(0 && "Unimp");
1580       // If there are more elements in the result than there are in the source,
1581       // then an output element is undef if the corresponding input element is
1582       // undef.
1583       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1584         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1585           UndefElts |= 1ULL << OutIdx;
1586     } else if (VWidth < InVWidth) {
1587       assert(0 && "Unimp");
1588       // If there are more elements in the source than there are in the result,
1589       // then a result element is undef if all of the corresponding input
1590       // elements are undef.
1591       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1592       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1593         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1594           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1595     }
1596     break;
1597   }
1598   case Instruction::And:
1599   case Instruction::Or:
1600   case Instruction::Xor:
1601   case Instruction::Add:
1602   case Instruction::Sub:
1603   case Instruction::Mul:
1604     // div/rem demand all inputs, because they don't want divide by zero.
1605     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1606                                       UndefElts, Depth+1);
1607     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1608     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1609                                       UndefElts2, Depth+1);
1610     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1611       
1612     // Output elements are undefined if both are undefined.  Consider things
1613     // like undef&0.  The result is known zero, not undef.
1614     UndefElts &= UndefElts2;
1615     break;
1616     
1617   case Instruction::Call: {
1618     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1619     if (!II) break;
1620     switch (II->getIntrinsicID()) {
1621     default: break;
1622       
1623     // Binary vector operations that work column-wise.  A dest element is a
1624     // function of the corresponding input elements from the two inputs.
1625     case Intrinsic::x86_sse_sub_ss:
1626     case Intrinsic::x86_sse_mul_ss:
1627     case Intrinsic::x86_sse_min_ss:
1628     case Intrinsic::x86_sse_max_ss:
1629     case Intrinsic::x86_sse2_sub_sd:
1630     case Intrinsic::x86_sse2_mul_sd:
1631     case Intrinsic::x86_sse2_min_sd:
1632     case Intrinsic::x86_sse2_max_sd:
1633       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1634                                         UndefElts, Depth+1);
1635       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1636       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1637                                         UndefElts2, Depth+1);
1638       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1639
1640       // If only the low elt is demanded and this is a scalarizable intrinsic,
1641       // scalarize it now.
1642       if (DemandedElts == 1) {
1643         switch (II->getIntrinsicID()) {
1644         default: break;
1645         case Intrinsic::x86_sse_sub_ss:
1646         case Intrinsic::x86_sse_mul_ss:
1647         case Intrinsic::x86_sse2_sub_sd:
1648         case Intrinsic::x86_sse2_mul_sd:
1649           // TODO: Lower MIN/MAX/ABS/etc
1650           Value *LHS = II->getOperand(1);
1651           Value *RHS = II->getOperand(2);
1652           // Extract the element as scalars.
1653           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1654           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1655           
1656           switch (II->getIntrinsicID()) {
1657           default: assert(0 && "Case stmts out of sync!");
1658           case Intrinsic::x86_sse_sub_ss:
1659           case Intrinsic::x86_sse2_sub_sd:
1660             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1661                                                         II->getName()), *II);
1662             break;
1663           case Intrinsic::x86_sse_mul_ss:
1664           case Intrinsic::x86_sse2_mul_sd:
1665             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1666                                                          II->getName()), *II);
1667             break;
1668           }
1669           
1670           Instruction *New =
1671             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1672                                       II->getName());
1673           InsertNewInstBefore(New, *II);
1674           AddSoonDeadInstToWorklist(*II, 0);
1675           return New;
1676         }            
1677       }
1678         
1679       // Output elements are undefined if both are undefined.  Consider things
1680       // like undef&0.  The result is known zero, not undef.
1681       UndefElts &= UndefElts2;
1682       break;
1683     }
1684     break;
1685   }
1686   }
1687   return MadeChange ? I : 0;
1688 }
1689
1690
1691 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1692 /// function is designed to check a chain of associative operators for a
1693 /// potential to apply a certain optimization.  Since the optimization may be
1694 /// applicable if the expression was reassociated, this checks the chain, then
1695 /// reassociates the expression as necessary to expose the optimization
1696 /// opportunity.  This makes use of a special Functor, which must define
1697 /// 'shouldApply' and 'apply' methods.
1698 ///
1699 template<typename Functor>
1700 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1701   unsigned Opcode = Root.getOpcode();
1702   Value *LHS = Root.getOperand(0);
1703
1704   // Quick check, see if the immediate LHS matches...
1705   if (F.shouldApply(LHS))
1706     return F.apply(Root);
1707
1708   // Otherwise, if the LHS is not of the same opcode as the root, return.
1709   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1710   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1711     // Should we apply this transform to the RHS?
1712     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1713
1714     // If not to the RHS, check to see if we should apply to the LHS...
1715     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1716       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1717       ShouldApply = true;
1718     }
1719
1720     // If the functor wants to apply the optimization to the RHS of LHSI,
1721     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1722     if (ShouldApply) {
1723       // Now all of the instructions are in the current basic block, go ahead
1724       // and perform the reassociation.
1725       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1726
1727       // First move the selected RHS to the LHS of the root...
1728       Root.setOperand(0, LHSI->getOperand(1));
1729
1730       // Make what used to be the LHS of the root be the user of the root...
1731       Value *ExtraOperand = TmpLHSI->getOperand(1);
1732       if (&Root == TmpLHSI) {
1733         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1734         return 0;
1735       }
1736       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1737       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1738       BasicBlock::iterator ARI = &Root; ++ARI;
1739       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1740       ARI = Root;
1741
1742       // Now propagate the ExtraOperand down the chain of instructions until we
1743       // get to LHSI.
1744       while (TmpLHSI != LHSI) {
1745         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1746         // Move the instruction to immediately before the chain we are
1747         // constructing to avoid breaking dominance properties.
1748         NextLHSI->moveBefore(ARI);
1749         ARI = NextLHSI;
1750
1751         Value *NextOp = NextLHSI->getOperand(1);
1752         NextLHSI->setOperand(1, ExtraOperand);
1753         TmpLHSI = NextLHSI;
1754         ExtraOperand = NextOp;
1755       }
1756
1757       // Now that the instructions are reassociated, have the functor perform
1758       // the transformation...
1759       return F.apply(Root);
1760     }
1761
1762     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1763   }
1764   return 0;
1765 }
1766
1767 namespace {
1768
1769 // AddRHS - Implements: X + X --> X << 1
1770 struct AddRHS {
1771   Value *RHS;
1772   AddRHS(Value *rhs) : RHS(rhs) {}
1773   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1774   Instruction *apply(BinaryOperator &Add) const {
1775     return BinaryOperator::CreateShl(Add.getOperand(0),
1776                                      ConstantInt::get(Add.getType(), 1));
1777   }
1778 };
1779
1780 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1781 //                 iff C1&C2 == 0
1782 struct AddMaskingAnd {
1783   Constant *C2;
1784   AddMaskingAnd(Constant *c) : C2(c) {}
1785   bool shouldApply(Value *LHS) const {
1786     ConstantInt *C1;
1787     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1788            ConstantExpr::getAnd(C1, C2)->isNullValue();
1789   }
1790   Instruction *apply(BinaryOperator &Add) const {
1791     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1792   }
1793 };
1794
1795 }
1796
1797 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1798                                              InstCombiner *IC) {
1799   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1800     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1801   }
1802
1803   // Figure out if the constant is the left or the right argument.
1804   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1805   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1806
1807   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1808     if (ConstIsRHS)
1809       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1810     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1811   }
1812
1813   Value *Op0 = SO, *Op1 = ConstOperand;
1814   if (!ConstIsRHS)
1815     std::swap(Op0, Op1);
1816   Instruction *New;
1817   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1818     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1819   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1820     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1821                           SO->getName()+".cmp");
1822   else {
1823     assert(0 && "Unknown binary instruction type!");
1824     abort();
1825   }
1826   return IC->InsertNewInstBefore(New, I);
1827 }
1828
1829 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1830 // constant as the other operand, try to fold the binary operator into the
1831 // select arguments.  This also works for Cast instructions, which obviously do
1832 // not have a second operand.
1833 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1834                                      InstCombiner *IC) {
1835   // Don't modify shared select instructions
1836   if (!SI->hasOneUse()) return 0;
1837   Value *TV = SI->getOperand(1);
1838   Value *FV = SI->getOperand(2);
1839
1840   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1841     // Bool selects with constant operands can be folded to logical ops.
1842     if (SI->getType() == Type::Int1Ty) return 0;
1843
1844     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1845     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1846
1847     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1848                               SelectFalseVal);
1849   }
1850   return 0;
1851 }
1852
1853
1854 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1855 /// node as operand #0, see if we can fold the instruction into the PHI (which
1856 /// is only possible if all operands to the PHI are constants).
1857 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1858   PHINode *PN = cast<PHINode>(I.getOperand(0));
1859   unsigned NumPHIValues = PN->getNumIncomingValues();
1860   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1861
1862   // Check to see if all of the operands of the PHI are constants.  If there is
1863   // one non-constant value, remember the BB it is.  If there is more than one
1864   // or if *it* is a PHI, bail out.
1865   BasicBlock *NonConstBB = 0;
1866   for (unsigned i = 0; i != NumPHIValues; ++i)
1867     if (!isa<Constant>(PN->getIncomingValue(i))) {
1868       if (NonConstBB) return 0;  // More than one non-const value.
1869       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1870       NonConstBB = PN->getIncomingBlock(i);
1871       
1872       // If the incoming non-constant value is in I's block, we have an infinite
1873       // loop.
1874       if (NonConstBB == I.getParent())
1875         return 0;
1876     }
1877   
1878   // If there is exactly one non-constant value, we can insert a copy of the
1879   // operation in that block.  However, if this is a critical edge, we would be
1880   // inserting the computation one some other paths (e.g. inside a loop).  Only
1881   // do this if the pred block is unconditionally branching into the phi block.
1882   if (NonConstBB) {
1883     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1884     if (!BI || !BI->isUnconditional()) return 0;
1885   }
1886
1887   // Okay, we can do the transformation: create the new PHI node.
1888   PHINode *NewPN = PHINode::Create(I.getType(), "");
1889   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1890   InsertNewInstBefore(NewPN, *PN);
1891   NewPN->takeName(PN);
1892
1893   // Next, add all of the operands to the PHI.
1894   if (I.getNumOperands() == 2) {
1895     Constant *C = cast<Constant>(I.getOperand(1));
1896     for (unsigned i = 0; i != NumPHIValues; ++i) {
1897       Value *InV = 0;
1898       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1899         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1900           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1901         else
1902           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1903       } else {
1904         assert(PN->getIncomingBlock(i) == NonConstBB);
1905         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1906           InV = BinaryOperator::Create(BO->getOpcode(),
1907                                        PN->getIncomingValue(i), C, "phitmp",
1908                                        NonConstBB->getTerminator());
1909         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1910           InV = CmpInst::Create(CI->getOpcode(), 
1911                                 CI->getPredicate(),
1912                                 PN->getIncomingValue(i), C, "phitmp",
1913                                 NonConstBB->getTerminator());
1914         else
1915           assert(0 && "Unknown binop!");
1916         
1917         AddToWorkList(cast<Instruction>(InV));
1918       }
1919       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1920     }
1921   } else { 
1922     CastInst *CI = cast<CastInst>(&I);
1923     const Type *RetTy = CI->getType();
1924     for (unsigned i = 0; i != NumPHIValues; ++i) {
1925       Value *InV;
1926       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1927         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1928       } else {
1929         assert(PN->getIncomingBlock(i) == NonConstBB);
1930         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1931                                I.getType(), "phitmp", 
1932                                NonConstBB->getTerminator());
1933         AddToWorkList(cast<Instruction>(InV));
1934       }
1935       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1936     }
1937   }
1938   return ReplaceInstUsesWith(I, NewPN);
1939 }
1940
1941
1942 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1943 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1944 /// This basically requires proving that the add in the original type would not
1945 /// overflow to change the sign bit or have a carry out.
1946 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1947   // There are different heuristics we can use for this.  Here are some simple
1948   // ones.
1949   
1950   // Add has the property that adding any two 2's complement numbers can only 
1951   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1952   // have at least two sign bits, we know that the addition of the two values will
1953   // sign extend fine.
1954   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1955     return true;
1956   
1957   
1958   // If one of the operands only has one non-zero bit, and if the other operand
1959   // has a known-zero bit in a more significant place than it (not including the
1960   // sign bit) the ripple may go up to and fill the zero, but won't change the
1961   // sign.  For example, (X & ~4) + 1.
1962   
1963   // TODO: Implement.
1964   
1965   return false;
1966 }
1967
1968
1969 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1970   bool Changed = SimplifyCommutative(I);
1971   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1972
1973   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1974     // X + undef -> undef
1975     if (isa<UndefValue>(RHS))
1976       return ReplaceInstUsesWith(I, RHS);
1977
1978     // X + 0 --> X
1979     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1980       if (RHSC->isNullValue())
1981         return ReplaceInstUsesWith(I, LHS);
1982     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1983       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1984                               (I.getType())->getValueAPF()))
1985         return ReplaceInstUsesWith(I, LHS);
1986     }
1987
1988     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1989       // X + (signbit) --> X ^ signbit
1990       const APInt& Val = CI->getValue();
1991       uint32_t BitWidth = Val.getBitWidth();
1992       if (Val == APInt::getSignBit(BitWidth))
1993         return BinaryOperator::CreateXor(LHS, RHS);
1994       
1995       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1996       // (X & 254)+1 -> (X&254)|1
1997       if (!isa<VectorType>(I.getType())) {
1998         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1999         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2000                                  KnownZero, KnownOne))
2001           return &I;
2002       }
2003
2004       // zext(i1) - 1  ->  select i1, 0, -1
2005       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2006         if (CI->isAllOnesValue() &&
2007             ZI->getOperand(0)->getType() == Type::Int1Ty)
2008           return SelectInst::Create(ZI->getOperand(0),
2009                                     Constant::getNullValue(I.getType()),
2010                                     ConstantInt::getAllOnesValue(I.getType()));
2011     }
2012
2013     if (isa<PHINode>(LHS))
2014       if (Instruction *NV = FoldOpIntoPhi(I))
2015         return NV;
2016     
2017     ConstantInt *XorRHS = 0;
2018     Value *XorLHS = 0;
2019     if (isa<ConstantInt>(RHSC) &&
2020         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2021       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2022       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2023       
2024       uint32_t Size = TySizeBits / 2;
2025       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2026       APInt CFF80Val(-C0080Val);
2027       do {
2028         if (TySizeBits > Size) {
2029           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2030           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2031           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2032               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2033             // This is a sign extend if the top bits are known zero.
2034             if (!MaskedValueIsZero(XorLHS, 
2035                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2036               Size = 0;  // Not a sign ext, but can't be any others either.
2037             break;
2038           }
2039         }
2040         Size >>= 1;
2041         C0080Val = APIntOps::lshr(C0080Val, Size);
2042         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2043       } while (Size >= 1);
2044       
2045       // FIXME: This shouldn't be necessary. When the backends can handle types
2046       // with funny bit widths then this switch statement should be removed. It
2047       // is just here to get the size of the "middle" type back up to something
2048       // that the back ends can handle.
2049       const Type *MiddleType = 0;
2050       switch (Size) {
2051         default: break;
2052         case 32: MiddleType = Type::Int32Ty; break;
2053         case 16: MiddleType = Type::Int16Ty; break;
2054         case  8: MiddleType = Type::Int8Ty; break;
2055       }
2056       if (MiddleType) {
2057         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2058         InsertNewInstBefore(NewTrunc, I);
2059         return new SExtInst(NewTrunc, I.getType(), I.getName());
2060       }
2061     }
2062   }
2063
2064   if (I.getType() == Type::Int1Ty)
2065     return BinaryOperator::CreateXor(LHS, RHS);
2066
2067   // X + X --> X << 1
2068   if (I.getType()->isInteger()) {
2069     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2070
2071     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2072       if (RHSI->getOpcode() == Instruction::Sub)
2073         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2074           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2075     }
2076     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2077       if (LHSI->getOpcode() == Instruction::Sub)
2078         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2079           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2080     }
2081   }
2082
2083   // -A + B  -->  B - A
2084   // -A + -B  -->  -(A + B)
2085   if (Value *LHSV = dyn_castNegVal(LHS)) {
2086     if (LHS->getType()->isIntOrIntVector()) {
2087       if (Value *RHSV = dyn_castNegVal(RHS)) {
2088         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2089         InsertNewInstBefore(NewAdd, I);
2090         return BinaryOperator::CreateNeg(NewAdd);
2091       }
2092     }
2093     
2094     return BinaryOperator::CreateSub(RHS, LHSV);
2095   }
2096
2097   // A + -B  -->  A - B
2098   if (!isa<Constant>(RHS))
2099     if (Value *V = dyn_castNegVal(RHS))
2100       return BinaryOperator::CreateSub(LHS, V);
2101
2102
2103   ConstantInt *C2;
2104   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2105     if (X == RHS)   // X*C + X --> X * (C+1)
2106       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2107
2108     // X*C1 + X*C2 --> X * (C1+C2)
2109     ConstantInt *C1;
2110     if (X == dyn_castFoldableMul(RHS, C1))
2111       return BinaryOperator::CreateMul(X, Add(C1, C2));
2112   }
2113
2114   // X + X*C --> X * (C+1)
2115   if (dyn_castFoldableMul(RHS, C2) == LHS)
2116     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2117
2118   // X + ~X --> -1   since   ~X = -X-1
2119   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2120     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2121   
2122
2123   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2124   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2125     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2126       return R;
2127   
2128   // A+B --> A|B iff A and B have no bits set in common.
2129   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2130     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2131     APInt LHSKnownOne(IT->getBitWidth(), 0);
2132     APInt LHSKnownZero(IT->getBitWidth(), 0);
2133     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2134     if (LHSKnownZero != 0) {
2135       APInt RHSKnownOne(IT->getBitWidth(), 0);
2136       APInt RHSKnownZero(IT->getBitWidth(), 0);
2137       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2138       
2139       // No bits in common -> bitwise or.
2140       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2141         return BinaryOperator::CreateOr(LHS, RHS);
2142     }
2143   }
2144
2145   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2146   if (I.getType()->isIntOrIntVector()) {
2147     Value *W, *X, *Y, *Z;
2148     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2149         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2150       if (W != Y) {
2151         if (W == Z) {
2152           std::swap(Y, Z);
2153         } else if (Y == X) {
2154           std::swap(W, X);
2155         } else if (X == Z) {
2156           std::swap(Y, Z);
2157           std::swap(W, X);
2158         }
2159       }
2160
2161       if (W == Y) {
2162         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2163                                                             LHS->getName()), I);
2164         return BinaryOperator::CreateMul(W, NewAdd);
2165       }
2166     }
2167   }
2168
2169   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2170     Value *X = 0;
2171     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2172       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2173
2174     // (X & FF00) + xx00  -> (X+xx00) & FF00
2175     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2176       Constant *Anded = And(CRHS, C2);
2177       if (Anded == CRHS) {
2178         // See if all bits from the first bit set in the Add RHS up are included
2179         // in the mask.  First, get the rightmost bit.
2180         const APInt& AddRHSV = CRHS->getValue();
2181
2182         // Form a mask of all bits from the lowest bit added through the top.
2183         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2184
2185         // See if the and mask includes all of these bits.
2186         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2187
2188         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2189           // Okay, the xform is safe.  Insert the new add pronto.
2190           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2191                                                             LHS->getName()), I);
2192           return BinaryOperator::CreateAnd(NewAdd, C2);
2193         }
2194       }
2195     }
2196
2197     // Try to fold constant add into select arguments.
2198     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2199       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2200         return R;
2201   }
2202
2203   // add (cast *A to intptrtype) B -> 
2204   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2205   {
2206     CastInst *CI = dyn_cast<CastInst>(LHS);
2207     Value *Other = RHS;
2208     if (!CI) {
2209       CI = dyn_cast<CastInst>(RHS);
2210       Other = LHS;
2211     }
2212     if (CI && CI->getType()->isSized() && 
2213         (CI->getType()->getPrimitiveSizeInBits() == 
2214          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2215         && isa<PointerType>(CI->getOperand(0)->getType())) {
2216       unsigned AS =
2217         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2218       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2219                                       PointerType::get(Type::Int8Ty, AS), I);
2220       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2221       return new PtrToIntInst(I2, CI->getType());
2222     }
2223   }
2224   
2225   // add (select X 0 (sub n A)) A  -->  select X A n
2226   {
2227     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2228     Value *A = RHS;
2229     if (!SI) {
2230       SI = dyn_cast<SelectInst>(RHS);
2231       A = LHS;
2232     }
2233     if (SI && SI->hasOneUse()) {
2234       Value *TV = SI->getTrueValue();
2235       Value *FV = SI->getFalseValue();
2236       Value *N;
2237
2238       // Can we fold the add into the argument of the select?
2239       // We check both true and false select arguments for a matching subtract.
2240       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2241         // Fold the add into the true select value.
2242         return SelectInst::Create(SI->getCondition(), N, A);
2243       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2244         // Fold the add into the false select value.
2245         return SelectInst::Create(SI->getCondition(), A, N);
2246     }
2247   }
2248   
2249   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2250   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2251     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2252       return ReplaceInstUsesWith(I, LHS);
2253
2254   // Check for (add (sext x), y), see if we can merge this into an
2255   // integer add followed by a sext.
2256   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2257     // (add (sext x), cst) --> (sext (add x, cst'))
2258     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2259       Constant *CI = 
2260         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2261       if (LHSConv->hasOneUse() &&
2262           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2263           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2264         // Insert the new, smaller add.
2265         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2266                                                         CI, "addconv");
2267         InsertNewInstBefore(NewAdd, I);
2268         return new SExtInst(NewAdd, I.getType());
2269       }
2270     }
2271     
2272     // (add (sext x), (sext y)) --> (sext (add int x, y))
2273     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2274       // Only do this if x/y have the same type, if at last one of them has a
2275       // single use (so we don't increase the number of sexts), and if the
2276       // integer add will not overflow.
2277       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2278           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2279           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2280                                    RHSConv->getOperand(0))) {
2281         // Insert the new integer add.
2282         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2283                                                         RHSConv->getOperand(0),
2284                                                         "addconv");
2285         InsertNewInstBefore(NewAdd, I);
2286         return new SExtInst(NewAdd, I.getType());
2287       }
2288     }
2289   }
2290   
2291   // Check for (add double (sitofp x), y), see if we can merge this into an
2292   // integer add followed by a promotion.
2293   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2294     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2295     // ... if the constant fits in the integer value.  This is useful for things
2296     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2297     // requires a constant pool load, and generally allows the add to be better
2298     // instcombined.
2299     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2300       Constant *CI = 
2301       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2302       if (LHSConv->hasOneUse() &&
2303           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2304           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2305         // Insert the new integer add.
2306         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2307                                                         CI, "addconv");
2308         InsertNewInstBefore(NewAdd, I);
2309         return new SIToFPInst(NewAdd, I.getType());
2310       }
2311     }
2312     
2313     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2314     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2315       // Only do this if x/y have the same type, if at last one of them has a
2316       // single use (so we don't increase the number of int->fp conversions),
2317       // and if the integer add will not overflow.
2318       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2319           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2320           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2321                                    RHSConv->getOperand(0))) {
2322         // Insert the new integer add.
2323         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2324                                                         RHSConv->getOperand(0),
2325                                                         "addconv");
2326         InsertNewInstBefore(NewAdd, I);
2327         return new SIToFPInst(NewAdd, I.getType());
2328       }
2329     }
2330   }
2331   
2332   return Changed ? &I : 0;
2333 }
2334
2335 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2336   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2337
2338   if (Op0 == Op1 &&                        // sub X, X  -> 0
2339       !I.getType()->isFPOrFPVector())
2340     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2341
2342   // If this is a 'B = x-(-A)', change to B = x+A...
2343   if (Value *V = dyn_castNegVal(Op1))
2344     return BinaryOperator::CreateAdd(Op0, V);
2345
2346   if (isa<UndefValue>(Op0))
2347     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2348   if (isa<UndefValue>(Op1))
2349     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2350
2351   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2352     // Replace (-1 - A) with (~A)...
2353     if (C->isAllOnesValue())
2354       return BinaryOperator::CreateNot(Op1);
2355
2356     // C - ~X == X + (1+C)
2357     Value *X = 0;
2358     if (match(Op1, m_Not(m_Value(X))))
2359       return BinaryOperator::CreateAdd(X, AddOne(C));
2360
2361     // -(X >>u 31) -> (X >>s 31)
2362     // -(X >>s 31) -> (X >>u 31)
2363     if (C->isZero()) {
2364       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2365         if (SI->getOpcode() == Instruction::LShr) {
2366           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2367             // Check to see if we are shifting out everything but the sign bit.
2368             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2369                 SI->getType()->getPrimitiveSizeInBits()-1) {
2370               // Ok, the transformation is safe.  Insert AShr.
2371               return BinaryOperator::Create(Instruction::AShr, 
2372                                           SI->getOperand(0), CU, SI->getName());
2373             }
2374           }
2375         }
2376         else if (SI->getOpcode() == Instruction::AShr) {
2377           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2378             // Check to see if we are shifting out everything but the sign bit.
2379             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2380                 SI->getType()->getPrimitiveSizeInBits()-1) {
2381               // Ok, the transformation is safe.  Insert LShr. 
2382               return BinaryOperator::CreateLShr(
2383                                           SI->getOperand(0), CU, SI->getName());
2384             }
2385           }
2386         }
2387       }
2388     }
2389
2390     // Try to fold constant sub into select arguments.
2391     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2392       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2393         return R;
2394   }
2395
2396   if (I.getType() == Type::Int1Ty)
2397     return BinaryOperator::CreateXor(Op0, Op1);
2398
2399   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2400     if (Op1I->getOpcode() == Instruction::Add &&
2401         !Op0->getType()->isFPOrFPVector()) {
2402       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2403         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2404       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2405         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2406       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2407         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2408           // C1-(X+C2) --> (C1-C2)-X
2409           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2410                                            Op1I->getOperand(0));
2411       }
2412     }
2413
2414     if (Op1I->hasOneUse()) {
2415       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2416       // is not used by anyone else...
2417       //
2418       if (Op1I->getOpcode() == Instruction::Sub &&
2419           !Op1I->getType()->isFPOrFPVector()) {
2420         // Swap the two operands of the subexpr...
2421         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2422         Op1I->setOperand(0, IIOp1);
2423         Op1I->setOperand(1, IIOp0);
2424
2425         // Create the new top level add instruction...
2426         return BinaryOperator::CreateAdd(Op0, Op1);
2427       }
2428
2429       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2430       //
2431       if (Op1I->getOpcode() == Instruction::And &&
2432           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2433         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2434
2435         Value *NewNot =
2436           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2437         return BinaryOperator::CreateAnd(Op0, NewNot);
2438       }
2439
2440       // 0 - (X sdiv C)  -> (X sdiv -C)
2441       if (Op1I->getOpcode() == Instruction::SDiv)
2442         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2443           if (CSI->isZero())
2444             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2445               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2446                                                ConstantExpr::getNeg(DivRHS));
2447
2448       // X - X*C --> X * (1-C)
2449       ConstantInt *C2 = 0;
2450       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2451         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2452         return BinaryOperator::CreateMul(Op0, CP1);
2453       }
2454     }
2455   }
2456
2457   if (!Op0->getType()->isFPOrFPVector())
2458     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2459       if (Op0I->getOpcode() == Instruction::Add) {
2460         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2461           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2462         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2463           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2464       } else if (Op0I->getOpcode() == Instruction::Sub) {
2465         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2466           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2467       }
2468     }
2469
2470   ConstantInt *C1;
2471   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2472     if (X == Op1)  // X*C - X --> X * (C-1)
2473       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2474
2475     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2476     if (X == dyn_castFoldableMul(Op1, C2))
2477       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2478   }
2479   return 0;
2480 }
2481
2482 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2483 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2484 /// TrueIfSigned if the result of the comparison is true when the input value is
2485 /// signed.
2486 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2487                            bool &TrueIfSigned) {
2488   switch (pred) {
2489   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2490     TrueIfSigned = true;
2491     return RHS->isZero();
2492   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2493     TrueIfSigned = true;
2494     return RHS->isAllOnesValue();
2495   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2496     TrueIfSigned = false;
2497     return RHS->isAllOnesValue();
2498   case ICmpInst::ICMP_UGT:
2499     // True if LHS u> RHS and RHS == high-bit-mask - 1
2500     TrueIfSigned = true;
2501     return RHS->getValue() ==
2502       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2503   case ICmpInst::ICMP_UGE: 
2504     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2505     TrueIfSigned = true;
2506     return RHS->getValue().isSignBit();
2507   default:
2508     return false;
2509   }
2510 }
2511
2512 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2513   bool Changed = SimplifyCommutative(I);
2514   Value *Op0 = I.getOperand(0);
2515
2516   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2517     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2518
2519   // Simplify mul instructions with a constant RHS...
2520   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2521     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2522
2523       // ((X << C1)*C2) == (X * (C2 << C1))
2524       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2525         if (SI->getOpcode() == Instruction::Shl)
2526           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2527             return BinaryOperator::CreateMul(SI->getOperand(0),
2528                                              ConstantExpr::getShl(CI, ShOp));
2529
2530       if (CI->isZero())
2531         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2532       if (CI->equalsInt(1))                  // X * 1  == X
2533         return ReplaceInstUsesWith(I, Op0);
2534       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2535         return BinaryOperator::CreateNeg(Op0, I.getName());
2536
2537       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2538       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2539         return BinaryOperator::CreateShl(Op0,
2540                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2541       }
2542     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2543       if (Op1F->isNullValue())
2544         return ReplaceInstUsesWith(I, Op1);
2545
2546       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2547       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2548       if (Op1F->isExactlyValue(1.0))
2549         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2550     } else if (isa<VectorType>(Op1->getType())) {
2551       if (isa<ConstantAggregateZero>(Op1))
2552         return ReplaceInstUsesWith(I, Op1);
2553
2554       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2555         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2556           return BinaryOperator::CreateNeg(Op0, I.getName());
2557
2558         // As above, vector X*splat(1.0) -> X in all defined cases.
2559         if (Constant *Splat = Op1V->getSplatValue()) {
2560           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2561             if (F->isExactlyValue(1.0))
2562               return ReplaceInstUsesWith(I, Op0);
2563           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2564             if (CI->equalsInt(1))
2565               return ReplaceInstUsesWith(I, Op0);
2566         }
2567       }
2568     }
2569     
2570     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2571       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2572           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2573         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2574         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2575                                                      Op1, "tmp");
2576         InsertNewInstBefore(Add, I);
2577         Value *C1C2 = ConstantExpr::getMul(Op1, 
2578                                            cast<Constant>(Op0I->getOperand(1)));
2579         return BinaryOperator::CreateAdd(Add, C1C2);
2580         
2581       }
2582
2583     // Try to fold constant mul into select arguments.
2584     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2585       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2586         return R;
2587
2588     if (isa<PHINode>(Op0))
2589       if (Instruction *NV = FoldOpIntoPhi(I))
2590         return NV;
2591   }
2592
2593   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2594     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2595       return BinaryOperator::CreateMul(Op0v, Op1v);
2596
2597   // (X / Y) *  Y = X - (X % Y)
2598   // (X / Y) * -Y = (X % Y) - X
2599   {
2600     Value *Op1 = I.getOperand(1);
2601     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2602     if (!BO ||
2603         (BO->getOpcode() != Instruction::UDiv && 
2604          BO->getOpcode() != Instruction::SDiv)) {
2605       Op1 = Op0;
2606       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2607     }
2608     Value *Neg = dyn_castNegVal(Op1);
2609     if (BO && BO->hasOneUse() &&
2610         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2611         (BO->getOpcode() == Instruction::UDiv ||
2612          BO->getOpcode() == Instruction::SDiv)) {
2613       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2614
2615       Instruction *Rem;
2616       if (BO->getOpcode() == Instruction::UDiv)
2617         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2618       else
2619         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2620
2621       InsertNewInstBefore(Rem, I);
2622       Rem->takeName(BO);
2623
2624       if (Op1BO == Op1)
2625         return BinaryOperator::CreateSub(Op0BO, Rem);
2626       else
2627         return BinaryOperator::CreateSub(Rem, Op0BO);
2628     }
2629   }
2630
2631   if (I.getType() == Type::Int1Ty)
2632     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2633
2634   // If one of the operands of the multiply is a cast from a boolean value, then
2635   // we know the bool is either zero or one, so this is a 'masking' multiply.
2636   // See if we can simplify things based on how the boolean was originally
2637   // formed.
2638   CastInst *BoolCast = 0;
2639   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2640     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2641       BoolCast = CI;
2642   if (!BoolCast)
2643     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2644       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2645         BoolCast = CI;
2646   if (BoolCast) {
2647     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2648       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2649       const Type *SCOpTy = SCIOp0->getType();
2650       bool TIS = false;
2651       
2652       // If the icmp is true iff the sign bit of X is set, then convert this
2653       // multiply into a shift/and combination.
2654       if (isa<ConstantInt>(SCIOp1) &&
2655           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2656           TIS) {
2657         // Shift the X value right to turn it into "all signbits".
2658         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2659                                           SCOpTy->getPrimitiveSizeInBits()-1);
2660         Value *V =
2661           InsertNewInstBefore(
2662             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2663                                             BoolCast->getOperand(0)->getName()+
2664                                             ".mask"), I);
2665
2666         // If the multiply type is not the same as the source type, sign extend
2667         // or truncate to the multiply type.
2668         if (I.getType() != V->getType()) {
2669           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2670           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2671           Instruction::CastOps opcode = 
2672             (SrcBits == DstBits ? Instruction::BitCast : 
2673              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2674           V = InsertCastBefore(opcode, V, I.getType(), I);
2675         }
2676
2677         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2678         return BinaryOperator::CreateAnd(V, OtherOp);
2679       }
2680     }
2681   }
2682
2683   return Changed ? &I : 0;
2684 }
2685
2686 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2687 /// instruction.
2688 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2689   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2690   
2691   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2692   int NonNullOperand = -1;
2693   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2694     if (ST->isNullValue())
2695       NonNullOperand = 2;
2696   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2697   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2698     if (ST->isNullValue())
2699       NonNullOperand = 1;
2700   
2701   if (NonNullOperand == -1)
2702     return false;
2703   
2704   Value *SelectCond = SI->getOperand(0);
2705   
2706   // Change the div/rem to use 'Y' instead of the select.
2707   I.setOperand(1, SI->getOperand(NonNullOperand));
2708   
2709   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2710   // problem.  However, the select, or the condition of the select may have
2711   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2712   // propagate the known value for the select into other uses of it, and
2713   // propagate a known value of the condition into its other users.
2714   
2715   // If the select and condition only have a single use, don't bother with this,
2716   // early exit.
2717   if (SI->use_empty() && SelectCond->hasOneUse())
2718     return true;
2719   
2720   // Scan the current block backward, looking for other uses of SI.
2721   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2722   
2723   while (BBI != BBFront) {
2724     --BBI;
2725     // If we found a call to a function, we can't assume it will return, so
2726     // information from below it cannot be propagated above it.
2727     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2728       break;
2729     
2730     // Replace uses of the select or its condition with the known values.
2731     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2732          I != E; ++I) {
2733       if (*I == SI) {
2734         *I = SI->getOperand(NonNullOperand);
2735         AddToWorkList(BBI);
2736       } else if (*I == SelectCond) {
2737         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2738                                    ConstantInt::getFalse();
2739         AddToWorkList(BBI);
2740       }
2741     }
2742     
2743     // If we past the instruction, quit looking for it.
2744     if (&*BBI == SI)
2745       SI = 0;
2746     if (&*BBI == SelectCond)
2747       SelectCond = 0;
2748     
2749     // If we ran out of things to eliminate, break out of the loop.
2750     if (SelectCond == 0 && SI == 0)
2751       break;
2752     
2753   }
2754   return true;
2755 }
2756
2757
2758 /// This function implements the transforms on div instructions that work
2759 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2760 /// used by the visitors to those instructions.
2761 /// @brief Transforms common to all three div instructions
2762 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2763   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2764
2765   // undef / X -> 0        for integer.
2766   // undef / X -> undef    for FP (the undef could be a snan).
2767   if (isa<UndefValue>(Op0)) {
2768     if (Op0->getType()->isFPOrFPVector())
2769       return ReplaceInstUsesWith(I, Op0);
2770     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2771   }
2772
2773   // X / undef -> undef
2774   if (isa<UndefValue>(Op1))
2775     return ReplaceInstUsesWith(I, Op1);
2776
2777   return 0;
2778 }
2779
2780 /// This function implements the transforms common to both integer division
2781 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2782 /// division instructions.
2783 /// @brief Common integer divide transforms
2784 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2785   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2786
2787   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2788   if (Op0 == Op1) {
2789     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2790       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2791       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2792       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2793     }
2794
2795     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2796     return ReplaceInstUsesWith(I, CI);
2797   }
2798   
2799   if (Instruction *Common = commonDivTransforms(I))
2800     return Common;
2801   
2802   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2803   // This does not apply for fdiv.
2804   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2805     return &I;
2806
2807   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2808     // div X, 1 == X
2809     if (RHS->equalsInt(1))
2810       return ReplaceInstUsesWith(I, Op0);
2811
2812     // (X / C1) / C2  -> X / (C1*C2)
2813     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2814       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2815         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2816           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2817             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2818           else 
2819             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2820                                           Multiply(RHS, LHSRHS));
2821         }
2822
2823     if (!RHS->isZero()) { // avoid X udiv 0
2824       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2825         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2826           return R;
2827       if (isa<PHINode>(Op0))
2828         if (Instruction *NV = FoldOpIntoPhi(I))
2829           return NV;
2830     }
2831   }
2832
2833   // 0 / X == 0, we don't need to preserve faults!
2834   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2835     if (LHS->equalsInt(0))
2836       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2837
2838   // It can't be division by zero, hence it must be division by one.
2839   if (I.getType() == Type::Int1Ty)
2840     return ReplaceInstUsesWith(I, Op0);
2841
2842   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2843     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2844       // div X, 1 == X
2845       if (X->isOne())
2846         return ReplaceInstUsesWith(I, Op0);
2847   }
2848
2849   return 0;
2850 }
2851
2852 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2853   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2854
2855   // Handle the integer div common cases
2856   if (Instruction *Common = commonIDivTransforms(I))
2857     return Common;
2858
2859   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2860     // X udiv C^2 -> X >> C
2861     // Check to see if this is an unsigned division with an exact power of 2,
2862     // if so, convert to a right shift.
2863     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2864       return BinaryOperator::CreateLShr(Op0, 
2865                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2866
2867     // X udiv C, where C >= signbit
2868     if (C->getValue().isNegative()) {
2869       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2870                                       I);
2871       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2872                                 ConstantInt::get(I.getType(), 1));
2873     }
2874   }
2875
2876   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2877   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2878     if (RHSI->getOpcode() == Instruction::Shl &&
2879         isa<ConstantInt>(RHSI->getOperand(0))) {
2880       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2881       if (C1.isPowerOf2()) {
2882         Value *N = RHSI->getOperand(1);
2883         const Type *NTy = N->getType();
2884         if (uint32_t C2 = C1.logBase2()) {
2885           Constant *C2V = ConstantInt::get(NTy, C2);
2886           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2887         }
2888         return BinaryOperator::CreateLShr(Op0, N);
2889       }
2890     }
2891   }
2892   
2893   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2894   // where C1&C2 are powers of two.
2895   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2896     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2897       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2898         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2899         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2900           // Compute the shift amounts
2901           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2902           // Construct the "on true" case of the select
2903           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2904           Instruction *TSI = BinaryOperator::CreateLShr(
2905                                                  Op0, TC, SI->getName()+".t");
2906           TSI = InsertNewInstBefore(TSI, I);
2907   
2908           // Construct the "on false" case of the select
2909           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2910           Instruction *FSI = BinaryOperator::CreateLShr(
2911                                                  Op0, FC, SI->getName()+".f");
2912           FSI = InsertNewInstBefore(FSI, I);
2913
2914           // construct the select instruction and return it.
2915           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2916         }
2917       }
2918   return 0;
2919 }
2920
2921 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2922   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2923
2924   // Handle the integer div common cases
2925   if (Instruction *Common = commonIDivTransforms(I))
2926     return Common;
2927
2928   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2929     // sdiv X, -1 == -X
2930     if (RHS->isAllOnesValue())
2931       return BinaryOperator::CreateNeg(Op0);
2932   }
2933
2934   // If the sign bits of both operands are zero (i.e. we can prove they are
2935   // unsigned inputs), turn this into a udiv.
2936   if (I.getType()->isInteger()) {
2937     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2938     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2939       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2940       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2941     }
2942   }      
2943   
2944   return 0;
2945 }
2946
2947 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2948   return commonDivTransforms(I);
2949 }
2950
2951 /// This function implements the transforms on rem instructions that work
2952 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2953 /// is used by the visitors to those instructions.
2954 /// @brief Transforms common to all three rem instructions
2955 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2956   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2957
2958   // 0 % X == 0 for integer, we don't need to preserve faults!
2959   if (Constant *LHS = dyn_cast<Constant>(Op0))
2960     if (LHS->isNullValue())
2961       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2962
2963   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2964     if (I.getType()->isFPOrFPVector())
2965       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2966     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2967   }
2968   if (isa<UndefValue>(Op1))
2969     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2970
2971   // Handle cases involving: rem X, (select Cond, Y, Z)
2972   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2973     return &I;
2974
2975   return 0;
2976 }
2977
2978 /// This function implements the transforms common to both integer remainder
2979 /// instructions (urem and srem). It is called by the visitors to those integer
2980 /// remainder instructions.
2981 /// @brief Common integer remainder transforms
2982 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2983   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2984
2985   if (Instruction *common = commonRemTransforms(I))
2986     return common;
2987
2988   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2989     // X % 0 == undef, we don't need to preserve faults!
2990     if (RHS->equalsInt(0))
2991       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2992     
2993     if (RHS->equalsInt(1))  // X % 1 == 0
2994       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2995
2996     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2997       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2998         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2999           return R;
3000       } else if (isa<PHINode>(Op0I)) {
3001         if (Instruction *NV = FoldOpIntoPhi(I))
3002           return NV;
3003       }
3004
3005       // See if we can fold away this rem instruction.
3006       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3007       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3008       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3009                                KnownZero, KnownOne))
3010         return &I;
3011     }
3012   }
3013
3014   return 0;
3015 }
3016
3017 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3018   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3019
3020   if (Instruction *common = commonIRemTransforms(I))
3021     return common;
3022   
3023   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3024     // X urem C^2 -> X and C
3025     // Check to see if this is an unsigned remainder with an exact power of 2,
3026     // if so, convert to a bitwise and.
3027     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3028       if (C->getValue().isPowerOf2())
3029         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3030   }
3031
3032   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3033     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3034     if (RHSI->getOpcode() == Instruction::Shl &&
3035         isa<ConstantInt>(RHSI->getOperand(0))) {
3036       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3037         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3038         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3039                                                                    "tmp"), I);
3040         return BinaryOperator::CreateAnd(Op0, Add);
3041       }
3042     }
3043   }
3044
3045   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3046   // where C1&C2 are powers of two.
3047   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3048     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3049       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3050         // STO == 0 and SFO == 0 handled above.
3051         if ((STO->getValue().isPowerOf2()) && 
3052             (SFO->getValue().isPowerOf2())) {
3053           Value *TrueAnd = InsertNewInstBefore(
3054             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3055           Value *FalseAnd = InsertNewInstBefore(
3056             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3057           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3058         }
3059       }
3060   }
3061   
3062   return 0;
3063 }
3064
3065 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3066   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3067
3068   // Handle the integer rem common cases
3069   if (Instruction *common = commonIRemTransforms(I))
3070     return common;
3071   
3072   if (Value *RHSNeg = dyn_castNegVal(Op1))
3073     if (!isa<Constant>(RHSNeg) ||
3074         (isa<ConstantInt>(RHSNeg) &&
3075          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3076       // X % -Y -> X % Y
3077       AddUsesToWorkList(I);
3078       I.setOperand(1, RHSNeg);
3079       return &I;
3080     }
3081
3082   // If the sign bits of both operands are zero (i.e. we can prove they are
3083   // unsigned inputs), turn this into a urem.
3084   if (I.getType()->isInteger()) {
3085     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3086     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3087       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3088       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3089     }
3090   }
3091
3092   // If it's a constant vector, flip any negative values positive.
3093   if (isa<VectorType>(I.getType())) {
3094     if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3095       unsigned VWidth = RHSV->getNumOperands();
3096       std::vector<Constant *> Elts(VWidth);
3097
3098       for (unsigned i = 0; i != VWidth; ++i) {
3099         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3100           if (RHS->getValue().isNegative())
3101             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3102           else
3103             Elts[i] = RHS;
3104         }
3105       }
3106
3107       Constant *NewRHSV = ConstantVector::get(Elts);
3108       if (NewRHSV != RHSV) {
3109         I.setOperand(1, NewRHSV);
3110         return &I;
3111       }
3112     }
3113   }
3114
3115   return 0;
3116 }
3117
3118 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3119   return commonRemTransforms(I);
3120 }
3121
3122 // isOneBitSet - Return true if there is exactly one bit set in the specified
3123 // constant.
3124 static bool isOneBitSet(const ConstantInt *CI) {
3125   return CI->getValue().isPowerOf2();
3126 }
3127
3128 // isHighOnes - Return true if the constant is of the form 1+0+.
3129 // This is the same as lowones(~X).
3130 static bool isHighOnes(const ConstantInt *CI) {
3131   return (~CI->getValue() + 1).isPowerOf2();
3132 }
3133
3134 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3135 /// are carefully arranged to allow folding of expressions such as:
3136 ///
3137 ///      (A < B) | (A > B) --> (A != B)
3138 ///
3139 /// Note that this is only valid if the first and second predicates have the
3140 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3141 ///
3142 /// Three bits are used to represent the condition, as follows:
3143 ///   0  A > B
3144 ///   1  A == B
3145 ///   2  A < B
3146 ///
3147 /// <=>  Value  Definition
3148 /// 000     0   Always false
3149 /// 001     1   A >  B
3150 /// 010     2   A == B
3151 /// 011     3   A >= B
3152 /// 100     4   A <  B
3153 /// 101     5   A != B
3154 /// 110     6   A <= B
3155 /// 111     7   Always true
3156 ///  
3157 static unsigned getICmpCode(const ICmpInst *ICI) {
3158   switch (ICI->getPredicate()) {
3159     // False -> 0
3160   case ICmpInst::ICMP_UGT: return 1;  // 001
3161   case ICmpInst::ICMP_SGT: return 1;  // 001
3162   case ICmpInst::ICMP_EQ:  return 2;  // 010
3163   case ICmpInst::ICMP_UGE: return 3;  // 011
3164   case ICmpInst::ICMP_SGE: return 3;  // 011
3165   case ICmpInst::ICMP_ULT: return 4;  // 100
3166   case ICmpInst::ICMP_SLT: return 4;  // 100
3167   case ICmpInst::ICMP_NE:  return 5;  // 101
3168   case ICmpInst::ICMP_ULE: return 6;  // 110
3169   case ICmpInst::ICMP_SLE: return 6;  // 110
3170     // True -> 7
3171   default:
3172     assert(0 && "Invalid ICmp predicate!");
3173     return 0;
3174   }
3175 }
3176
3177 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3178 /// predicate into a three bit mask. It also returns whether it is an ordered
3179 /// predicate by reference.
3180 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3181   isOrdered = false;
3182   switch (CC) {
3183   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3184   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3185   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3186   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3187   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3188   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3189   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3190   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3191   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3192   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3193   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3194   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3195   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3196   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3197     // True -> 7
3198   default:
3199     // Not expecting FCMP_FALSE and FCMP_TRUE;
3200     assert(0 && "Unexpected FCmp predicate!");
3201     return 0;
3202   }
3203 }
3204
3205 /// getICmpValue - This is the complement of getICmpCode, which turns an
3206 /// opcode and two operands into either a constant true or false, or a brand 
3207 /// new ICmp instruction. The sign is passed in to determine which kind
3208 /// of predicate to use in the new icmp instruction.
3209 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3210   switch (code) {
3211   default: assert(0 && "Illegal ICmp code!");
3212   case  0: return ConstantInt::getFalse();
3213   case  1: 
3214     if (sign)
3215       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3216     else
3217       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3218   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3219   case  3: 
3220     if (sign)
3221       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3222     else
3223       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3224   case  4: 
3225     if (sign)
3226       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3227     else
3228       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3229   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3230   case  6: 
3231     if (sign)
3232       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3233     else
3234       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3235   case  7: return ConstantInt::getTrue();
3236   }
3237 }
3238
3239 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3240 /// opcode and two operands into either a FCmp instruction. isordered is passed
3241 /// in to determine which kind of predicate to use in the new fcmp instruction.
3242 static Value *getFCmpValue(bool isordered, unsigned code,
3243                            Value *LHS, Value *RHS) {
3244   switch (code) {
3245   default: assert(0 && "Illegal FCmp code!");
3246   case  0:
3247     if (isordered)
3248       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3249     else
3250       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3251   case  1: 
3252     if (isordered)
3253       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3254     else
3255       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3256   case  2: 
3257     if (isordered)
3258       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3259     else
3260       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3261   case  3: 
3262     if (isordered)
3263       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3264     else
3265       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3266   case  4: 
3267     if (isordered)
3268       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3269     else
3270       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3271   case  5: 
3272     if (isordered)
3273       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3274     else
3275       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3276   case  6: 
3277     if (isordered)
3278       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3279     else
3280       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3281   case  7: return ConstantInt::getTrue();
3282   }
3283 }
3284
3285 /// PredicatesFoldable - Return true if both predicates match sign or if at
3286 /// least one of them is an equality comparison (which is signless).
3287 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3288   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3289          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3290          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3291 }
3292
3293 namespace { 
3294 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3295 struct FoldICmpLogical {
3296   InstCombiner &IC;
3297   Value *LHS, *RHS;
3298   ICmpInst::Predicate pred;
3299   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3300     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3301       pred(ICI->getPredicate()) {}
3302   bool shouldApply(Value *V) const {
3303     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3304       if (PredicatesFoldable(pred, ICI->getPredicate()))
3305         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3306                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3307     return false;
3308   }
3309   Instruction *apply(Instruction &Log) const {
3310     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3311     if (ICI->getOperand(0) != LHS) {
3312       assert(ICI->getOperand(1) == LHS);
3313       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3314     }
3315
3316     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3317     unsigned LHSCode = getICmpCode(ICI);
3318     unsigned RHSCode = getICmpCode(RHSICI);
3319     unsigned Code;
3320     switch (Log.getOpcode()) {
3321     case Instruction::And: Code = LHSCode & RHSCode; break;
3322     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3323     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3324     default: assert(0 && "Illegal logical opcode!"); return 0;
3325     }
3326
3327     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3328                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3329       
3330     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3331     if (Instruction *I = dyn_cast<Instruction>(RV))
3332       return I;
3333     // Otherwise, it's a constant boolean value...
3334     return IC.ReplaceInstUsesWith(Log, RV);
3335   }
3336 };
3337 } // end anonymous namespace
3338
3339 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3340 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3341 // guaranteed to be a binary operator.
3342 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3343                                     ConstantInt *OpRHS,
3344                                     ConstantInt *AndRHS,
3345                                     BinaryOperator &TheAnd) {
3346   Value *X = Op->getOperand(0);
3347   Constant *Together = 0;
3348   if (!Op->isShift())
3349     Together = And(AndRHS, OpRHS);
3350
3351   switch (Op->getOpcode()) {
3352   case Instruction::Xor:
3353     if (Op->hasOneUse()) {
3354       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3355       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3356       InsertNewInstBefore(And, TheAnd);
3357       And->takeName(Op);
3358       return BinaryOperator::CreateXor(And, Together);
3359     }
3360     break;
3361   case Instruction::Or:
3362     if (Together == AndRHS) // (X | C) & C --> C
3363       return ReplaceInstUsesWith(TheAnd, AndRHS);
3364
3365     if (Op->hasOneUse() && Together != OpRHS) {
3366       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3367       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3368       InsertNewInstBefore(Or, TheAnd);
3369       Or->takeName(Op);
3370       return BinaryOperator::CreateAnd(Or, AndRHS);
3371     }
3372     break;
3373   case Instruction::Add:
3374     if (Op->hasOneUse()) {
3375       // Adding a one to a single bit bit-field should be turned into an XOR
3376       // of the bit.  First thing to check is to see if this AND is with a
3377       // single bit constant.
3378       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3379
3380       // If there is only one bit set...
3381       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3382         // Ok, at this point, we know that we are masking the result of the
3383         // ADD down to exactly one bit.  If the constant we are adding has
3384         // no bits set below this bit, then we can eliminate the ADD.
3385         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3386
3387         // Check to see if any bits below the one bit set in AndRHSV are set.
3388         if ((AddRHS & (AndRHSV-1)) == 0) {
3389           // If not, the only thing that can effect the output of the AND is
3390           // the bit specified by AndRHSV.  If that bit is set, the effect of
3391           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3392           // no effect.
3393           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3394             TheAnd.setOperand(0, X);
3395             return &TheAnd;
3396           } else {
3397             // Pull the XOR out of the AND.
3398             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3399             InsertNewInstBefore(NewAnd, TheAnd);
3400             NewAnd->takeName(Op);
3401             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3402           }
3403         }
3404       }
3405     }
3406     break;
3407
3408   case Instruction::Shl: {
3409     // We know that the AND will not produce any of the bits shifted in, so if
3410     // the anded constant includes them, clear them now!
3411     //
3412     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3413     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3414     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3415     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3416
3417     if (CI->getValue() == ShlMask) { 
3418     // Masking out bits that the shift already masks
3419       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3420     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3421       TheAnd.setOperand(1, CI);
3422       return &TheAnd;
3423     }
3424     break;
3425   }
3426   case Instruction::LShr:
3427   {
3428     // We know that the AND will not produce any of the bits shifted in, so if
3429     // the anded constant includes them, clear them now!  This only applies to
3430     // unsigned shifts, because a signed shr may bring in set bits!
3431     //
3432     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3433     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3434     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3435     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3436
3437     if (CI->getValue() == ShrMask) {   
3438     // Masking out bits that the shift already masks.
3439       return ReplaceInstUsesWith(TheAnd, Op);
3440     } else if (CI != AndRHS) {
3441       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3442       return &TheAnd;
3443     }
3444     break;
3445   }
3446   case Instruction::AShr:
3447     // Signed shr.
3448     // See if this is shifting in some sign extension, then masking it out
3449     // with an and.
3450     if (Op->hasOneUse()) {
3451       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3452       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3453       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3454       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3455       if (C == AndRHS) {          // Masking out bits shifted in.
3456         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3457         // Make the argument unsigned.
3458         Value *ShVal = Op->getOperand(0);
3459         ShVal = InsertNewInstBefore(
3460             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3461                                    Op->getName()), TheAnd);
3462         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3463       }
3464     }
3465     break;
3466   }
3467   return 0;
3468 }
3469
3470
3471 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3472 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3473 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3474 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3475 /// insert new instructions.
3476 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3477                                            bool isSigned, bool Inside, 
3478                                            Instruction &IB) {
3479   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3480             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3481          "Lo is not <= Hi in range emission code!");
3482     
3483   if (Inside) {
3484     if (Lo == Hi)  // Trivially false.
3485       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3486
3487     // V >= Min && V < Hi --> V < Hi
3488     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3489       ICmpInst::Predicate pred = (isSigned ? 
3490         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3491       return new ICmpInst(pred, V, Hi);
3492     }
3493
3494     // Emit V-Lo <u Hi-Lo
3495     Constant *NegLo = ConstantExpr::getNeg(Lo);
3496     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3497     InsertNewInstBefore(Add, IB);
3498     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3499     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3500   }
3501
3502   if (Lo == Hi)  // Trivially true.
3503     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3504
3505   // V < Min || V >= Hi -> V > Hi-1
3506   Hi = SubOne(cast<ConstantInt>(Hi));
3507   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3508     ICmpInst::Predicate pred = (isSigned ? 
3509         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3510     return new ICmpInst(pred, V, Hi);
3511   }
3512
3513   // Emit V-Lo >u Hi-1-Lo
3514   // Note that Hi has already had one subtracted from it, above.
3515   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3516   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3517   InsertNewInstBefore(Add, IB);
3518   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3519   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3520 }
3521
3522 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3523 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3524 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3525 // not, since all 1s are not contiguous.
3526 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3527   const APInt& V = Val->getValue();
3528   uint32_t BitWidth = Val->getType()->getBitWidth();
3529   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3530
3531   // look for the first zero bit after the run of ones
3532   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3533   // look for the first non-zero bit
3534   ME = V.getActiveBits(); 
3535   return true;
3536 }
3537
3538 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3539 /// where isSub determines whether the operator is a sub.  If we can fold one of
3540 /// the following xforms:
3541 /// 
3542 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3543 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3544 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3545 ///
3546 /// return (A +/- B).
3547 ///
3548 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3549                                         ConstantInt *Mask, bool isSub,
3550                                         Instruction &I) {
3551   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3552   if (!LHSI || LHSI->getNumOperands() != 2 ||
3553       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3554
3555   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3556
3557   switch (LHSI->getOpcode()) {
3558   default: return 0;
3559   case Instruction::And:
3560     if (And(N, Mask) == Mask) {
3561       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3562       if ((Mask->getValue().countLeadingZeros() + 
3563            Mask->getValue().countPopulation()) == 
3564           Mask->getValue().getBitWidth())
3565         break;
3566
3567       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3568       // part, we don't need any explicit masks to take them out of A.  If that
3569       // is all N is, ignore it.
3570       uint32_t MB = 0, ME = 0;
3571       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3572         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3573         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3574         if (MaskedValueIsZero(RHS, Mask))
3575           break;
3576       }
3577     }
3578     return 0;
3579   case Instruction::Or:
3580   case Instruction::Xor:
3581     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3582     if ((Mask->getValue().countLeadingZeros() + 
3583          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3584         && And(N, Mask)->isZero())
3585       break;
3586     return 0;
3587   }
3588   
3589   Instruction *New;
3590   if (isSub)
3591     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3592   else
3593     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3594   return InsertNewInstBefore(New, I);
3595 }
3596
3597 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3598 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3599                                           ICmpInst *LHS, ICmpInst *RHS) {
3600   Value *Val, *Val2;
3601   ConstantInt *LHSCst, *RHSCst;
3602   ICmpInst::Predicate LHSCC, RHSCC;
3603   
3604   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3605   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3606       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3607     return 0;
3608   
3609   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3610   // where C is a power of 2
3611   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3612       LHSCst->getValue().isPowerOf2()) {
3613     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3614     InsertNewInstBefore(NewOr, I);
3615     return new ICmpInst(LHSCC, NewOr, LHSCst);
3616   }
3617   
3618   // From here on, we only handle:
3619   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3620   if (Val != Val2) return 0;
3621   
3622   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3623   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3624       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3625       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3626       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3627     return 0;
3628   
3629   // We can't fold (ugt x, C) & (sgt x, C2).
3630   if (!PredicatesFoldable(LHSCC, RHSCC))
3631     return 0;
3632     
3633   // Ensure that the larger constant is on the RHS.
3634   bool ShouldSwap;
3635   if (ICmpInst::isSignedPredicate(LHSCC) ||
3636       (ICmpInst::isEquality(LHSCC) && 
3637        ICmpInst::isSignedPredicate(RHSCC)))
3638     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3639   else
3640     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3641     
3642   if (ShouldSwap) {
3643     std::swap(LHS, RHS);
3644     std::swap(LHSCst, RHSCst);
3645     std::swap(LHSCC, RHSCC);
3646   }
3647
3648   // At this point, we know we have have two icmp instructions
3649   // comparing a value against two constants and and'ing the result
3650   // together.  Because of the above check, we know that we only have
3651   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3652   // (from the FoldICmpLogical check above), that the two constants 
3653   // are not equal and that the larger constant is on the RHS
3654   assert(LHSCst != RHSCst && "Compares not folded above?");
3655
3656   switch (LHSCC) {
3657   default: assert(0 && "Unknown integer condition code!");
3658   case ICmpInst::ICMP_EQ:
3659     switch (RHSCC) {
3660     default: assert(0 && "Unknown integer condition code!");
3661     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3662     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3663     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3664       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3665     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3666     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3667     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3668       return ReplaceInstUsesWith(I, LHS);
3669     }
3670   case ICmpInst::ICMP_NE:
3671     switch (RHSCC) {
3672     default: assert(0 && "Unknown integer condition code!");
3673     case ICmpInst::ICMP_ULT:
3674       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3675         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3676       break;                        // (X != 13 & X u< 15) -> no change
3677     case ICmpInst::ICMP_SLT:
3678       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3679         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3680       break;                        // (X != 13 & X s< 15) -> no change
3681     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3682     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3683     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3684       return ReplaceInstUsesWith(I, RHS);
3685     case ICmpInst::ICMP_NE:
3686       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3687         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3688         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3689                                                      Val->getName()+".off");
3690         InsertNewInstBefore(Add, I);
3691         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3692                             ConstantInt::get(Add->getType(), 1));
3693       }
3694       break;                        // (X != 13 & X != 15) -> no change
3695     }
3696     break;
3697   case ICmpInst::ICMP_ULT:
3698     switch (RHSCC) {
3699     default: assert(0 && "Unknown integer condition code!");
3700     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3701     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3702       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3703     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3704       break;
3705     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3706     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3707       return ReplaceInstUsesWith(I, LHS);
3708     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3709       break;
3710     }
3711     break;
3712   case ICmpInst::ICMP_SLT:
3713     switch (RHSCC) {
3714     default: assert(0 && "Unknown integer condition code!");
3715     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3716     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3717       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3718     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3719       break;
3720     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3721     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3722       return ReplaceInstUsesWith(I, LHS);
3723     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3724       break;
3725     }
3726     break;
3727   case ICmpInst::ICMP_UGT:
3728     switch (RHSCC) {
3729     default: assert(0 && "Unknown integer condition code!");
3730     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3731     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3732       return ReplaceInstUsesWith(I, RHS);
3733     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3734       break;
3735     case ICmpInst::ICMP_NE:
3736       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3737         return new ICmpInst(LHSCC, Val, RHSCst);
3738       break;                        // (X u> 13 & X != 15) -> no change
3739     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3740       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3741     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3742       break;
3743     }
3744     break;
3745   case ICmpInst::ICMP_SGT:
3746     switch (RHSCC) {
3747     default: assert(0 && "Unknown integer condition code!");
3748     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3749     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3750       return ReplaceInstUsesWith(I, RHS);
3751     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3752       break;
3753     case ICmpInst::ICMP_NE:
3754       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3755         return new ICmpInst(LHSCC, Val, RHSCst);
3756       break;                        // (X s> 13 & X != 15) -> no change
3757     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3758       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3759     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3760       break;
3761     }
3762     break;
3763   }
3764  
3765   return 0;
3766 }
3767
3768
3769 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3770   bool Changed = SimplifyCommutative(I);
3771   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3772
3773   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3774     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3775
3776   // and X, X = X
3777   if (Op0 == Op1)
3778     return ReplaceInstUsesWith(I, Op1);
3779
3780   // See if we can simplify any instructions used by the instruction whose sole 
3781   // purpose is to compute bits we don't care about.
3782   if (!isa<VectorType>(I.getType())) {
3783     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3784     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3785     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3786                              KnownZero, KnownOne))
3787       return &I;
3788   } else {
3789     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3790       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3791         return ReplaceInstUsesWith(I, I.getOperand(0));
3792     } else if (isa<ConstantAggregateZero>(Op1)) {
3793       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3794     }
3795   }
3796   
3797   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3798     const APInt& AndRHSMask = AndRHS->getValue();
3799     APInt NotAndRHS(~AndRHSMask);
3800
3801     // Optimize a variety of ((val OP C1) & C2) combinations...
3802     if (isa<BinaryOperator>(Op0)) {
3803       Instruction *Op0I = cast<Instruction>(Op0);
3804       Value *Op0LHS = Op0I->getOperand(0);
3805       Value *Op0RHS = Op0I->getOperand(1);
3806       switch (Op0I->getOpcode()) {
3807       case Instruction::Xor:
3808       case Instruction::Or:
3809         // If the mask is only needed on one incoming arm, push it up.
3810         if (Op0I->hasOneUse()) {
3811           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3812             // Not masking anything out for the LHS, move to RHS.
3813             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3814                                                    Op0RHS->getName()+".masked");
3815             InsertNewInstBefore(NewRHS, I);
3816             return BinaryOperator::Create(
3817                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3818           }
3819           if (!isa<Constant>(Op0RHS) &&
3820               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3821             // Not masking anything out for the RHS, move to LHS.
3822             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3823                                                    Op0LHS->getName()+".masked");
3824             InsertNewInstBefore(NewLHS, I);
3825             return BinaryOperator::Create(
3826                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3827           }
3828         }
3829
3830         break;
3831       case Instruction::Add:
3832         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3833         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3834         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3835         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3836           return BinaryOperator::CreateAnd(V, AndRHS);
3837         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3838           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3839         break;
3840
3841       case Instruction::Sub:
3842         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3843         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3844         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3845         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3846           return BinaryOperator::CreateAnd(V, AndRHS);
3847
3848         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3849         // has 1's for all bits that the subtraction with A might affect.
3850         if (Op0I->hasOneUse()) {
3851           uint32_t BitWidth = AndRHSMask.getBitWidth();
3852           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3853           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3854
3855           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3856           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3857               MaskedValueIsZero(Op0LHS, Mask)) {
3858             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3859             InsertNewInstBefore(NewNeg, I);
3860             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3861           }
3862         }
3863         break;
3864
3865       case Instruction::Shl:
3866       case Instruction::LShr:
3867         // (1 << x) & 1 --> zext(x == 0)
3868         // (1 >> x) & 1 --> zext(x == 0)
3869         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3870           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3871                                            Constant::getNullValue(I.getType()));
3872           InsertNewInstBefore(NewICmp, I);
3873           return new ZExtInst(NewICmp, I.getType());
3874         }
3875         break;
3876       }
3877
3878       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3879         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3880           return Res;
3881     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3882       // If this is an integer truncation or change from signed-to-unsigned, and
3883       // if the source is an and/or with immediate, transform it.  This
3884       // frequently occurs for bitfield accesses.
3885       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3886         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3887             CastOp->getNumOperands() == 2)
3888           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3889             if (CastOp->getOpcode() == Instruction::And) {
3890               // Change: and (cast (and X, C1) to T), C2
3891               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3892               // This will fold the two constants together, which may allow 
3893               // other simplifications.
3894               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3895                 CastOp->getOperand(0), I.getType(), 
3896                 CastOp->getName()+".shrunk");
3897               NewCast = InsertNewInstBefore(NewCast, I);
3898               // trunc_or_bitcast(C1)&C2
3899               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3900               C3 = ConstantExpr::getAnd(C3, AndRHS);
3901               return BinaryOperator::CreateAnd(NewCast, C3);
3902             } else if (CastOp->getOpcode() == Instruction::Or) {
3903               // Change: and (cast (or X, C1) to T), C2
3904               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3905               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3906               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3907                 return ReplaceInstUsesWith(I, AndRHS);
3908             }
3909           }
3910       }
3911     }
3912
3913     // Try to fold constant and into select arguments.
3914     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3915       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3916         return R;
3917     if (isa<PHINode>(Op0))
3918       if (Instruction *NV = FoldOpIntoPhi(I))
3919         return NV;
3920   }
3921
3922   Value *Op0NotVal = dyn_castNotVal(Op0);
3923   Value *Op1NotVal = dyn_castNotVal(Op1);
3924
3925   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3926     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3927
3928   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3929   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3930     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3931                                                I.getName()+".demorgan");
3932     InsertNewInstBefore(Or, I);
3933     return BinaryOperator::CreateNot(Or);
3934   }
3935   
3936   {
3937     Value *A = 0, *B = 0, *C = 0, *D = 0;
3938     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3939       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3940         return ReplaceInstUsesWith(I, Op1);
3941     
3942       // (A|B) & ~(A&B) -> A^B
3943       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3944         if ((A == C && B == D) || (A == D && B == C))
3945           return BinaryOperator::CreateXor(A, B);
3946       }
3947     }
3948     
3949     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3950       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3951         return ReplaceInstUsesWith(I, Op0);
3952
3953       // ~(A&B) & (A|B) -> A^B
3954       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3955         if ((A == C && B == D) || (A == D && B == C))
3956           return BinaryOperator::CreateXor(A, B);
3957       }
3958     }
3959     
3960     if (Op0->hasOneUse() &&
3961         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3962       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3963         I.swapOperands();     // Simplify below
3964         std::swap(Op0, Op1);
3965       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3966         cast<BinaryOperator>(Op0)->swapOperands();
3967         I.swapOperands();     // Simplify below
3968         std::swap(Op0, Op1);
3969       }
3970     }
3971
3972     if (Op1->hasOneUse() &&
3973         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3974       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3975         cast<BinaryOperator>(Op1)->swapOperands();
3976         std::swap(A, B);
3977       }
3978       if (A == Op0) {                                // A&(A^B) -> A & ~B
3979         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3980         InsertNewInstBefore(NotB, I);
3981         return BinaryOperator::CreateAnd(A, NotB);
3982       }
3983     }
3984
3985     // (A&((~A)|B)) -> A&B
3986     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
3987         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
3988       return BinaryOperator::CreateAnd(A, Op1);
3989     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
3990         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
3991       return BinaryOperator::CreateAnd(A, Op0);
3992   }
3993   
3994   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3995     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3996     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3997       return R;
3998
3999     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4000       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4001         return Res;
4002   }
4003
4004   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4005   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4006     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4007       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4008         const Type *SrcTy = Op0C->getOperand(0)->getType();
4009         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4010             // Only do this if the casts both really cause code to be generated.
4011             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4012                               I.getType(), TD) &&
4013             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4014                               I.getType(), TD)) {
4015           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4016                                                          Op1C->getOperand(0),
4017                                                          I.getName());
4018           InsertNewInstBefore(NewOp, I);
4019           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4020         }
4021       }
4022     
4023   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4024   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4025     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4026       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4027           SI0->getOperand(1) == SI1->getOperand(1) &&
4028           (SI0->hasOneUse() || SI1->hasOneUse())) {
4029         Instruction *NewOp =
4030           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4031                                                         SI1->getOperand(0),
4032                                                         SI0->getName()), I);
4033         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4034                                       SI1->getOperand(1));
4035       }
4036   }
4037
4038   // If and'ing two fcmp, try combine them into one.
4039   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4040     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4041       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4042           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4043         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4044         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4045           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4046             // If either of the constants are nans, then the whole thing returns
4047             // false.
4048             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4049               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4050             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4051                                 RHS->getOperand(0));
4052           }
4053       } else {
4054         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4055         FCmpInst::Predicate Op0CC, Op1CC;
4056         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4057             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4058           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4059             // Swap RHS operands to match LHS.
4060             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4061             std::swap(Op1LHS, Op1RHS);
4062           }
4063           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4064             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4065             if (Op0CC == Op1CC)
4066               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4067             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4068                      Op1CC == FCmpInst::FCMP_FALSE)
4069               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4070             else if (Op0CC == FCmpInst::FCMP_TRUE)
4071               return ReplaceInstUsesWith(I, Op1);
4072             else if (Op1CC == FCmpInst::FCMP_TRUE)
4073               return ReplaceInstUsesWith(I, Op0);
4074             bool Op0Ordered;
4075             bool Op1Ordered;
4076             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4077             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4078             if (Op1Pred == 0) {
4079               std::swap(Op0, Op1);
4080               std::swap(Op0Pred, Op1Pred);
4081               std::swap(Op0Ordered, Op1Ordered);
4082             }
4083             if (Op0Pred == 0) {
4084               // uno && ueq -> uno && (uno || eq) -> ueq
4085               // ord && olt -> ord && (ord && lt) -> olt
4086               if (Op0Ordered == Op1Ordered)
4087                 return ReplaceInstUsesWith(I, Op1);
4088               // uno && oeq -> uno && (ord && eq) -> false
4089               // uno && ord -> false
4090               if (!Op0Ordered)
4091                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4092               // ord && ueq -> ord && (uno || eq) -> oeq
4093               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4094                                                     Op0LHS, Op0RHS));
4095             }
4096           }
4097         }
4098       }
4099     }
4100   }
4101
4102   return Changed ? &I : 0;
4103 }
4104
4105 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4106 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4107 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4108 /// the expression came from the corresponding "byte swapped" byte in some other
4109 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4110 /// we know that the expression deposits the low byte of %X into the high byte
4111 /// of the bswap result and that all other bytes are zero.  This expression is
4112 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4113 /// match.
4114 ///
4115 /// This function returns true if the match was unsuccessful and false if so.
4116 /// On entry to the function the "OverallLeftShift" is a signed integer value
4117 /// indicating the number of bytes that the subexpression is later shifted.  For
4118 /// example, if the expression is later right shifted by 16 bits, the
4119 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4120 /// byte of ByteValues is actually being set.
4121 ///
4122 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4123 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4124 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4125 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4126 /// always in the local (OverallLeftShift) coordinate space.
4127 ///
4128 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4129                               SmallVector<Value*, 8> &ByteValues) {
4130   if (Instruction *I = dyn_cast<Instruction>(V)) {
4131     // If this is an or instruction, it may be an inner node of the bswap.
4132     if (I->getOpcode() == Instruction::Or) {
4133       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4134                                ByteValues) ||
4135              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4136                                ByteValues);
4137     }
4138   
4139     // If this is a logical shift by a constant multiple of 8, recurse with
4140     // OverallLeftShift and ByteMask adjusted.
4141     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4142       unsigned ShAmt = 
4143         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4144       // Ensure the shift amount is defined and of a byte value.
4145       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4146         return true;
4147
4148       unsigned ByteShift = ShAmt >> 3;
4149       if (I->getOpcode() == Instruction::Shl) {
4150         // X << 2 -> collect(X, +2)
4151         OverallLeftShift += ByteShift;
4152         ByteMask >>= ByteShift;
4153       } else {
4154         // X >>u 2 -> collect(X, -2)
4155         OverallLeftShift -= ByteShift;
4156         ByteMask <<= ByteShift;
4157         ByteMask &= (~0U >> (32-ByteValues.size()));
4158       }
4159
4160       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4161       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4162
4163       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4164                                ByteValues);
4165     }
4166
4167     // If this is a logical 'and' with a mask that clears bytes, clear the
4168     // corresponding bytes in ByteMask.
4169     if (I->getOpcode() == Instruction::And &&
4170         isa<ConstantInt>(I->getOperand(1))) {
4171       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4172       unsigned NumBytes = ByteValues.size();
4173       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4174       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4175       
4176       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4177         // If this byte is masked out by a later operation, we don't care what
4178         // the and mask is.
4179         if ((ByteMask & (1 << i)) == 0)
4180           continue;
4181         
4182         // If the AndMask is all zeros for this byte, clear the bit.
4183         APInt MaskB = AndMask & Byte;
4184         if (MaskB == 0) {
4185           ByteMask &= ~(1U << i);
4186           continue;
4187         }
4188         
4189         // If the AndMask is not all ones for this byte, it's not a bytezap.
4190         if (MaskB != Byte)
4191           return true;
4192
4193         // Otherwise, this byte is kept.
4194       }
4195
4196       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4197                                ByteValues);
4198     }
4199   }
4200   
4201   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4202   // the input value to the bswap.  Some observations: 1) if more than one byte
4203   // is demanded from this input, then it could not be successfully assembled
4204   // into a byteswap.  At least one of the two bytes would not be aligned with
4205   // their ultimate destination.
4206   if (!isPowerOf2_32(ByteMask)) return true;
4207   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4208   
4209   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4210   // is demanded, it needs to go into byte 0 of the result.  This means that the
4211   // byte needs to be shifted until it lands in the right byte bucket.  The
4212   // shift amount depends on the position: if the byte is coming from the high
4213   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4214   // low part, it must be shifted left.
4215   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4216   if (InputByteNo < ByteValues.size()/2) {
4217     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4218       return true;
4219   } else {
4220     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4221       return true;
4222   }
4223   
4224   // If the destination byte value is already defined, the values are or'd
4225   // together, which isn't a bswap (unless it's an or of the same bits).
4226   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4227     return true;
4228   ByteValues[DestByteNo] = V;
4229   return false;
4230 }
4231
4232 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4233 /// If so, insert the new bswap intrinsic and return it.
4234 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4235   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4236   if (!ITy || ITy->getBitWidth() % 16 || 
4237       // ByteMask only allows up to 32-byte values.
4238       ITy->getBitWidth() > 32*8) 
4239     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4240   
4241   /// ByteValues - For each byte of the result, we keep track of which value
4242   /// defines each byte.
4243   SmallVector<Value*, 8> ByteValues;
4244   ByteValues.resize(ITy->getBitWidth()/8);
4245     
4246   // Try to find all the pieces corresponding to the bswap.
4247   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4248   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4249     return 0;
4250   
4251   // Check to see if all of the bytes come from the same value.
4252   Value *V = ByteValues[0];
4253   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4254   
4255   // Check to make sure that all of the bytes come from the same value.
4256   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4257     if (ByteValues[i] != V)
4258       return 0;
4259   const Type *Tys[] = { ITy };
4260   Module *M = I.getParent()->getParent()->getParent();
4261   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4262   return CallInst::Create(F, V);
4263 }
4264
4265 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4266 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4267 /// we can simplify this expression to "cond ? C : D or B".
4268 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4269                                          Value *C, Value *D) {
4270   // If A is not a select of -1/0, this cannot match.
4271   Value *Cond = 0;
4272   if (!match(A, m_SelectCst(m_Value(Cond), -1, 0)))
4273     return 0;
4274
4275   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4276   if (match(D, m_SelectCst(m_Specific(Cond), 0, -1)))
4277     return SelectInst::Create(Cond, C, B);
4278   if (match(D, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
4279     return SelectInst::Create(Cond, C, B);
4280   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4281   if (match(B, m_SelectCst(m_Specific(Cond), 0, -1)))
4282     return SelectInst::Create(Cond, C, D);
4283   if (match(B, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
4284     return SelectInst::Create(Cond, C, D);
4285   return 0;
4286 }
4287
4288 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4289 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4290                                          ICmpInst *LHS, ICmpInst *RHS) {
4291   Value *Val, *Val2;
4292   ConstantInt *LHSCst, *RHSCst;
4293   ICmpInst::Predicate LHSCC, RHSCC;
4294   
4295   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4296   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4297       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4298     return 0;
4299   
4300   // From here on, we only handle:
4301   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4302   if (Val != Val2) return 0;
4303   
4304   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4305   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4306       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4307       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4308       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4309     return 0;
4310   
4311   // We can't fold (ugt x, C) | (sgt x, C2).
4312   if (!PredicatesFoldable(LHSCC, RHSCC))
4313     return 0;
4314   
4315   // Ensure that the larger constant is on the RHS.
4316   bool ShouldSwap;
4317   if (ICmpInst::isSignedPredicate(LHSCC) ||
4318       (ICmpInst::isEquality(LHSCC) && 
4319        ICmpInst::isSignedPredicate(RHSCC)))
4320     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4321   else
4322     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4323   
4324   if (ShouldSwap) {
4325     std::swap(LHS, RHS);
4326     std::swap(LHSCst, RHSCst);
4327     std::swap(LHSCC, RHSCC);
4328   }
4329   
4330   // At this point, we know we have have two icmp instructions
4331   // comparing a value against two constants and or'ing the result
4332   // together.  Because of the above check, we know that we only have
4333   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4334   // FoldICmpLogical check above), that the two constants are not
4335   // equal.
4336   assert(LHSCst != RHSCst && "Compares not folded above?");
4337
4338   switch (LHSCC) {
4339   default: assert(0 && "Unknown integer condition code!");
4340   case ICmpInst::ICMP_EQ:
4341     switch (RHSCC) {
4342     default: assert(0 && "Unknown integer condition code!");
4343     case ICmpInst::ICMP_EQ:
4344       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4345         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4346         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4347                                                      Val->getName()+".off");
4348         InsertNewInstBefore(Add, I);
4349         AddCST = Subtract(AddOne(RHSCst), LHSCst);
4350         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4351       }
4352       break;                         // (X == 13 | X == 15) -> no change
4353     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4354     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4355       break;
4356     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4357     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4358     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4359       return ReplaceInstUsesWith(I, RHS);
4360     }
4361     break;
4362   case ICmpInst::ICMP_NE:
4363     switch (RHSCC) {
4364     default: assert(0 && "Unknown integer condition code!");
4365     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4366     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4367     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4368       return ReplaceInstUsesWith(I, LHS);
4369     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4370     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4371     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4372       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4373     }
4374     break;
4375   case ICmpInst::ICMP_ULT:
4376     switch (RHSCC) {
4377     default: assert(0 && "Unknown integer condition code!");
4378     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4379       break;
4380     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4381       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4382       // this can cause overflow.
4383       if (RHSCst->isMaxValue(false))
4384         return ReplaceInstUsesWith(I, LHS);
4385       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4386     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4387       break;
4388     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4389     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4390       return ReplaceInstUsesWith(I, RHS);
4391     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4392       break;
4393     }
4394     break;
4395   case ICmpInst::ICMP_SLT:
4396     switch (RHSCC) {
4397     default: assert(0 && "Unknown integer condition code!");
4398     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4399       break;
4400     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4401       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4402       // this can cause overflow.
4403       if (RHSCst->isMaxValue(true))
4404         return ReplaceInstUsesWith(I, LHS);
4405       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4406     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4407       break;
4408     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4409     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4410       return ReplaceInstUsesWith(I, RHS);
4411     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4412       break;
4413     }
4414     break;
4415   case ICmpInst::ICMP_UGT:
4416     switch (RHSCC) {
4417     default: assert(0 && "Unknown integer condition code!");
4418     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4419     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4420       return ReplaceInstUsesWith(I, LHS);
4421     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4422       break;
4423     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4424     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4425       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4426     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4427       break;
4428     }
4429     break;
4430   case ICmpInst::ICMP_SGT:
4431     switch (RHSCC) {
4432     default: assert(0 && "Unknown integer condition code!");
4433     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4434     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4435       return ReplaceInstUsesWith(I, LHS);
4436     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4437       break;
4438     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4439     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4440       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4441     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4442       break;
4443     }
4444     break;
4445   }
4446   return 0;
4447 }
4448
4449 /// FoldOrWithConstants - This helper function folds:
4450 ///
4451 ///     ((A | B) & C1) | (B & C2)
4452 ///
4453 /// into:
4454 /// 
4455 ///     (A & C1) | B
4456 ///
4457 /// when the XOR of the two constants is "all ones" (-1).
4458 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4459                                                Value *A, Value *B, Value *C) {
4460   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4461   if (!CI1) return 0;
4462
4463   Value *V1 = 0;
4464   ConstantInt *CI2 = 0;
4465   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4466
4467   APInt Xor = CI1->getValue() ^ CI2->getValue();
4468   if (!Xor.isAllOnesValue()) return 0;
4469
4470   if (V1 == A || V1 == B) {
4471     Instruction *NewOp =
4472       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4473     return BinaryOperator::CreateOr(NewOp, V1);
4474   }
4475
4476   return 0;
4477 }
4478
4479 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4480   bool Changed = SimplifyCommutative(I);
4481   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4482
4483   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4484     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4485
4486   // or X, X = X
4487   if (Op0 == Op1)
4488     return ReplaceInstUsesWith(I, Op0);
4489
4490   // See if we can simplify any instructions used by the instruction whose sole 
4491   // purpose is to compute bits we don't care about.
4492   if (!isa<VectorType>(I.getType())) {
4493     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4494     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4495     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4496                              KnownZero, KnownOne))
4497       return &I;
4498   } else if (isa<ConstantAggregateZero>(Op1)) {
4499     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4500   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4501     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4502       return ReplaceInstUsesWith(I, I.getOperand(1));
4503   }
4504     
4505
4506   
4507   // or X, -1 == -1
4508   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4509     ConstantInt *C1 = 0; Value *X = 0;
4510     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4511     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4512       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4513       InsertNewInstBefore(Or, I);
4514       Or->takeName(Op0);
4515       return BinaryOperator::CreateAnd(Or, 
4516                ConstantInt::get(RHS->getValue() | C1->getValue()));
4517     }
4518
4519     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4520     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4521       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4522       InsertNewInstBefore(Or, I);
4523       Or->takeName(Op0);
4524       return BinaryOperator::CreateXor(Or,
4525                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4526     }
4527
4528     // Try to fold constant and into select arguments.
4529     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4530       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4531         return R;
4532     if (isa<PHINode>(Op0))
4533       if (Instruction *NV = FoldOpIntoPhi(I))
4534         return NV;
4535   }
4536
4537   Value *A = 0, *B = 0;
4538   ConstantInt *C1 = 0, *C2 = 0;
4539
4540   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4541     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4542       return ReplaceInstUsesWith(I, Op1);
4543   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4544     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4545       return ReplaceInstUsesWith(I, Op0);
4546
4547   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4548   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4549   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4550       match(Op1, m_Or(m_Value(), m_Value())) ||
4551       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4552        match(Op1, m_Shift(m_Value(), m_Value())))) {
4553     if (Instruction *BSwap = MatchBSwap(I))
4554       return BSwap;
4555   }
4556   
4557   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4558   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4559       MaskedValueIsZero(Op1, C1->getValue())) {
4560     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4561     InsertNewInstBefore(NOr, I);
4562     NOr->takeName(Op0);
4563     return BinaryOperator::CreateXor(NOr, C1);
4564   }
4565
4566   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4567   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4568       MaskedValueIsZero(Op0, C1->getValue())) {
4569     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4570     InsertNewInstBefore(NOr, I);
4571     NOr->takeName(Op0);
4572     return BinaryOperator::CreateXor(NOr, C1);
4573   }
4574
4575   // (A & C)|(B & D)
4576   Value *C = 0, *D = 0;
4577   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4578       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4579     Value *V1 = 0, *V2 = 0, *V3 = 0;
4580     C1 = dyn_cast<ConstantInt>(C);
4581     C2 = dyn_cast<ConstantInt>(D);
4582     if (C1 && C2) {  // (A & C1)|(B & C2)
4583       // If we have: ((V + N) & C1) | (V & C2)
4584       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4585       // replace with V+N.
4586       if (C1->getValue() == ~C2->getValue()) {
4587         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4588             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4589           // Add commutes, try both ways.
4590           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4591             return ReplaceInstUsesWith(I, A);
4592           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4593             return ReplaceInstUsesWith(I, A);
4594         }
4595         // Or commutes, try both ways.
4596         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4597             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4598           // Add commutes, try both ways.
4599           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4600             return ReplaceInstUsesWith(I, B);
4601           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4602             return ReplaceInstUsesWith(I, B);
4603         }
4604       }
4605       V1 = 0; V2 = 0; V3 = 0;
4606     }
4607     
4608     // Check to see if we have any common things being and'ed.  If so, find the
4609     // terms for V1 & (V2|V3).
4610     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4611       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4612         V1 = A, V2 = C, V3 = D;
4613       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4614         V1 = A, V2 = B, V3 = C;
4615       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4616         V1 = C, V2 = A, V3 = D;
4617       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4618         V1 = C, V2 = A, V3 = B;
4619       
4620       if (V1) {
4621         Value *Or =
4622           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4623         return BinaryOperator::CreateAnd(V1, Or);
4624       }
4625     }
4626
4627     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4628     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4629       return Match;
4630     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4631       return Match;
4632     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4633       return Match;
4634     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4635       return Match;
4636
4637     // ((A&~B)|(~A&B)) -> A^B
4638     if ((match(C, m_Not(m_Specific(D))) &&
4639          match(B, m_Not(m_Specific(A)))))
4640       return BinaryOperator::CreateXor(A, D);
4641     // ((~B&A)|(~A&B)) -> A^B
4642     if ((match(A, m_Not(m_Specific(D))) &&
4643          match(B, m_Not(m_Specific(C)))))
4644       return BinaryOperator::CreateXor(C, D);
4645     // ((A&~B)|(B&~A)) -> A^B
4646     if ((match(C, m_Not(m_Specific(B))) &&
4647          match(D, m_Not(m_Specific(A)))))
4648       return BinaryOperator::CreateXor(A, B);
4649     // ((~B&A)|(B&~A)) -> A^B
4650     if ((match(A, m_Not(m_Specific(B))) &&
4651          match(D, m_Not(m_Specific(C)))))
4652       return BinaryOperator::CreateXor(C, B);
4653   }
4654   
4655   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4656   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4657     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4658       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4659           SI0->getOperand(1) == SI1->getOperand(1) &&
4660           (SI0->hasOneUse() || SI1->hasOneUse())) {
4661         Instruction *NewOp =
4662         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4663                                                      SI1->getOperand(0),
4664                                                      SI0->getName()), I);
4665         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4666                                       SI1->getOperand(1));
4667       }
4668   }
4669
4670   // ((A|B)&1)|(B&-2) -> (A&1) | B
4671   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4672       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4673     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4674     if (Ret) return Ret;
4675   }
4676   // (B&-2)|((A|B)&1) -> (A&1) | B
4677   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4678       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4679     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4680     if (Ret) return Ret;
4681   }
4682
4683   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4684     if (A == Op1)   // ~A | A == -1
4685       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4686   } else {
4687     A = 0;
4688   }
4689   // Note, A is still live here!
4690   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4691     if (Op0 == B)
4692       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4693
4694     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4695     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4696       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4697                                               I.getName()+".demorgan"), I);
4698       return BinaryOperator::CreateNot(And);
4699     }
4700   }
4701
4702   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4703   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4704     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4705       return R;
4706
4707     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4708       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4709         return Res;
4710   }
4711     
4712   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4713   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4714     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4715       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4716         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4717             !isa<ICmpInst>(Op1C->getOperand(0))) {
4718           const Type *SrcTy = Op0C->getOperand(0)->getType();
4719           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4720               // Only do this if the casts both really cause code to be
4721               // generated.
4722               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4723                                 I.getType(), TD) &&
4724               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4725                                 I.getType(), TD)) {
4726             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4727                                                           Op1C->getOperand(0),
4728                                                           I.getName());
4729             InsertNewInstBefore(NewOp, I);
4730             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4731           }
4732         }
4733       }
4734   }
4735   
4736     
4737   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4738   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4739     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4740       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4741           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4742           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4743         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4744           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4745             // If either of the constants are nans, then the whole thing returns
4746             // true.
4747             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4748               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4749             
4750             // Otherwise, no need to compare the two constants, compare the
4751             // rest.
4752             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4753                                 RHS->getOperand(0));
4754           }
4755       } else {
4756         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4757         FCmpInst::Predicate Op0CC, Op1CC;
4758         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4759             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4760           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4761             // Swap RHS operands to match LHS.
4762             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4763             std::swap(Op1LHS, Op1RHS);
4764           }
4765           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4766             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4767             if (Op0CC == Op1CC)
4768               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4769             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4770                      Op1CC == FCmpInst::FCMP_TRUE)
4771               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4772             else if (Op0CC == FCmpInst::FCMP_FALSE)
4773               return ReplaceInstUsesWith(I, Op1);
4774             else if (Op1CC == FCmpInst::FCMP_FALSE)
4775               return ReplaceInstUsesWith(I, Op0);
4776             bool Op0Ordered;
4777             bool Op1Ordered;
4778             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4779             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4780             if (Op0Ordered == Op1Ordered) {
4781               // If both are ordered or unordered, return a new fcmp with
4782               // or'ed predicates.
4783               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4784                                        Op0LHS, Op0RHS);
4785               if (Instruction *I = dyn_cast<Instruction>(RV))
4786                 return I;
4787               // Otherwise, it's a constant boolean value...
4788               return ReplaceInstUsesWith(I, RV);
4789             }
4790           }
4791         }
4792       }
4793     }
4794   }
4795
4796   return Changed ? &I : 0;
4797 }
4798
4799 namespace {
4800
4801 // XorSelf - Implements: X ^ X --> 0
4802 struct XorSelf {
4803   Value *RHS;
4804   XorSelf(Value *rhs) : RHS(rhs) {}
4805   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4806   Instruction *apply(BinaryOperator &Xor) const {
4807     return &Xor;
4808   }
4809 };
4810
4811 }
4812
4813 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4814   bool Changed = SimplifyCommutative(I);
4815   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4816
4817   if (isa<UndefValue>(Op1)) {
4818     if (isa<UndefValue>(Op0))
4819       // Handle undef ^ undef -> 0 special case. This is a common
4820       // idiom (misuse).
4821       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4822     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4823   }
4824
4825   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4826   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4827     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4828     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4829   }
4830   
4831   // See if we can simplify any instructions used by the instruction whose sole 
4832   // purpose is to compute bits we don't care about.
4833   if (!isa<VectorType>(I.getType())) {
4834     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4835     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4836     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4837                              KnownZero, KnownOne))
4838       return &I;
4839   } else if (isa<ConstantAggregateZero>(Op1)) {
4840     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4841   }
4842
4843   // Is this a ~ operation?
4844   if (Value *NotOp = dyn_castNotVal(&I)) {
4845     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4846     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4847     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4848       if (Op0I->getOpcode() == Instruction::And || 
4849           Op0I->getOpcode() == Instruction::Or) {
4850         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4851         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4852           Instruction *NotY =
4853             BinaryOperator::CreateNot(Op0I->getOperand(1),
4854                                       Op0I->getOperand(1)->getName()+".not");
4855           InsertNewInstBefore(NotY, I);
4856           if (Op0I->getOpcode() == Instruction::And)
4857             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4858           else
4859             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4860         }
4861       }
4862     }
4863   }
4864   
4865   
4866   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4867     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4868     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4869       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4870         return new ICmpInst(ICI->getInversePredicate(),
4871                             ICI->getOperand(0), ICI->getOperand(1));
4872
4873       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4874         return new FCmpInst(FCI->getInversePredicate(),
4875                             FCI->getOperand(0), FCI->getOperand(1));
4876     }
4877
4878     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4879     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4880       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4881         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4882           Instruction::CastOps Opcode = Op0C->getOpcode();
4883           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4884             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4885                                              Op0C->getDestTy())) {
4886               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4887                                      CI->getOpcode(), CI->getInversePredicate(),
4888                                      CI->getOperand(0), CI->getOperand(1)), I);
4889               NewCI->takeName(CI);
4890               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4891             }
4892           }
4893         }
4894       }
4895     }
4896
4897     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4898       // ~(c-X) == X-c-1 == X+(-c-1)
4899       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4900         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4901           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4902           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4903                                               ConstantInt::get(I.getType(), 1));
4904           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4905         }
4906           
4907       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4908         if (Op0I->getOpcode() == Instruction::Add) {
4909           // ~(X-c) --> (-c-1)-X
4910           if (RHS->isAllOnesValue()) {
4911             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4912             return BinaryOperator::CreateSub(
4913                            ConstantExpr::getSub(NegOp0CI,
4914                                              ConstantInt::get(I.getType(), 1)),
4915                                           Op0I->getOperand(0));
4916           } else if (RHS->getValue().isSignBit()) {
4917             // (X + C) ^ signbit -> (X + C + signbit)
4918             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4919             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4920
4921           }
4922         } else if (Op0I->getOpcode() == Instruction::Or) {
4923           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4924           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4925             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4926             // Anything in both C1 and C2 is known to be zero, remove it from
4927             // NewRHS.
4928             Constant *CommonBits = And(Op0CI, RHS);
4929             NewRHS = ConstantExpr::getAnd(NewRHS, 
4930                                           ConstantExpr::getNot(CommonBits));
4931             AddToWorkList(Op0I);
4932             I.setOperand(0, Op0I->getOperand(0));
4933             I.setOperand(1, NewRHS);
4934             return &I;
4935           }
4936         }
4937       }
4938     }
4939
4940     // Try to fold constant and into select arguments.
4941     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4942       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4943         return R;
4944     if (isa<PHINode>(Op0))
4945       if (Instruction *NV = FoldOpIntoPhi(I))
4946         return NV;
4947   }
4948
4949   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4950     if (X == Op1)
4951       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4952
4953   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4954     if (X == Op0)
4955       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4956
4957   
4958   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4959   if (Op1I) {
4960     Value *A, *B;
4961     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4962       if (A == Op0) {              // B^(B|A) == (A|B)^B
4963         Op1I->swapOperands();
4964         I.swapOperands();
4965         std::swap(Op0, Op1);
4966       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4967         I.swapOperands();     // Simplified below.
4968         std::swap(Op0, Op1);
4969       }
4970     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
4971       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
4972     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
4973       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
4974     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4975       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4976         Op1I->swapOperands();
4977         std::swap(A, B);
4978       }
4979       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4980         I.swapOperands();     // Simplified below.
4981         std::swap(Op0, Op1);
4982       }
4983     }
4984   }
4985   
4986   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4987   if (Op0I) {
4988     Value *A, *B;
4989     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4990       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4991         std::swap(A, B);
4992       if (B == Op1) {                                // (A|B)^B == A & ~B
4993         Instruction *NotB =
4994           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4995         return BinaryOperator::CreateAnd(A, NotB);
4996       }
4997     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
4998       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
4999     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5000       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5001     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5002       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5003         std::swap(A, B);
5004       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5005           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5006         Instruction *N =
5007           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5008         return BinaryOperator::CreateAnd(N, Op1);
5009       }
5010     }
5011   }
5012   
5013   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5014   if (Op0I && Op1I && Op0I->isShift() && 
5015       Op0I->getOpcode() == Op1I->getOpcode() && 
5016       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5017       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5018     Instruction *NewOp =
5019       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5020                                                     Op1I->getOperand(0),
5021                                                     Op0I->getName()), I);
5022     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5023                                   Op1I->getOperand(1));
5024   }
5025     
5026   if (Op0I && Op1I) {
5027     Value *A, *B, *C, *D;
5028     // (A & B)^(A | B) -> A ^ B
5029     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5030         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5031       if ((A == C && B == D) || (A == D && B == C)) 
5032         return BinaryOperator::CreateXor(A, B);
5033     }
5034     // (A | B)^(A & B) -> A ^ B
5035     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5036         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5037       if ((A == C && B == D) || (A == D && B == C)) 
5038         return BinaryOperator::CreateXor(A, B);
5039     }
5040     
5041     // (A & B)^(C & D)
5042     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5043         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5044         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5045       // (X & Y)^(X & Y) -> (Y^Z) & X
5046       Value *X = 0, *Y = 0, *Z = 0;
5047       if (A == C)
5048         X = A, Y = B, Z = D;
5049       else if (A == D)
5050         X = A, Y = B, Z = C;
5051       else if (B == C)
5052         X = B, Y = A, Z = D;
5053       else if (B == D)
5054         X = B, Y = A, Z = C;
5055       
5056       if (X) {
5057         Instruction *NewOp =
5058         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5059         return BinaryOperator::CreateAnd(NewOp, X);
5060       }
5061     }
5062   }
5063     
5064   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5065   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5066     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5067       return R;
5068
5069   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5070   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5071     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5072       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5073         const Type *SrcTy = Op0C->getOperand(0)->getType();
5074         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5075             // Only do this if the casts both really cause code to be generated.
5076             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5077                               I.getType(), TD) &&
5078             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5079                               I.getType(), TD)) {
5080           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5081                                                          Op1C->getOperand(0),
5082                                                          I.getName());
5083           InsertNewInstBefore(NewOp, I);
5084           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5085         }
5086       }
5087   }
5088
5089   return Changed ? &I : 0;
5090 }
5091
5092 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5093 /// overflowed for this type.
5094 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5095                             ConstantInt *In2, bool IsSigned = false) {
5096   Result = cast<ConstantInt>(Add(In1, In2));
5097
5098   if (IsSigned)
5099     if (In2->getValue().isNegative())
5100       return Result->getValue().sgt(In1->getValue());
5101     else
5102       return Result->getValue().slt(In1->getValue());
5103   else
5104     return Result->getValue().ult(In1->getValue());
5105 }
5106
5107 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5108 /// overflowed for this type.
5109 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5110                             ConstantInt *In2, bool IsSigned = false) {
5111   Result = cast<ConstantInt>(Subtract(In1, In2));
5112
5113   if (IsSigned)
5114     if (In2->getValue().isNegative())
5115       return Result->getValue().slt(In1->getValue());
5116     else
5117       return Result->getValue().sgt(In1->getValue());
5118   else
5119     return Result->getValue().ugt(In1->getValue());
5120 }
5121
5122 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5123 /// code necessary to compute the offset from the base pointer (without adding
5124 /// in the base pointer).  Return the result as a signed integer of intptr size.
5125 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5126   TargetData &TD = IC.getTargetData();
5127   gep_type_iterator GTI = gep_type_begin(GEP);
5128   const Type *IntPtrTy = TD.getIntPtrType();
5129   Value *Result = Constant::getNullValue(IntPtrTy);
5130
5131   // Build a mask for high order bits.
5132   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5133   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5134
5135   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5136        ++i, ++GTI) {
5137     Value *Op = *i;
5138     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
5139     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5140       if (OpC->isZero()) continue;
5141       
5142       // Handle a struct index, which adds its field offset to the pointer.
5143       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5144         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5145         
5146         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5147           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5148         else
5149           Result = IC.InsertNewInstBefore(
5150                    BinaryOperator::CreateAdd(Result,
5151                                              ConstantInt::get(IntPtrTy, Size),
5152                                              GEP->getName()+".offs"), I);
5153         continue;
5154       }
5155       
5156       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5157       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5158       Scale = ConstantExpr::getMul(OC, Scale);
5159       if (Constant *RC = dyn_cast<Constant>(Result))
5160         Result = ConstantExpr::getAdd(RC, Scale);
5161       else {
5162         // Emit an add instruction.
5163         Result = IC.InsertNewInstBefore(
5164            BinaryOperator::CreateAdd(Result, Scale,
5165                                      GEP->getName()+".offs"), I);
5166       }
5167       continue;
5168     }
5169     // Convert to correct type.
5170     if (Op->getType() != IntPtrTy) {
5171       if (Constant *OpC = dyn_cast<Constant>(Op))
5172         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5173       else
5174         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5175                                                  Op->getName()+".c"), I);
5176     }
5177     if (Size != 1) {
5178       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5179       if (Constant *OpC = dyn_cast<Constant>(Op))
5180         Op = ConstantExpr::getMul(OpC, Scale);
5181       else    // We'll let instcombine(mul) convert this to a shl if possible.
5182         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5183                                                   GEP->getName()+".idx"), I);
5184     }
5185
5186     // Emit an add instruction.
5187     if (isa<Constant>(Op) && isa<Constant>(Result))
5188       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5189                                     cast<Constant>(Result));
5190     else
5191       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5192                                                   GEP->getName()+".offs"), I);
5193   }
5194   return Result;
5195 }
5196
5197
5198 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5199 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5200 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5201 /// complex, and scales are involved.  The above expression would also be legal
5202 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5203 /// later form is less amenable to optimization though, and we are allowed to
5204 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5205 ///
5206 /// If we can't emit an optimized form for this expression, this returns null.
5207 /// 
5208 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5209                                           InstCombiner &IC) {
5210   TargetData &TD = IC.getTargetData();
5211   gep_type_iterator GTI = gep_type_begin(GEP);
5212
5213   // Check to see if this gep only has a single variable index.  If so, and if
5214   // any constant indices are a multiple of its scale, then we can compute this
5215   // in terms of the scale of the variable index.  For example, if the GEP
5216   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5217   // because the expression will cross zero at the same point.
5218   unsigned i, e = GEP->getNumOperands();
5219   int64_t Offset = 0;
5220   for (i = 1; i != e; ++i, ++GTI) {
5221     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5222       // Compute the aggregate offset of constant indices.
5223       if (CI->isZero()) continue;
5224
5225       // Handle a struct index, which adds its field offset to the pointer.
5226       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5227         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5228       } else {
5229         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5230         Offset += Size*CI->getSExtValue();
5231       }
5232     } else {
5233       // Found our variable index.
5234       break;
5235     }
5236   }
5237   
5238   // If there are no variable indices, we must have a constant offset, just
5239   // evaluate it the general way.
5240   if (i == e) return 0;
5241   
5242   Value *VariableIdx = GEP->getOperand(i);
5243   // Determine the scale factor of the variable element.  For example, this is
5244   // 4 if the variable index is into an array of i32.
5245   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5246   
5247   // Verify that there are no other variable indices.  If so, emit the hard way.
5248   for (++i, ++GTI; i != e; ++i, ++GTI) {
5249     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5250     if (!CI) return 0;
5251    
5252     // Compute the aggregate offset of constant indices.
5253     if (CI->isZero()) continue;
5254     
5255     // Handle a struct index, which adds its field offset to the pointer.
5256     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5257       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5258     } else {
5259       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5260       Offset += Size*CI->getSExtValue();
5261     }
5262   }
5263   
5264   // Okay, we know we have a single variable index, which must be a
5265   // pointer/array/vector index.  If there is no offset, life is simple, return
5266   // the index.
5267   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5268   if (Offset == 0) {
5269     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5270     // we don't need to bother extending: the extension won't affect where the
5271     // computation crosses zero.
5272     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5273       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5274                                   VariableIdx->getNameStart(), &I);
5275     return VariableIdx;
5276   }
5277   
5278   // Otherwise, there is an index.  The computation we will do will be modulo
5279   // the pointer size, so get it.
5280   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5281   
5282   Offset &= PtrSizeMask;
5283   VariableScale &= PtrSizeMask;
5284
5285   // To do this transformation, any constant index must be a multiple of the
5286   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5287   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5288   // multiple of the variable scale.
5289   int64_t NewOffs = Offset / (int64_t)VariableScale;
5290   if (Offset != NewOffs*(int64_t)VariableScale)
5291     return 0;
5292
5293   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5294   const Type *IntPtrTy = TD.getIntPtrType();
5295   if (VariableIdx->getType() != IntPtrTy)
5296     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5297                                               true /*SExt*/, 
5298                                               VariableIdx->getNameStart(), &I);
5299   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5300   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5301 }
5302
5303
5304 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5305 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5306 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5307                                        ICmpInst::Predicate Cond,
5308                                        Instruction &I) {
5309   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5310
5311   // Look through bitcasts.
5312   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5313     RHS = BCI->getOperand(0);
5314
5315   Value *PtrBase = GEPLHS->getOperand(0);
5316   if (PtrBase == RHS) {
5317     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5318     // This transformation (ignoring the base and scales) is valid because we
5319     // know pointers can't overflow.  See if we can output an optimized form.
5320     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5321     
5322     // If not, synthesize the offset the hard way.
5323     if (Offset == 0)
5324       Offset = EmitGEPOffset(GEPLHS, I, *this);
5325     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5326                         Constant::getNullValue(Offset->getType()));
5327   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5328     // If the base pointers are different, but the indices are the same, just
5329     // compare the base pointer.
5330     if (PtrBase != GEPRHS->getOperand(0)) {
5331       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5332       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5333                         GEPRHS->getOperand(0)->getType();
5334       if (IndicesTheSame)
5335         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5336           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5337             IndicesTheSame = false;
5338             break;
5339           }
5340
5341       // If all indices are the same, just compare the base pointers.
5342       if (IndicesTheSame)
5343         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5344                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5345
5346       // Otherwise, the base pointers are different and the indices are
5347       // different, bail out.
5348       return 0;
5349     }
5350
5351     // If one of the GEPs has all zero indices, recurse.
5352     bool AllZeros = true;
5353     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5354       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5355           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5356         AllZeros = false;
5357         break;
5358       }
5359     if (AllZeros)
5360       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5361                           ICmpInst::getSwappedPredicate(Cond), I);
5362
5363     // If the other GEP has all zero indices, recurse.
5364     AllZeros = true;
5365     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5366       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5367           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5368         AllZeros = false;
5369         break;
5370       }
5371     if (AllZeros)
5372       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5373
5374     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5375       // If the GEPs only differ by one index, compare it.
5376       unsigned NumDifferences = 0;  // Keep track of # differences.
5377       unsigned DiffOperand = 0;     // The operand that differs.
5378       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5379         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5380           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5381                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5382             // Irreconcilable differences.
5383             NumDifferences = 2;
5384             break;
5385           } else {
5386             if (NumDifferences++) break;
5387             DiffOperand = i;
5388           }
5389         }
5390
5391       if (NumDifferences == 0)   // SAME GEP?
5392         return ReplaceInstUsesWith(I, // No comparison is needed here.
5393                                    ConstantInt::get(Type::Int1Ty,
5394                                              ICmpInst::isTrueWhenEqual(Cond)));
5395
5396       else if (NumDifferences == 1) {
5397         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5398         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5399         // Make sure we do a signed comparison here.
5400         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5401       }
5402     }
5403
5404     // Only lower this if the icmp is the only user of the GEP or if we expect
5405     // the result to fold to a constant!
5406     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5407         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5408       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5409       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5410       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5411       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5412     }
5413   }
5414   return 0;
5415 }
5416
5417 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5418 ///
5419 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5420                                                 Instruction *LHSI,
5421                                                 Constant *RHSC) {
5422   if (!isa<ConstantFP>(RHSC)) return 0;
5423   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5424   
5425   // Get the width of the mantissa.  We don't want to hack on conversions that
5426   // might lose information from the integer, e.g. "i64 -> float"
5427   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5428   if (MantissaWidth == -1) return 0;  // Unknown.
5429   
5430   // Check to see that the input is converted from an integer type that is small
5431   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5432   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5433   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5434   
5435   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5436   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5437   if (LHSUnsigned)
5438     ++InputSize;
5439   
5440   // If the conversion would lose info, don't hack on this.
5441   if ((int)InputSize > MantissaWidth)
5442     return 0;
5443   
5444   // Otherwise, we can potentially simplify the comparison.  We know that it
5445   // will always come through as an integer value and we know the constant is
5446   // not a NAN (it would have been previously simplified).
5447   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5448   
5449   ICmpInst::Predicate Pred;
5450   switch (I.getPredicate()) {
5451   default: assert(0 && "Unexpected predicate!");
5452   case FCmpInst::FCMP_UEQ:
5453   case FCmpInst::FCMP_OEQ:
5454     Pred = ICmpInst::ICMP_EQ;
5455     break;
5456   case FCmpInst::FCMP_UGT:
5457   case FCmpInst::FCMP_OGT:
5458     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5459     break;
5460   case FCmpInst::FCMP_UGE:
5461   case FCmpInst::FCMP_OGE:
5462     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5463     break;
5464   case FCmpInst::FCMP_ULT:
5465   case FCmpInst::FCMP_OLT:
5466     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5467     break;
5468   case FCmpInst::FCMP_ULE:
5469   case FCmpInst::FCMP_OLE:
5470     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5471     break;
5472   case FCmpInst::FCMP_UNE:
5473   case FCmpInst::FCMP_ONE:
5474     Pred = ICmpInst::ICMP_NE;
5475     break;
5476   case FCmpInst::FCMP_ORD:
5477     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5478   case FCmpInst::FCMP_UNO:
5479     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5480   }
5481   
5482   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5483   
5484   // Now we know that the APFloat is a normal number, zero or inf.
5485   
5486   // See if the FP constant is too large for the integer.  For example,
5487   // comparing an i8 to 300.0.
5488   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5489   
5490   if (!LHSUnsigned) {
5491     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5492     // and large values.
5493     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5494     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5495                           APFloat::rmNearestTiesToEven);
5496     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5497       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5498           Pred == ICmpInst::ICMP_SLE)
5499         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5500       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5501     }
5502   } else {
5503     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5504     // +INF and large values.
5505     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5506     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5507                           APFloat::rmNearestTiesToEven);
5508     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5509       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5510           Pred == ICmpInst::ICMP_ULE)
5511         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5512       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5513     }
5514   }
5515   
5516   if (!LHSUnsigned) {
5517     // See if the RHS value is < SignedMin.
5518     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5519     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5520                           APFloat::rmNearestTiesToEven);
5521     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5522       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5523           Pred == ICmpInst::ICMP_SGE)
5524         return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5525       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5526     }
5527   }
5528
5529   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5530   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5531   // casting the FP value to the integer value and back, checking for equality.
5532   // Don't do this for zero, because -0.0 is not fractional.
5533   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5534   if (!RHS.isZero() &&
5535       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5536     // If we had a comparison against a fractional value, we have to adjust the
5537     // compare predicate and sometimes the value.  RHSC is rounded towards zero
5538     // at this point.
5539     switch (Pred) {
5540     default: assert(0 && "Unexpected integer comparison!");
5541     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5542       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5543     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5544       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5545     case ICmpInst::ICMP_ULE:
5546       // (float)int <= 4.4   --> int <= 4
5547       // (float)int <= -4.4  --> false
5548       if (RHS.isNegative())
5549         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5550       break;
5551     case ICmpInst::ICMP_SLE:
5552       // (float)int <= 4.4   --> int <= 4
5553       // (float)int <= -4.4  --> int < -4
5554       if (RHS.isNegative())
5555         Pred = ICmpInst::ICMP_SLT;
5556       break;
5557     case ICmpInst::ICMP_ULT:
5558       // (float)int < -4.4   --> false
5559       // (float)int < 4.4    --> int <= 4
5560       if (RHS.isNegative())
5561         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5562       Pred = ICmpInst::ICMP_ULE;
5563       break;
5564     case ICmpInst::ICMP_SLT:
5565       // (float)int < -4.4   --> int < -4
5566       // (float)int < 4.4    --> int <= 4
5567       if (!RHS.isNegative())
5568         Pred = ICmpInst::ICMP_SLE;
5569       break;
5570     case ICmpInst::ICMP_UGT:
5571       // (float)int > 4.4    --> int > 4
5572       // (float)int > -4.4   --> true
5573       if (RHS.isNegative())
5574         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5575       break;
5576     case ICmpInst::ICMP_SGT:
5577       // (float)int > 4.4    --> int > 4
5578       // (float)int > -4.4   --> int >= -4
5579       if (RHS.isNegative())
5580         Pred = ICmpInst::ICMP_SGE;
5581       break;
5582     case ICmpInst::ICMP_UGE:
5583       // (float)int >= -4.4   --> true
5584       // (float)int >= 4.4    --> int > 4
5585       if (!RHS.isNegative())
5586         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5587       Pred = ICmpInst::ICMP_UGT;
5588       break;
5589     case ICmpInst::ICMP_SGE:
5590       // (float)int >= -4.4   --> int >= -4
5591       // (float)int >= 4.4    --> int > 4
5592       if (!RHS.isNegative())
5593         Pred = ICmpInst::ICMP_SGT;
5594       break;
5595     }
5596   }
5597
5598   // Lower this FP comparison into an appropriate integer version of the
5599   // comparison.
5600   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5601 }
5602
5603 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5604   bool Changed = SimplifyCompare(I);
5605   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5606
5607   // Fold trivial predicates.
5608   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5609     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5610   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5611     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5612   
5613   // Simplify 'fcmp pred X, X'
5614   if (Op0 == Op1) {
5615     switch (I.getPredicate()) {
5616     default: assert(0 && "Unknown predicate!");
5617     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5618     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5619     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5620       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5621     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5622     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5623     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5624       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5625       
5626     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5627     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5628     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5629     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5630       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5631       I.setPredicate(FCmpInst::FCMP_UNO);
5632       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5633       return &I;
5634       
5635     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5636     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5637     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5638     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5639       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5640       I.setPredicate(FCmpInst::FCMP_ORD);
5641       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5642       return &I;
5643     }
5644   }
5645     
5646   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5647     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5648
5649   // Handle fcmp with constant RHS
5650   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5651     // If the constant is a nan, see if we can fold the comparison based on it.
5652     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5653       if (CFP->getValueAPF().isNaN()) {
5654         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5655           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5656         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5657                "Comparison must be either ordered or unordered!");
5658         // True if unordered.
5659         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5660       }
5661     }
5662     
5663     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5664       switch (LHSI->getOpcode()) {
5665       case Instruction::PHI:
5666         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5667         // block.  If in the same block, we're encouraging jump threading.  If
5668         // not, we are just pessimizing the code by making an i1 phi.
5669         if (LHSI->getParent() == I.getParent())
5670           if (Instruction *NV = FoldOpIntoPhi(I))
5671             return NV;
5672         break;
5673       case Instruction::SIToFP:
5674       case Instruction::UIToFP:
5675         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5676           return NV;
5677         break;
5678       case Instruction::Select:
5679         // If either operand of the select is a constant, we can fold the
5680         // comparison into the select arms, which will cause one to be
5681         // constant folded and the select turned into a bitwise or.
5682         Value *Op1 = 0, *Op2 = 0;
5683         if (LHSI->hasOneUse()) {
5684           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5685             // Fold the known value into the constant operand.
5686             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5687             // Insert a new FCmp of the other select operand.
5688             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5689                                                       LHSI->getOperand(2), RHSC,
5690                                                       I.getName()), I);
5691           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5692             // Fold the known value into the constant operand.
5693             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5694             // Insert a new FCmp of the other select operand.
5695             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5696                                                       LHSI->getOperand(1), RHSC,
5697                                                       I.getName()), I);
5698           }
5699         }
5700
5701         if (Op1)
5702           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5703         break;
5704       }
5705   }
5706
5707   return Changed ? &I : 0;
5708 }
5709
5710 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5711   bool Changed = SimplifyCompare(I);
5712   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5713   const Type *Ty = Op0->getType();
5714
5715   // icmp X, X
5716   if (Op0 == Op1)
5717     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5718                                                    I.isTrueWhenEqual()));
5719
5720   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5721     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5722   
5723   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5724   // addresses never equal each other!  We already know that Op0 != Op1.
5725   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5726        isa<ConstantPointerNull>(Op0)) &&
5727       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5728        isa<ConstantPointerNull>(Op1)))
5729     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5730                                                    !I.isTrueWhenEqual()));
5731
5732   // icmp's with boolean values can always be turned into bitwise operations
5733   if (Ty == Type::Int1Ty) {
5734     switch (I.getPredicate()) {
5735     default: assert(0 && "Invalid icmp instruction!");
5736     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5737       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5738       InsertNewInstBefore(Xor, I);
5739       return BinaryOperator::CreateNot(Xor);
5740     }
5741     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5742       return BinaryOperator::CreateXor(Op0, Op1);
5743
5744     case ICmpInst::ICMP_UGT:
5745       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5746       // FALL THROUGH
5747     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5748       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5749       InsertNewInstBefore(Not, I);
5750       return BinaryOperator::CreateAnd(Not, Op1);
5751     }
5752     case ICmpInst::ICMP_SGT:
5753       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5754       // FALL THROUGH
5755     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5756       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5757       InsertNewInstBefore(Not, I);
5758       return BinaryOperator::CreateAnd(Not, Op0);
5759     }
5760     case ICmpInst::ICMP_UGE:
5761       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5762       // FALL THROUGH
5763     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5764       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5765       InsertNewInstBefore(Not, I);
5766       return BinaryOperator::CreateOr(Not, Op1);
5767     }
5768     case ICmpInst::ICMP_SGE:
5769       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5770       // FALL THROUGH
5771     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5772       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5773       InsertNewInstBefore(Not, I);
5774       return BinaryOperator::CreateOr(Not, Op0);
5775     }
5776     }
5777   }
5778
5779   // See if we are doing a comparison with a constant.
5780   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5781     Value *A, *B;
5782     
5783     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5784     if (I.isEquality() && CI->isNullValue() &&
5785         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5786       // (icmp cond A B) if cond is equality
5787       return new ICmpInst(I.getPredicate(), A, B);
5788     }
5789     
5790     // If we have an icmp le or icmp ge instruction, turn it into the
5791     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5792     // them being folded in the code below.
5793     switch (I.getPredicate()) {
5794     default: break;
5795     case ICmpInst::ICMP_ULE:
5796       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5797         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5798       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5799     case ICmpInst::ICMP_SLE:
5800       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5801         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5802       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5803     case ICmpInst::ICMP_UGE:
5804       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5805         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5806       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5807     case ICmpInst::ICMP_SGE:
5808       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5809         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5810       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5811     }
5812     
5813     // See if we can fold the comparison based on range information we can get
5814     // by checking whether bits are known to be zero or one in the input.
5815     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5816     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5817     
5818     // If this comparison is a normal comparison, it demands all
5819     // bits, if it is a sign bit comparison, it only demands the sign bit.
5820     bool UnusedBit;
5821     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5822     
5823     if (SimplifyDemandedBits(Op0, 
5824                              isSignBit ? APInt::getSignBit(BitWidth)
5825                                        : APInt::getAllOnesValue(BitWidth),
5826                              KnownZero, KnownOne, 0))
5827       return &I;
5828         
5829     // Given the known and unknown bits, compute a range that the LHS could be
5830     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5831     // EQ and NE we use unsigned values.
5832     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5833     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5834       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5835     else
5836       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5837     
5838     // If Min and Max are known to be the same, then SimplifyDemandedBits
5839     // figured out that the LHS is a constant.  Just constant fold this now so
5840     // that code below can assume that Min != Max.
5841     if (Min == Max)
5842       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5843                                                           ConstantInt::get(Min),
5844                                                           CI));
5845     
5846     // Based on the range information we know about the LHS, see if we can
5847     // simplify this comparison.  For example, (x&4) < 8  is always true.
5848     const APInt &RHSVal = CI->getValue();
5849     switch (I.getPredicate()) {  // LE/GE have been folded already.
5850     default: assert(0 && "Unknown icmp opcode!");
5851     case ICmpInst::ICMP_EQ:
5852       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5853         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5854       break;
5855     case ICmpInst::ICMP_NE:
5856       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5857         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5858       break;
5859     case ICmpInst::ICMP_ULT:
5860       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5861         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5862       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5863         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5864       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5865         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5866       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5867         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5868         
5869       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5870       if (CI->isMinValue(true))
5871         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5872                             ConstantInt::getAllOnesValue(Op0->getType()));
5873       break;
5874     case ICmpInst::ICMP_UGT:
5875       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5876         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5877       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5878         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5879         
5880       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5881         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5882       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5883         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5884       
5885       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5886       if (CI->isMaxValue(true))
5887         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5888                             ConstantInt::getNullValue(Op0->getType()));
5889       break;
5890     case ICmpInst::ICMP_SLT:
5891       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5892         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5893       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5894         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5895       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5896         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5897       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5898         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5899       break;
5900     case ICmpInst::ICMP_SGT: 
5901       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5902         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5903       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5904         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5905         
5906       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5907         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5908       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5909         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5910       break;
5911     }
5912   }
5913
5914   // Test if the ICmpInst instruction is used exclusively by a select as
5915   // part of a minimum or maximum operation. If so, refrain from doing
5916   // any other folding. This helps out other analyses which understand
5917   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5918   // and CodeGen. And in this case, at least one of the comparison
5919   // operands has at least one user besides the compare (the select),
5920   // which would often largely negate the benefit of folding anyway.
5921   if (I.hasOneUse())
5922     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5923       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5924           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5925         return 0;
5926
5927   // See if we are doing a comparison between a constant and an instruction that
5928   // can be folded into the comparison.
5929   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5930     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5931     // instruction, see if that instruction also has constants so that the 
5932     // instruction can be folded into the icmp 
5933     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5934       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5935         return Res;
5936   }
5937
5938   // Handle icmp with constant (but not simple integer constant) RHS
5939   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5940     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5941       switch (LHSI->getOpcode()) {
5942       case Instruction::GetElementPtr:
5943         if (RHSC->isNullValue()) {
5944           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5945           bool isAllZeros = true;
5946           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5947             if (!isa<Constant>(LHSI->getOperand(i)) ||
5948                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5949               isAllZeros = false;
5950               break;
5951             }
5952           if (isAllZeros)
5953             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5954                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5955         }
5956         break;
5957
5958       case Instruction::PHI:
5959         // Only fold icmp into the PHI if the phi and fcmp are in the same
5960         // block.  If in the same block, we're encouraging jump threading.  If
5961         // not, we are just pessimizing the code by making an i1 phi.
5962         if (LHSI->getParent() == I.getParent())
5963           if (Instruction *NV = FoldOpIntoPhi(I))
5964             return NV;
5965         break;
5966       case Instruction::Select: {
5967         // If either operand of the select is a constant, we can fold the
5968         // comparison into the select arms, which will cause one to be
5969         // constant folded and the select turned into a bitwise or.
5970         Value *Op1 = 0, *Op2 = 0;
5971         if (LHSI->hasOneUse()) {
5972           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5973             // Fold the known value into the constant operand.
5974             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5975             // Insert a new ICmp of the other select operand.
5976             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5977                                                    LHSI->getOperand(2), RHSC,
5978                                                    I.getName()), I);
5979           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5980             // Fold the known value into the constant operand.
5981             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5982             // Insert a new ICmp of the other select operand.
5983             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5984                                                    LHSI->getOperand(1), RHSC,
5985                                                    I.getName()), I);
5986           }
5987         }
5988
5989         if (Op1)
5990           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5991         break;
5992       }
5993       case Instruction::Malloc:
5994         // If we have (malloc != null), and if the malloc has a single use, we
5995         // can assume it is successful and remove the malloc.
5996         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5997           AddToWorkList(LHSI);
5998           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5999                                                          !I.isTrueWhenEqual()));
6000         }
6001         break;
6002       }
6003   }
6004
6005   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6006   if (User *GEP = dyn_castGetElementPtr(Op0))
6007     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6008       return NI;
6009   if (User *GEP = dyn_castGetElementPtr(Op1))
6010     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6011                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6012       return NI;
6013
6014   // Test to see if the operands of the icmp are casted versions of other
6015   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6016   // now.
6017   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6018     if (isa<PointerType>(Op0->getType()) && 
6019         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6020       // We keep moving the cast from the left operand over to the right
6021       // operand, where it can often be eliminated completely.
6022       Op0 = CI->getOperand(0);
6023
6024       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6025       // so eliminate it as well.
6026       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6027         Op1 = CI2->getOperand(0);
6028
6029       // If Op1 is a constant, we can fold the cast into the constant.
6030       if (Op0->getType() != Op1->getType()) {
6031         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6032           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6033         } else {
6034           // Otherwise, cast the RHS right before the icmp
6035           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6036         }
6037       }
6038       return new ICmpInst(I.getPredicate(), Op0, Op1);
6039     }
6040   }
6041   
6042   if (isa<CastInst>(Op0)) {
6043     // Handle the special case of: icmp (cast bool to X), <cst>
6044     // This comes up when you have code like
6045     //   int X = A < B;
6046     //   if (X) ...
6047     // For generality, we handle any zero-extension of any operand comparison
6048     // with a constant or another cast from the same type.
6049     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6050       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6051         return R;
6052   }
6053   
6054   // See if it's the same type of instruction on the left and right.
6055   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6056     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6057       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6058           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
6059           I.isEquality()) {
6060         switch (Op0I->getOpcode()) {
6061         default: break;
6062         case Instruction::Add:
6063         case Instruction::Sub:
6064         case Instruction::Xor:
6065           // a+x icmp eq/ne b+x --> a icmp b
6066           return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6067                               Op1I->getOperand(0));
6068           break;
6069         case Instruction::Mul:
6070           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6071             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6072             // Mask = -1 >> count-trailing-zeros(Cst).
6073             if (!CI->isZero() && !CI->isOne()) {
6074               const APInt &AP = CI->getValue();
6075               ConstantInt *Mask = ConstantInt::get(
6076                                       APInt::getLowBitsSet(AP.getBitWidth(),
6077                                                            AP.getBitWidth() -
6078                                                       AP.countTrailingZeros()));
6079               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6080                                                             Mask);
6081               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6082                                                             Mask);
6083               InsertNewInstBefore(And1, I);
6084               InsertNewInstBefore(And2, I);
6085               return new ICmpInst(I.getPredicate(), And1, And2);
6086             }
6087           }
6088           break;
6089         }
6090       }
6091     }
6092   }
6093   
6094   // ~x < ~y --> y < x
6095   { Value *A, *B;
6096     if (match(Op0, m_Not(m_Value(A))) &&
6097         match(Op1, m_Not(m_Value(B))))
6098       return new ICmpInst(I.getPredicate(), B, A);
6099   }
6100   
6101   if (I.isEquality()) {
6102     Value *A, *B, *C, *D;
6103     
6104     // -x == -y --> x == y
6105     if (match(Op0, m_Neg(m_Value(A))) &&
6106         match(Op1, m_Neg(m_Value(B))))
6107       return new ICmpInst(I.getPredicate(), A, B);
6108     
6109     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6110       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6111         Value *OtherVal = A == Op1 ? B : A;
6112         return new ICmpInst(I.getPredicate(), OtherVal,
6113                             Constant::getNullValue(A->getType()));
6114       }
6115
6116       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6117         // A^c1 == C^c2 --> A == C^(c1^c2)
6118         ConstantInt *C1, *C2;
6119         if (match(B, m_ConstantInt(C1)) &&
6120             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6121           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6122           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6123           return new ICmpInst(I.getPredicate(), A,
6124                               InsertNewInstBefore(Xor, I));
6125         }
6126         
6127         // A^B == A^D -> B == D
6128         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6129         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6130         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6131         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6132       }
6133     }
6134     
6135     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6136         (A == Op0 || B == Op0)) {
6137       // A == (A^B)  ->  B == 0
6138       Value *OtherVal = A == Op0 ? B : A;
6139       return new ICmpInst(I.getPredicate(), OtherVal,
6140                           Constant::getNullValue(A->getType()));
6141     }
6142
6143     // (A-B) == A  ->  B == 0
6144     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6145       return new ICmpInst(I.getPredicate(), B, 
6146                           Constant::getNullValue(B->getType()));
6147
6148     // A == (A-B)  ->  B == 0
6149     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6150       return new ICmpInst(I.getPredicate(), B,
6151                           Constant::getNullValue(B->getType()));
6152     
6153     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6154     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6155         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6156         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6157       Value *X = 0, *Y = 0, *Z = 0;
6158       
6159       if (A == C) {
6160         X = B; Y = D; Z = A;
6161       } else if (A == D) {
6162         X = B; Y = C; Z = A;
6163       } else if (B == C) {
6164         X = A; Y = D; Z = B;
6165       } else if (B == D) {
6166         X = A; Y = C; Z = B;
6167       }
6168       
6169       if (X) {   // Build (X^Y) & Z
6170         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6171         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6172         I.setOperand(0, Op1);
6173         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6174         return &I;
6175       }
6176     }
6177   }
6178   return Changed ? &I : 0;
6179 }
6180
6181
6182 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6183 /// and CmpRHS are both known to be integer constants.
6184 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6185                                           ConstantInt *DivRHS) {
6186   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6187   const APInt &CmpRHSV = CmpRHS->getValue();
6188   
6189   // FIXME: If the operand types don't match the type of the divide 
6190   // then don't attempt this transform. The code below doesn't have the
6191   // logic to deal with a signed divide and an unsigned compare (and
6192   // vice versa). This is because (x /s C1) <s C2  produces different 
6193   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6194   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6195   // work. :(  The if statement below tests that condition and bails 
6196   // if it finds it. 
6197   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6198   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6199     return 0;
6200   if (DivRHS->isZero())
6201     return 0; // The ProdOV computation fails on divide by zero.
6202   if (DivIsSigned && DivRHS->isAllOnesValue())
6203     return 0; // The overflow computation also screws up here
6204   if (DivRHS->isOne())
6205     return 0; // Not worth bothering, and eliminates some funny cases
6206               // with INT_MIN.
6207
6208   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6209   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6210   // C2 (CI). By solving for X we can turn this into a range check 
6211   // instead of computing a divide. 
6212   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6213
6214   // Determine if the product overflows by seeing if the product is
6215   // not equal to the divide. Make sure we do the same kind of divide
6216   // as in the LHS instruction that we're folding. 
6217   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6218                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6219
6220   // Get the ICmp opcode
6221   ICmpInst::Predicate Pred = ICI.getPredicate();
6222
6223   // Figure out the interval that is being checked.  For example, a comparison
6224   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6225   // Compute this interval based on the constants involved and the signedness of
6226   // the compare/divide.  This computes a half-open interval, keeping track of
6227   // whether either value in the interval overflows.  After analysis each
6228   // overflow variable is set to 0 if it's corresponding bound variable is valid
6229   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6230   int LoOverflow = 0, HiOverflow = 0;
6231   ConstantInt *LoBound = 0, *HiBound = 0;
6232   
6233   if (!DivIsSigned) {  // udiv
6234     // e.g. X/5 op 3  --> [15, 20)
6235     LoBound = Prod;
6236     HiOverflow = LoOverflow = ProdOV;
6237     if (!HiOverflow)
6238       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6239   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6240     if (CmpRHSV == 0) {       // (X / pos) op 0
6241       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6242       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6243       HiBound = DivRHS;
6244     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6245       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6246       HiOverflow = LoOverflow = ProdOV;
6247       if (!HiOverflow)
6248         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6249     } else {                       // (X / pos) op neg
6250       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6251       HiBound = AddOne(Prod);
6252       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6253       if (!LoOverflow) {
6254         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6255         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6256                                      true) ? -1 : 0;
6257        }
6258     }
6259   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6260     if (CmpRHSV == 0) {       // (X / neg) op 0
6261       // e.g. X/-5 op 0  --> [-4, 5)
6262       LoBound = AddOne(DivRHS);
6263       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6264       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6265         HiOverflow = 1;            // [INTMIN+1, overflow)
6266         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6267       }
6268     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6269       // e.g. X/-5 op 3  --> [-19, -14)
6270       HiBound = AddOne(Prod);
6271       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6272       if (!LoOverflow)
6273         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6274     } else {                       // (X / neg) op neg
6275       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6276       LoOverflow = HiOverflow = ProdOV;
6277       if (!HiOverflow)
6278         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6279     }
6280     
6281     // Dividing by a negative swaps the condition.  LT <-> GT
6282     Pred = ICmpInst::getSwappedPredicate(Pred);
6283   }
6284
6285   Value *X = DivI->getOperand(0);
6286   switch (Pred) {
6287   default: assert(0 && "Unhandled icmp opcode!");
6288   case ICmpInst::ICMP_EQ:
6289     if (LoOverflow && HiOverflow)
6290       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6291     else if (HiOverflow)
6292       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6293                           ICmpInst::ICMP_UGE, X, LoBound);
6294     else if (LoOverflow)
6295       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6296                           ICmpInst::ICMP_ULT, X, HiBound);
6297     else
6298       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6299   case ICmpInst::ICMP_NE:
6300     if (LoOverflow && HiOverflow)
6301       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6302     else if (HiOverflow)
6303       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6304                           ICmpInst::ICMP_ULT, X, LoBound);
6305     else if (LoOverflow)
6306       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6307                           ICmpInst::ICMP_UGE, X, HiBound);
6308     else
6309       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6310   case ICmpInst::ICMP_ULT:
6311   case ICmpInst::ICMP_SLT:
6312     if (LoOverflow == +1)   // Low bound is greater than input range.
6313       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6314     if (LoOverflow == -1)   // Low bound is less than input range.
6315       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6316     return new ICmpInst(Pred, X, LoBound);
6317   case ICmpInst::ICMP_UGT:
6318   case ICmpInst::ICMP_SGT:
6319     if (HiOverflow == +1)       // High bound greater than input range.
6320       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6321     else if (HiOverflow == -1)  // High bound less than input range.
6322       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6323     if (Pred == ICmpInst::ICMP_UGT)
6324       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6325     else
6326       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6327   }
6328 }
6329
6330
6331 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6332 ///
6333 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6334                                                           Instruction *LHSI,
6335                                                           ConstantInt *RHS) {
6336   const APInt &RHSV = RHS->getValue();
6337   
6338   switch (LHSI->getOpcode()) {
6339   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6340     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6341       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6342       // fold the xor.
6343       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6344           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6345         Value *CompareVal = LHSI->getOperand(0);
6346         
6347         // If the sign bit of the XorCST is not set, there is no change to
6348         // the operation, just stop using the Xor.
6349         if (!XorCST->getValue().isNegative()) {
6350           ICI.setOperand(0, CompareVal);
6351           AddToWorkList(LHSI);
6352           return &ICI;
6353         }
6354         
6355         // Was the old condition true if the operand is positive?
6356         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6357         
6358         // If so, the new one isn't.
6359         isTrueIfPositive ^= true;
6360         
6361         if (isTrueIfPositive)
6362           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6363         else
6364           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6365       }
6366     }
6367     break;
6368   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6369     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6370         LHSI->getOperand(0)->hasOneUse()) {
6371       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6372       
6373       // If the LHS is an AND of a truncating cast, we can widen the
6374       // and/compare to be the input width without changing the value
6375       // produced, eliminating a cast.
6376       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6377         // We can do this transformation if either the AND constant does not
6378         // have its sign bit set or if it is an equality comparison. 
6379         // Extending a relational comparison when we're checking the sign
6380         // bit would not work.
6381         if (Cast->hasOneUse() &&
6382             (ICI.isEquality() ||
6383              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6384           uint32_t BitWidth = 
6385             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6386           APInt NewCST = AndCST->getValue();
6387           NewCST.zext(BitWidth);
6388           APInt NewCI = RHSV;
6389           NewCI.zext(BitWidth);
6390           Instruction *NewAnd = 
6391             BinaryOperator::CreateAnd(Cast->getOperand(0),
6392                                       ConstantInt::get(NewCST),LHSI->getName());
6393           InsertNewInstBefore(NewAnd, ICI);
6394           return new ICmpInst(ICI.getPredicate(), NewAnd,
6395                               ConstantInt::get(NewCI));
6396         }
6397       }
6398       
6399       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6400       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6401       // happens a LOT in code produced by the C front-end, for bitfield
6402       // access.
6403       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6404       if (Shift && !Shift->isShift())
6405         Shift = 0;
6406       
6407       ConstantInt *ShAmt;
6408       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6409       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6410       const Type *AndTy = AndCST->getType();          // Type of the and.
6411       
6412       // We can fold this as long as we can't shift unknown bits
6413       // into the mask.  This can only happen with signed shift
6414       // rights, as they sign-extend.
6415       if (ShAmt) {
6416         bool CanFold = Shift->isLogicalShift();
6417         if (!CanFold) {
6418           // To test for the bad case of the signed shr, see if any
6419           // of the bits shifted in could be tested after the mask.
6420           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6421           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6422           
6423           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6424           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6425                AndCST->getValue()) == 0)
6426             CanFold = true;
6427         }
6428         
6429         if (CanFold) {
6430           Constant *NewCst;
6431           if (Shift->getOpcode() == Instruction::Shl)
6432             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6433           else
6434             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6435           
6436           // Check to see if we are shifting out any of the bits being
6437           // compared.
6438           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6439             // If we shifted bits out, the fold is not going to work out.
6440             // As a special case, check to see if this means that the
6441             // result is always true or false now.
6442             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6443               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6444             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6445               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6446           } else {
6447             ICI.setOperand(1, NewCst);
6448             Constant *NewAndCST;
6449             if (Shift->getOpcode() == Instruction::Shl)
6450               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6451             else
6452               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6453             LHSI->setOperand(1, NewAndCST);
6454             LHSI->setOperand(0, Shift->getOperand(0));
6455             AddToWorkList(Shift); // Shift is dead.
6456             AddUsesToWorkList(ICI);
6457             return &ICI;
6458           }
6459         }
6460       }
6461       
6462       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6463       // preferable because it allows the C<<Y expression to be hoisted out
6464       // of a loop if Y is invariant and X is not.
6465       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6466           ICI.isEquality() && !Shift->isArithmeticShift() &&
6467           isa<Instruction>(Shift->getOperand(0))) {
6468         // Compute C << Y.
6469         Value *NS;
6470         if (Shift->getOpcode() == Instruction::LShr) {
6471           NS = BinaryOperator::CreateShl(AndCST, 
6472                                          Shift->getOperand(1), "tmp");
6473         } else {
6474           // Insert a logical shift.
6475           NS = BinaryOperator::CreateLShr(AndCST,
6476                                           Shift->getOperand(1), "tmp");
6477         }
6478         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6479         
6480         // Compute X & (C << Y).
6481         Instruction *NewAnd = 
6482           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6483         InsertNewInstBefore(NewAnd, ICI);
6484         
6485         ICI.setOperand(0, NewAnd);
6486         return &ICI;
6487       }
6488     }
6489     break;
6490     
6491   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6492     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6493     if (!ShAmt) break;
6494     
6495     uint32_t TypeBits = RHSV.getBitWidth();
6496     
6497     // Check that the shift amount is in range.  If not, don't perform
6498     // undefined shifts.  When the shift is visited it will be
6499     // simplified.
6500     if (ShAmt->uge(TypeBits))
6501       break;
6502     
6503     if (ICI.isEquality()) {
6504       // If we are comparing against bits always shifted out, the
6505       // comparison cannot succeed.
6506       Constant *Comp =
6507         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6508       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6509         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6510         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6511         return ReplaceInstUsesWith(ICI, Cst);
6512       }
6513       
6514       if (LHSI->hasOneUse()) {
6515         // Otherwise strength reduce the shift into an and.
6516         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6517         Constant *Mask =
6518           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6519         
6520         Instruction *AndI =
6521           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6522                                     Mask, LHSI->getName()+".mask");
6523         Value *And = InsertNewInstBefore(AndI, ICI);
6524         return new ICmpInst(ICI.getPredicate(), And,
6525                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6526       }
6527     }
6528     
6529     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6530     bool TrueIfSigned = false;
6531     if (LHSI->hasOneUse() &&
6532         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6533       // (X << 31) <s 0  --> (X&1) != 0
6534       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6535                                            (TypeBits-ShAmt->getZExtValue()-1));
6536       Instruction *AndI =
6537         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6538                                   Mask, LHSI->getName()+".mask");
6539       Value *And = InsertNewInstBefore(AndI, ICI);
6540       
6541       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6542                           And, Constant::getNullValue(And->getType()));
6543     }
6544     break;
6545   }
6546     
6547   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6548   case Instruction::AShr: {
6549     // Only handle equality comparisons of shift-by-constant.
6550     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6551     if (!ShAmt || !ICI.isEquality()) break;
6552
6553     // Check that the shift amount is in range.  If not, don't perform
6554     // undefined shifts.  When the shift is visited it will be
6555     // simplified.
6556     uint32_t TypeBits = RHSV.getBitWidth();
6557     if (ShAmt->uge(TypeBits))
6558       break;
6559     
6560     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6561       
6562     // If we are comparing against bits always shifted out, the
6563     // comparison cannot succeed.
6564     APInt Comp = RHSV << ShAmtVal;
6565     if (LHSI->getOpcode() == Instruction::LShr)
6566       Comp = Comp.lshr(ShAmtVal);
6567     else
6568       Comp = Comp.ashr(ShAmtVal);
6569     
6570     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6571       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6572       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6573       return ReplaceInstUsesWith(ICI, Cst);
6574     }
6575     
6576     // Otherwise, check to see if the bits shifted out are known to be zero.
6577     // If so, we can compare against the unshifted value:
6578     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6579     if (LHSI->hasOneUse() &&
6580         MaskedValueIsZero(LHSI->getOperand(0), 
6581                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6582       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6583                           ConstantExpr::getShl(RHS, ShAmt));
6584     }
6585       
6586     if (LHSI->hasOneUse()) {
6587       // Otherwise strength reduce the shift into an and.
6588       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6589       Constant *Mask = ConstantInt::get(Val);
6590       
6591       Instruction *AndI =
6592         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6593                                   Mask, LHSI->getName()+".mask");
6594       Value *And = InsertNewInstBefore(AndI, ICI);
6595       return new ICmpInst(ICI.getPredicate(), And,
6596                           ConstantExpr::getShl(RHS, ShAmt));
6597     }
6598     break;
6599   }
6600     
6601   case Instruction::SDiv:
6602   case Instruction::UDiv:
6603     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6604     // Fold this div into the comparison, producing a range check. 
6605     // Determine, based on the divide type, what the range is being 
6606     // checked.  If there is an overflow on the low or high side, remember 
6607     // it, otherwise compute the range [low, hi) bounding the new value.
6608     // See: InsertRangeTest above for the kinds of replacements possible.
6609     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6610       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6611                                           DivRHS))
6612         return R;
6613     break;
6614
6615   case Instruction::Add:
6616     // Fold: icmp pred (add, X, C1), C2
6617
6618     if (!ICI.isEquality()) {
6619       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6620       if (!LHSC) break;
6621       const APInt &LHSV = LHSC->getValue();
6622
6623       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6624                             .subtract(LHSV);
6625
6626       if (ICI.isSignedPredicate()) {
6627         if (CR.getLower().isSignBit()) {
6628           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6629                               ConstantInt::get(CR.getUpper()));
6630         } else if (CR.getUpper().isSignBit()) {
6631           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6632                               ConstantInt::get(CR.getLower()));
6633         }
6634       } else {
6635         if (CR.getLower().isMinValue()) {
6636           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6637                               ConstantInt::get(CR.getUpper()));
6638         } else if (CR.getUpper().isMinValue()) {
6639           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6640                               ConstantInt::get(CR.getLower()));
6641         }
6642       }
6643     }
6644     break;
6645   }
6646   
6647   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6648   if (ICI.isEquality()) {
6649     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6650     
6651     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6652     // the second operand is a constant, simplify a bit.
6653     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6654       switch (BO->getOpcode()) {
6655       case Instruction::SRem:
6656         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6657         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6658           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6659           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6660             Instruction *NewRem =
6661               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6662                                          BO->getName());
6663             InsertNewInstBefore(NewRem, ICI);
6664             return new ICmpInst(ICI.getPredicate(), NewRem, 
6665                                 Constant::getNullValue(BO->getType()));
6666           }
6667         }
6668         break;
6669       case Instruction::Add:
6670         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6671         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6672           if (BO->hasOneUse())
6673             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6674                                 Subtract(RHS, BOp1C));
6675         } else if (RHSV == 0) {
6676           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6677           // efficiently invertible, or if the add has just this one use.
6678           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6679           
6680           if (Value *NegVal = dyn_castNegVal(BOp1))
6681             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6682           else if (Value *NegVal = dyn_castNegVal(BOp0))
6683             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6684           else if (BO->hasOneUse()) {
6685             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6686             InsertNewInstBefore(Neg, ICI);
6687             Neg->takeName(BO);
6688             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6689           }
6690         }
6691         break;
6692       case Instruction::Xor:
6693         // For the xor case, we can xor two constants together, eliminating
6694         // the explicit xor.
6695         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6696           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6697                               ConstantExpr::getXor(RHS, BOC));
6698         
6699         // FALLTHROUGH
6700       case Instruction::Sub:
6701         // Replace (([sub|xor] A, B) != 0) with (A != B)
6702         if (RHSV == 0)
6703           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6704                               BO->getOperand(1));
6705         break;
6706         
6707       case Instruction::Or:
6708         // If bits are being or'd in that are not present in the constant we
6709         // are comparing against, then the comparison could never succeed!
6710         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6711           Constant *NotCI = ConstantExpr::getNot(RHS);
6712           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6713             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6714                                                              isICMP_NE));
6715         }
6716         break;
6717         
6718       case Instruction::And:
6719         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6720           // If bits are being compared against that are and'd out, then the
6721           // comparison can never succeed!
6722           if ((RHSV & ~BOC->getValue()) != 0)
6723             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6724                                                              isICMP_NE));
6725           
6726           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6727           if (RHS == BOC && RHSV.isPowerOf2())
6728             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6729                                 ICmpInst::ICMP_NE, LHSI,
6730                                 Constant::getNullValue(RHS->getType()));
6731           
6732           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6733           if (BOC->getValue().isSignBit()) {
6734             Value *X = BO->getOperand(0);
6735             Constant *Zero = Constant::getNullValue(X->getType());
6736             ICmpInst::Predicate pred = isICMP_NE ? 
6737               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6738             return new ICmpInst(pred, X, Zero);
6739           }
6740           
6741           // ((X & ~7) == 0) --> X < 8
6742           if (RHSV == 0 && isHighOnes(BOC)) {
6743             Value *X = BO->getOperand(0);
6744             Constant *NegX = ConstantExpr::getNeg(BOC);
6745             ICmpInst::Predicate pred = isICMP_NE ? 
6746               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6747             return new ICmpInst(pred, X, NegX);
6748           }
6749         }
6750       default: break;
6751       }
6752     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6753       // Handle icmp {eq|ne} <intrinsic>, intcst.
6754       if (II->getIntrinsicID() == Intrinsic::bswap) {
6755         AddToWorkList(II);
6756         ICI.setOperand(0, II->getOperand(1));
6757         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6758         return &ICI;
6759       }
6760     }
6761   } else {  // Not a ICMP_EQ/ICMP_NE
6762             // If the LHS is a cast from an integral value of the same size, 
6763             // then since we know the RHS is a constant, try to simlify.
6764     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6765       Value *CastOp = Cast->getOperand(0);
6766       const Type *SrcTy = CastOp->getType();
6767       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6768       if (SrcTy->isInteger() && 
6769           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6770         // If this is an unsigned comparison, try to make the comparison use
6771         // smaller constant values.
6772         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6773           // X u< 128 => X s> -1
6774           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6775                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6776         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6777                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6778           // X u> 127 => X s< 0
6779           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6780                               Constant::getNullValue(SrcTy));
6781         }
6782       }
6783     }
6784   }
6785   return 0;
6786 }
6787
6788 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6789 /// We only handle extending casts so far.
6790 ///
6791 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6792   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6793   Value *LHSCIOp        = LHSCI->getOperand(0);
6794   const Type *SrcTy     = LHSCIOp->getType();
6795   const Type *DestTy    = LHSCI->getType();
6796   Value *RHSCIOp;
6797
6798   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6799   // integer type is the same size as the pointer type.
6800   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6801       getTargetData().getPointerSizeInBits() == 
6802          cast<IntegerType>(DestTy)->getBitWidth()) {
6803     Value *RHSOp = 0;
6804     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6805       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6806     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6807       RHSOp = RHSC->getOperand(0);
6808       // If the pointer types don't match, insert a bitcast.
6809       if (LHSCIOp->getType() != RHSOp->getType())
6810         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6811     }
6812
6813     if (RHSOp)
6814       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6815   }
6816   
6817   // The code below only handles extension cast instructions, so far.
6818   // Enforce this.
6819   if (LHSCI->getOpcode() != Instruction::ZExt &&
6820       LHSCI->getOpcode() != Instruction::SExt)
6821     return 0;
6822
6823   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6824   bool isSignedCmp = ICI.isSignedPredicate();
6825
6826   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6827     // Not an extension from the same type?
6828     RHSCIOp = CI->getOperand(0);
6829     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6830       return 0;
6831     
6832     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6833     // and the other is a zext), then we can't handle this.
6834     if (CI->getOpcode() != LHSCI->getOpcode())
6835       return 0;
6836
6837     // Deal with equality cases early.
6838     if (ICI.isEquality())
6839       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6840
6841     // A signed comparison of sign extended values simplifies into a
6842     // signed comparison.
6843     if (isSignedCmp && isSignedExt)
6844       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6845
6846     // The other three cases all fold into an unsigned comparison.
6847     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6848   }
6849
6850   // If we aren't dealing with a constant on the RHS, exit early
6851   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6852   if (!CI)
6853     return 0;
6854
6855   // Compute the constant that would happen if we truncated to SrcTy then
6856   // reextended to DestTy.
6857   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6858   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6859
6860   // If the re-extended constant didn't change...
6861   if (Res2 == CI) {
6862     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6863     // For example, we might have:
6864     //    %A = sext short %X to uint
6865     //    %B = icmp ugt uint %A, 1330
6866     // It is incorrect to transform this into 
6867     //    %B = icmp ugt short %X, 1330 
6868     // because %A may have negative value. 
6869     //
6870     // However, we allow this when the compare is EQ/NE, because they are
6871     // signless.
6872     if (isSignedExt == isSignedCmp || ICI.isEquality())
6873       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6874     return 0;
6875   }
6876
6877   // The re-extended constant changed so the constant cannot be represented 
6878   // in the shorter type. Consequently, we cannot emit a simple comparison.
6879
6880   // First, handle some easy cases. We know the result cannot be equal at this
6881   // point so handle the ICI.isEquality() cases
6882   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6883     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6884   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6885     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6886
6887   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6888   // should have been folded away previously and not enter in here.
6889   Value *Result;
6890   if (isSignedCmp) {
6891     // We're performing a signed comparison.
6892     if (cast<ConstantInt>(CI)->getValue().isNegative())
6893       Result = ConstantInt::getFalse();          // X < (small) --> false
6894     else
6895       Result = ConstantInt::getTrue();           // X < (large) --> true
6896   } else {
6897     // We're performing an unsigned comparison.
6898     if (isSignedExt) {
6899       // We're performing an unsigned comp with a sign extended value.
6900       // This is true if the input is >= 0. [aka >s -1]
6901       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6902       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6903                                    NegOne, ICI.getName()), ICI);
6904     } else {
6905       // Unsigned extend & unsigned compare -> always true.
6906       Result = ConstantInt::getTrue();
6907     }
6908   }
6909
6910   // Finally, return the value computed.
6911   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6912       ICI.getPredicate() == ICmpInst::ICMP_SLT)
6913     return ReplaceInstUsesWith(ICI, Result);
6914
6915   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6916           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6917          "ICmp should be folded!");
6918   if (Constant *CI = dyn_cast<Constant>(Result))
6919     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6920   return BinaryOperator::CreateNot(Result);
6921 }
6922
6923 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6924   return commonShiftTransforms(I);
6925 }
6926
6927 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6928   return commonShiftTransforms(I);
6929 }
6930
6931 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6932   if (Instruction *R = commonShiftTransforms(I))
6933     return R;
6934   
6935   Value *Op0 = I.getOperand(0);
6936   
6937   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6938   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6939     if (CSI->isAllOnesValue())
6940       return ReplaceInstUsesWith(I, CSI);
6941   
6942   // See if we can turn a signed shr into an unsigned shr.
6943   if (!isa<VectorType>(I.getType()) &&
6944       MaskedValueIsZero(Op0,
6945                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6946     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6947   
6948   return 0;
6949 }
6950
6951 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6952   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6953   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6954
6955   // shl X, 0 == X and shr X, 0 == X
6956   // shl 0, X == 0 and shr 0, X == 0
6957   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6958       Op0 == Constant::getNullValue(Op0->getType()))
6959     return ReplaceInstUsesWith(I, Op0);
6960   
6961   if (isa<UndefValue>(Op0)) {            
6962     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6963       return ReplaceInstUsesWith(I, Op0);
6964     else                                    // undef << X -> 0, undef >>u X -> 0
6965       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6966   }
6967   if (isa<UndefValue>(Op1)) {
6968     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6969       return ReplaceInstUsesWith(I, Op0);          
6970     else                                     // X << undef, X >>u undef -> 0
6971       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6972   }
6973
6974   // Try to fold constant and into select arguments.
6975   if (isa<Constant>(Op0))
6976     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6977       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6978         return R;
6979
6980   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6981     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6982       return Res;
6983   return 0;
6984 }
6985
6986 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6987                                                BinaryOperator &I) {
6988   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6989
6990   // See if we can simplify any instructions used by the instruction whose sole 
6991   // purpose is to compute bits we don't care about.
6992   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6993   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6994   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6995                            KnownZero, KnownOne))
6996     return &I;
6997   
6998   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6999   // of a signed value.
7000   //
7001   if (Op1->uge(TypeBits)) {
7002     if (I.getOpcode() != Instruction::AShr)
7003       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7004     else {
7005       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7006       return &I;
7007     }
7008   }
7009   
7010   // ((X*C1) << C2) == (X * (C1 << C2))
7011   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7012     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7013       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7014         return BinaryOperator::CreateMul(BO->getOperand(0),
7015                                          ConstantExpr::getShl(BOOp, Op1));
7016   
7017   // Try to fold constant and into select arguments.
7018   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7019     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7020       return R;
7021   if (isa<PHINode>(Op0))
7022     if (Instruction *NV = FoldOpIntoPhi(I))
7023       return NV;
7024   
7025   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7026   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7027     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7028     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7029     // place.  Don't try to do this transformation in this case.  Also, we
7030     // require that the input operand is a shift-by-constant so that we have
7031     // confidence that the shifts will get folded together.  We could do this
7032     // xform in more cases, but it is unlikely to be profitable.
7033     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7034         isa<ConstantInt>(TrOp->getOperand(1))) {
7035       // Okay, we'll do this xform.  Make the shift of shift.
7036       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7037       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7038                                                 I.getName());
7039       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7040
7041       // For logical shifts, the truncation has the effect of making the high
7042       // part of the register be zeros.  Emulate this by inserting an AND to
7043       // clear the top bits as needed.  This 'and' will usually be zapped by
7044       // other xforms later if dead.
7045       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7046       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7047       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7048       
7049       // The mask we constructed says what the trunc would do if occurring
7050       // between the shifts.  We want to know the effect *after* the second
7051       // shift.  We know that it is a logical shift by a constant, so adjust the
7052       // mask as appropriate.
7053       if (I.getOpcode() == Instruction::Shl)
7054         MaskV <<= Op1->getZExtValue();
7055       else {
7056         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7057         MaskV = MaskV.lshr(Op1->getZExtValue());
7058       }
7059
7060       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7061                                                    TI->getName());
7062       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7063
7064       // Return the value truncated to the interesting size.
7065       return new TruncInst(And, I.getType());
7066     }
7067   }
7068   
7069   if (Op0->hasOneUse()) {
7070     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7071       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7072       Value *V1, *V2;
7073       ConstantInt *CC;
7074       switch (Op0BO->getOpcode()) {
7075         default: break;
7076         case Instruction::Add:
7077         case Instruction::And:
7078         case Instruction::Or:
7079         case Instruction::Xor: {
7080           // These operators commute.
7081           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7082           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7083               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7084             Instruction *YS = BinaryOperator::CreateShl(
7085                                             Op0BO->getOperand(0), Op1,
7086                                             Op0BO->getName());
7087             InsertNewInstBefore(YS, I); // (Y << C)
7088             Instruction *X = 
7089               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7090                                      Op0BO->getOperand(1)->getName());
7091             InsertNewInstBefore(X, I);  // (X + (Y << C))
7092             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7093             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7094                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7095           }
7096           
7097           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7098           Value *Op0BOOp1 = Op0BO->getOperand(1);
7099           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7100               match(Op0BOOp1, 
7101                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7102                           m_ConstantInt(CC))) &&
7103               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7104             Instruction *YS = BinaryOperator::CreateShl(
7105                                                      Op0BO->getOperand(0), Op1,
7106                                                      Op0BO->getName());
7107             InsertNewInstBefore(YS, I); // (Y << C)
7108             Instruction *XM =
7109               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7110                                         V1->getName()+".mask");
7111             InsertNewInstBefore(XM, I); // X & (CC << C)
7112             
7113             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7114           }
7115         }
7116           
7117         // FALL THROUGH.
7118         case Instruction::Sub: {
7119           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7120           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7121               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7122             Instruction *YS = BinaryOperator::CreateShl(
7123                                                      Op0BO->getOperand(1), Op1,
7124                                                      Op0BO->getName());
7125             InsertNewInstBefore(YS, I); // (Y << C)
7126             Instruction *X =
7127               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7128                                      Op0BO->getOperand(0)->getName());
7129             InsertNewInstBefore(X, I);  // (X + (Y << C))
7130             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7131             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7132                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7133           }
7134           
7135           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7136           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7137               match(Op0BO->getOperand(0),
7138                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7139                           m_ConstantInt(CC))) && V2 == Op1 &&
7140               cast<BinaryOperator>(Op0BO->getOperand(0))
7141                   ->getOperand(0)->hasOneUse()) {
7142             Instruction *YS = BinaryOperator::CreateShl(
7143                                                      Op0BO->getOperand(1), Op1,
7144                                                      Op0BO->getName());
7145             InsertNewInstBefore(YS, I); // (Y << C)
7146             Instruction *XM =
7147               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7148                                         V1->getName()+".mask");
7149             InsertNewInstBefore(XM, I); // X & (CC << C)
7150             
7151             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7152           }
7153           
7154           break;
7155         }
7156       }
7157       
7158       
7159       // If the operand is an bitwise operator with a constant RHS, and the
7160       // shift is the only use, we can pull it out of the shift.
7161       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7162         bool isValid = true;     // Valid only for And, Or, Xor
7163         bool highBitSet = false; // Transform if high bit of constant set?
7164         
7165         switch (Op0BO->getOpcode()) {
7166           default: isValid = false; break;   // Do not perform transform!
7167           case Instruction::Add:
7168             isValid = isLeftShift;
7169             break;
7170           case Instruction::Or:
7171           case Instruction::Xor:
7172             highBitSet = false;
7173             break;
7174           case Instruction::And:
7175             highBitSet = true;
7176             break;
7177         }
7178         
7179         // If this is a signed shift right, and the high bit is modified
7180         // by the logical operation, do not perform the transformation.
7181         // The highBitSet boolean indicates the value of the high bit of
7182         // the constant which would cause it to be modified for this
7183         // operation.
7184         //
7185         if (isValid && I.getOpcode() == Instruction::AShr)
7186           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7187         
7188         if (isValid) {
7189           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7190           
7191           Instruction *NewShift =
7192             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7193           InsertNewInstBefore(NewShift, I);
7194           NewShift->takeName(Op0BO);
7195           
7196           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7197                                         NewRHS);
7198         }
7199       }
7200     }
7201   }
7202   
7203   // Find out if this is a shift of a shift by a constant.
7204   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7205   if (ShiftOp && !ShiftOp->isShift())
7206     ShiftOp = 0;
7207   
7208   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7209     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7210     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7211     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7212     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7213     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7214     Value *X = ShiftOp->getOperand(0);
7215     
7216     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7217     if (AmtSum > TypeBits)
7218       AmtSum = TypeBits;
7219     
7220     const IntegerType *Ty = cast<IntegerType>(I.getType());
7221     
7222     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7223     if (I.getOpcode() == ShiftOp->getOpcode()) {
7224       return BinaryOperator::Create(I.getOpcode(), X,
7225                                     ConstantInt::get(Ty, AmtSum));
7226     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7227                I.getOpcode() == Instruction::AShr) {
7228       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7229       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7230     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7231                I.getOpcode() == Instruction::LShr) {
7232       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7233       Instruction *Shift =
7234         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7235       InsertNewInstBefore(Shift, I);
7236
7237       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7238       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7239     }
7240     
7241     // Okay, if we get here, one shift must be left, and the other shift must be
7242     // right.  See if the amounts are equal.
7243     if (ShiftAmt1 == ShiftAmt2) {
7244       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7245       if (I.getOpcode() == Instruction::Shl) {
7246         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7247         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7248       }
7249       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7250       if (I.getOpcode() == Instruction::LShr) {
7251         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7252         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7253       }
7254       // We can simplify ((X << C) >>s C) into a trunc + sext.
7255       // NOTE: we could do this for any C, but that would make 'unusual' integer
7256       // types.  For now, just stick to ones well-supported by the code
7257       // generators.
7258       const Type *SExtType = 0;
7259       switch (Ty->getBitWidth() - ShiftAmt1) {
7260       case 1  :
7261       case 8  :
7262       case 16 :
7263       case 32 :
7264       case 64 :
7265       case 128:
7266         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7267         break;
7268       default: break;
7269       }
7270       if (SExtType) {
7271         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7272         InsertNewInstBefore(NewTrunc, I);
7273         return new SExtInst(NewTrunc, Ty);
7274       }
7275       // Otherwise, we can't handle it yet.
7276     } else if (ShiftAmt1 < ShiftAmt2) {
7277       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7278       
7279       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7280       if (I.getOpcode() == Instruction::Shl) {
7281         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7282                ShiftOp->getOpcode() == Instruction::AShr);
7283         Instruction *Shift =
7284           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7285         InsertNewInstBefore(Shift, I);
7286         
7287         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7288         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7289       }
7290       
7291       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7292       if (I.getOpcode() == Instruction::LShr) {
7293         assert(ShiftOp->getOpcode() == Instruction::Shl);
7294         Instruction *Shift =
7295           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7296         InsertNewInstBefore(Shift, I);
7297         
7298         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7299         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7300       }
7301       
7302       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7303     } else {
7304       assert(ShiftAmt2 < ShiftAmt1);
7305       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7306
7307       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7308       if (I.getOpcode() == Instruction::Shl) {
7309         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7310                ShiftOp->getOpcode() == Instruction::AShr);
7311         Instruction *Shift =
7312           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7313                                  ConstantInt::get(Ty, ShiftDiff));
7314         InsertNewInstBefore(Shift, I);
7315         
7316         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7317         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7318       }
7319       
7320       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7321       if (I.getOpcode() == Instruction::LShr) {
7322         assert(ShiftOp->getOpcode() == Instruction::Shl);
7323         Instruction *Shift =
7324           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7325         InsertNewInstBefore(Shift, I);
7326         
7327         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7328         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7329       }
7330       
7331       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7332     }
7333   }
7334   return 0;
7335 }
7336
7337
7338 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7339 /// expression.  If so, decompose it, returning some value X, such that Val is
7340 /// X*Scale+Offset.
7341 ///
7342 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7343                                         int &Offset) {
7344   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7345   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7346     Offset = CI->getZExtValue();
7347     Scale  = 0;
7348     return ConstantInt::get(Type::Int32Ty, 0);
7349   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7350     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7351       if (I->getOpcode() == Instruction::Shl) {
7352         // This is a value scaled by '1 << the shift amt'.
7353         Scale = 1U << RHS->getZExtValue();
7354         Offset = 0;
7355         return I->getOperand(0);
7356       } else if (I->getOpcode() == Instruction::Mul) {
7357         // This value is scaled by 'RHS'.
7358         Scale = RHS->getZExtValue();
7359         Offset = 0;
7360         return I->getOperand(0);
7361       } else if (I->getOpcode() == Instruction::Add) {
7362         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7363         // where C1 is divisible by C2.
7364         unsigned SubScale;
7365         Value *SubVal = 
7366           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7367         Offset += RHS->getZExtValue();
7368         Scale = SubScale;
7369         return SubVal;
7370       }
7371     }
7372   }
7373
7374   // Otherwise, we can't look past this.
7375   Scale = 1;
7376   Offset = 0;
7377   return Val;
7378 }
7379
7380
7381 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7382 /// try to eliminate the cast by moving the type information into the alloc.
7383 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7384                                                    AllocationInst &AI) {
7385   const PointerType *PTy = cast<PointerType>(CI.getType());
7386   
7387   // Remove any uses of AI that are dead.
7388   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7389   
7390   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7391     Instruction *User = cast<Instruction>(*UI++);
7392     if (isInstructionTriviallyDead(User)) {
7393       while (UI != E && *UI == User)
7394         ++UI; // If this instruction uses AI more than once, don't break UI.
7395       
7396       ++NumDeadInst;
7397       DOUT << "IC: DCE: " << *User;
7398       EraseInstFromFunction(*User);
7399     }
7400   }
7401   
7402   // Get the type really allocated and the type casted to.
7403   const Type *AllocElTy = AI.getAllocatedType();
7404   const Type *CastElTy = PTy->getElementType();
7405   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7406
7407   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7408   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7409   if (CastElTyAlign < AllocElTyAlign) return 0;
7410
7411   // If the allocation has multiple uses, only promote it if we are strictly
7412   // increasing the alignment of the resultant allocation.  If we keep it the
7413   // same, we open the door to infinite loops of various kinds.
7414   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7415
7416   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7417   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
7418   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7419
7420   // See if we can satisfy the modulus by pulling a scale out of the array
7421   // size argument.
7422   unsigned ArraySizeScale;
7423   int ArrayOffset;
7424   Value *NumElements = // See if the array size is a decomposable linear expr.
7425     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7426  
7427   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7428   // do the xform.
7429   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7430       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7431
7432   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7433   Value *Amt = 0;
7434   if (Scale == 1) {
7435     Amt = NumElements;
7436   } else {
7437     // If the allocation size is constant, form a constant mul expression
7438     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7439     if (isa<ConstantInt>(NumElements))
7440       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7441     // otherwise multiply the amount and the number of elements
7442     else if (Scale != 1) {
7443       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7444       Amt = InsertNewInstBefore(Tmp, AI);
7445     }
7446   }
7447   
7448   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7449     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7450     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7451     Amt = InsertNewInstBefore(Tmp, AI);
7452   }
7453   
7454   AllocationInst *New;
7455   if (isa<MallocInst>(AI))
7456     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7457   else
7458     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7459   InsertNewInstBefore(New, AI);
7460   New->takeName(&AI);
7461   
7462   // If the allocation has multiple uses, insert a cast and change all things
7463   // that used it to use the new cast.  This will also hack on CI, but it will
7464   // die soon.
7465   if (!AI.hasOneUse()) {
7466     AddUsesToWorkList(AI);
7467     // New is the allocation instruction, pointer typed. AI is the original
7468     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7469     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7470     InsertNewInstBefore(NewCast, AI);
7471     AI.replaceAllUsesWith(NewCast);
7472   }
7473   return ReplaceInstUsesWith(CI, New);
7474 }
7475
7476 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7477 /// and return it as type Ty without inserting any new casts and without
7478 /// changing the computed value.  This is used by code that tries to decide
7479 /// whether promoting or shrinking integer operations to wider or smaller types
7480 /// will allow us to eliminate a truncate or extend.
7481 ///
7482 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7483 /// extension operation if Ty is larger.
7484 ///
7485 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7486 /// should return true if trunc(V) can be computed by computing V in the smaller
7487 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7488 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7489 /// efficiently truncated.
7490 ///
7491 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7492 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7493 /// the final result.
7494 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7495                                               unsigned CastOpc,
7496                                               int &NumCastsRemoved) {
7497   // We can always evaluate constants in another type.
7498   if (isa<ConstantInt>(V))
7499     return true;
7500   
7501   Instruction *I = dyn_cast<Instruction>(V);
7502   if (!I) return false;
7503   
7504   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7505   
7506   // If this is an extension or truncate, we can often eliminate it.
7507   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7508     // If this is a cast from the destination type, we can trivially eliminate
7509     // it, and this will remove a cast overall.
7510     if (I->getOperand(0)->getType() == Ty) {
7511       // If the first operand is itself a cast, and is eliminable, do not count
7512       // this as an eliminable cast.  We would prefer to eliminate those two
7513       // casts first.
7514       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7515         ++NumCastsRemoved;
7516       return true;
7517     }
7518   }
7519
7520   // We can't extend or shrink something that has multiple uses: doing so would
7521   // require duplicating the instruction in general, which isn't profitable.
7522   if (!I->hasOneUse()) return false;
7523
7524   switch (I->getOpcode()) {
7525   case Instruction::Add:
7526   case Instruction::Sub:
7527   case Instruction::Mul:
7528   case Instruction::And:
7529   case Instruction::Or:
7530   case Instruction::Xor:
7531     // These operators can all arbitrarily be extended or truncated.
7532     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7533                                       NumCastsRemoved) &&
7534            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7535                                       NumCastsRemoved);
7536
7537   case Instruction::Shl:
7538     // If we are truncating the result of this SHL, and if it's a shift of a
7539     // constant amount, we can always perform a SHL in a smaller type.
7540     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7541       uint32_t BitWidth = Ty->getBitWidth();
7542       if (BitWidth < OrigTy->getBitWidth() && 
7543           CI->getLimitedValue(BitWidth) < BitWidth)
7544         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7545                                           NumCastsRemoved);
7546     }
7547     break;
7548   case Instruction::LShr:
7549     // If this is a truncate of a logical shr, we can truncate it to a smaller
7550     // lshr iff we know that the bits we would otherwise be shifting in are
7551     // already zeros.
7552     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7553       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7554       uint32_t BitWidth = Ty->getBitWidth();
7555       if (BitWidth < OrigBitWidth &&
7556           MaskedValueIsZero(I->getOperand(0),
7557             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7558           CI->getLimitedValue(BitWidth) < BitWidth) {
7559         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7560                                           NumCastsRemoved);
7561       }
7562     }
7563     break;
7564   case Instruction::ZExt:
7565   case Instruction::SExt:
7566   case Instruction::Trunc:
7567     // If this is the same kind of case as our original (e.g. zext+zext), we
7568     // can safely replace it.  Note that replacing it does not reduce the number
7569     // of casts in the input.
7570     if (I->getOpcode() == CastOpc)
7571       return true;
7572     break;
7573   case Instruction::Select: {
7574     SelectInst *SI = cast<SelectInst>(I);
7575     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7576                                       NumCastsRemoved) &&
7577            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7578                                       NumCastsRemoved);
7579   }
7580   case Instruction::PHI: {
7581     // We can change a phi if we can change all operands.
7582     PHINode *PN = cast<PHINode>(I);
7583     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7584       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7585                                       NumCastsRemoved))
7586         return false;
7587     return true;
7588   }
7589   default:
7590     // TODO: Can handle more cases here.
7591     break;
7592   }
7593   
7594   return false;
7595 }
7596
7597 /// EvaluateInDifferentType - Given an expression that 
7598 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7599 /// evaluate the expression.
7600 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7601                                              bool isSigned) {
7602   if (Constant *C = dyn_cast<Constant>(V))
7603     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7604
7605   // Otherwise, it must be an instruction.
7606   Instruction *I = cast<Instruction>(V);
7607   Instruction *Res = 0;
7608   switch (I->getOpcode()) {
7609   case Instruction::Add:
7610   case Instruction::Sub:
7611   case Instruction::Mul:
7612   case Instruction::And:
7613   case Instruction::Or:
7614   case Instruction::Xor:
7615   case Instruction::AShr:
7616   case Instruction::LShr:
7617   case Instruction::Shl: {
7618     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7619     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7620     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7621                                  LHS, RHS);
7622     break;
7623   }    
7624   case Instruction::Trunc:
7625   case Instruction::ZExt:
7626   case Instruction::SExt:
7627     // If the source type of the cast is the type we're trying for then we can
7628     // just return the source.  There's no need to insert it because it is not
7629     // new.
7630     if (I->getOperand(0)->getType() == Ty)
7631       return I->getOperand(0);
7632     
7633     // Otherwise, must be the same type of cast, so just reinsert a new one.
7634     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7635                            Ty);
7636     break;
7637   case Instruction::Select: {
7638     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7639     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7640     Res = SelectInst::Create(I->getOperand(0), True, False);
7641     break;
7642   }
7643   case Instruction::PHI: {
7644     PHINode *OPN = cast<PHINode>(I);
7645     PHINode *NPN = PHINode::Create(Ty);
7646     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7647       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7648       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7649     }
7650     Res = NPN;
7651     break;
7652   }
7653   default: 
7654     // TODO: Can handle more cases here.
7655     assert(0 && "Unreachable!");
7656     break;
7657   }
7658   
7659   Res->takeName(I);
7660   return InsertNewInstBefore(Res, *I);
7661 }
7662
7663 /// @brief Implement the transforms common to all CastInst visitors.
7664 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7665   Value *Src = CI.getOperand(0);
7666
7667   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7668   // eliminate it now.
7669   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7670     if (Instruction::CastOps opc = 
7671         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7672       // The first cast (CSrc) is eliminable so we need to fix up or replace
7673       // the second cast (CI). CSrc will then have a good chance of being dead.
7674       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7675     }
7676   }
7677
7678   // If we are casting a select then fold the cast into the select
7679   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7680     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7681       return NV;
7682
7683   // If we are casting a PHI then fold the cast into the PHI
7684   if (isa<PHINode>(Src))
7685     if (Instruction *NV = FoldOpIntoPhi(CI))
7686       return NV;
7687   
7688   return 0;
7689 }
7690
7691 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7692 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7693   Value *Src = CI.getOperand(0);
7694   
7695   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7696     // If casting the result of a getelementptr instruction with no offset, turn
7697     // this into a cast of the original pointer!
7698     if (GEP->hasAllZeroIndices()) {
7699       // Changing the cast operand is usually not a good idea but it is safe
7700       // here because the pointer operand is being replaced with another 
7701       // pointer operand so the opcode doesn't need to change.
7702       AddToWorkList(GEP);
7703       CI.setOperand(0, GEP->getOperand(0));
7704       return &CI;
7705     }
7706     
7707     // If the GEP has a single use, and the base pointer is a bitcast, and the
7708     // GEP computes a constant offset, see if we can convert these three
7709     // instructions into fewer.  This typically happens with unions and other
7710     // non-type-safe code.
7711     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7712       if (GEP->hasAllConstantIndices()) {
7713         // We are guaranteed to get a constant from EmitGEPOffset.
7714         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7715         int64_t Offset = OffsetV->getSExtValue();
7716         
7717         // Get the base pointer input of the bitcast, and the type it points to.
7718         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7719         const Type *GEPIdxTy =
7720           cast<PointerType>(OrigBase->getType())->getElementType();
7721         if (GEPIdxTy->isSized()) {
7722           SmallVector<Value*, 8> NewIndices;
7723           
7724           // Start with the index over the outer type.  Note that the type size
7725           // might be zero (even if the offset isn't zero) if the indexed type
7726           // is something like [0 x {int, int}]
7727           const Type *IntPtrTy = TD->getIntPtrType();
7728           int64_t FirstIdx = 0;
7729           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7730             FirstIdx = Offset/TySize;
7731             Offset %= TySize;
7732           
7733             // Handle silly modulus not returning values values [0..TySize).
7734             if (Offset < 0) {
7735               --FirstIdx;
7736               Offset += TySize;
7737               assert(Offset >= 0);
7738             }
7739             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7740           }
7741           
7742           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7743
7744           // Index into the types.  If we fail, set OrigBase to null.
7745           while (Offset) {
7746             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7747               const StructLayout *SL = TD->getStructLayout(STy);
7748               if (Offset < (int64_t)SL->getSizeInBytes()) {
7749                 unsigned Elt = SL->getElementContainingOffset(Offset);
7750                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7751               
7752                 Offset -= SL->getElementOffset(Elt);
7753                 GEPIdxTy = STy->getElementType(Elt);
7754               } else {
7755                 // Otherwise, we can't index into this, bail out.
7756                 Offset = 0;
7757                 OrigBase = 0;
7758               }
7759             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7760               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7761               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7762                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7763                 Offset %= EltSize;
7764               } else {
7765                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7766               }
7767               GEPIdxTy = STy->getElementType();
7768             } else {
7769               // Otherwise, we can't index into this, bail out.
7770               Offset = 0;
7771               OrigBase = 0;
7772             }
7773           }
7774           if (OrigBase) {
7775             // If we were able to index down into an element, create the GEP
7776             // and bitcast the result.  This eliminates one bitcast, potentially
7777             // two.
7778             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7779                                                           NewIndices.begin(),
7780                                                           NewIndices.end(), "");
7781             InsertNewInstBefore(NGEP, CI);
7782             NGEP->takeName(GEP);
7783             
7784             if (isa<BitCastInst>(CI))
7785               return new BitCastInst(NGEP, CI.getType());
7786             assert(isa<PtrToIntInst>(CI));
7787             return new PtrToIntInst(NGEP, CI.getType());
7788           }
7789         }
7790       }      
7791     }
7792   }
7793     
7794   return commonCastTransforms(CI);
7795 }
7796
7797
7798
7799 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7800 /// integer types. This function implements the common transforms for all those
7801 /// cases.
7802 /// @brief Implement the transforms common to CastInst with integer operands
7803 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7804   if (Instruction *Result = commonCastTransforms(CI))
7805     return Result;
7806
7807   Value *Src = CI.getOperand(0);
7808   const Type *SrcTy = Src->getType();
7809   const Type *DestTy = CI.getType();
7810   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7811   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7812
7813   // See if we can simplify any instructions used by the LHS whose sole 
7814   // purpose is to compute bits we don't care about.
7815   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7816   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7817                            KnownZero, KnownOne))
7818     return &CI;
7819
7820   // If the source isn't an instruction or has more than one use then we
7821   // can't do anything more. 
7822   Instruction *SrcI = dyn_cast<Instruction>(Src);
7823   if (!SrcI || !Src->hasOneUse())
7824     return 0;
7825
7826   // Attempt to propagate the cast into the instruction for int->int casts.
7827   int NumCastsRemoved = 0;
7828   if (!isa<BitCastInst>(CI) &&
7829       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7830                                  CI.getOpcode(), NumCastsRemoved)) {
7831     // If this cast is a truncate, evaluting in a different type always
7832     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7833     // we need to do an AND to maintain the clear top-part of the computation,
7834     // so we require that the input have eliminated at least one cast.  If this
7835     // is a sign extension, we insert two new casts (to do the extension) so we
7836     // require that two casts have been eliminated.
7837     bool DoXForm;
7838     switch (CI.getOpcode()) {
7839     default:
7840       // All the others use floating point so we shouldn't actually 
7841       // get here because of the check above.
7842       assert(0 && "Unknown cast type");
7843     case Instruction::Trunc:
7844       DoXForm = true;
7845       break;
7846     case Instruction::ZExt:
7847       DoXForm = NumCastsRemoved >= 1;
7848       break;
7849     case Instruction::SExt:
7850       DoXForm = NumCastsRemoved >= 2;
7851       break;
7852     }
7853     
7854     if (DoXForm) {
7855       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7856                                            CI.getOpcode() == Instruction::SExt);
7857       assert(Res->getType() == DestTy);
7858       switch (CI.getOpcode()) {
7859       default: assert(0 && "Unknown cast type!");
7860       case Instruction::Trunc:
7861       case Instruction::BitCast:
7862         // Just replace this cast with the result.
7863         return ReplaceInstUsesWith(CI, Res);
7864       case Instruction::ZExt: {
7865         // We need to emit an AND to clear the high bits.
7866         assert(SrcBitSize < DestBitSize && "Not a zext?");
7867         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7868                                                             SrcBitSize));
7869         return BinaryOperator::CreateAnd(Res, C);
7870       }
7871       case Instruction::SExt:
7872         // We need to emit a cast to truncate, then a cast to sext.
7873         return CastInst::Create(Instruction::SExt,
7874             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7875                              CI), DestTy);
7876       }
7877     }
7878   }
7879   
7880   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7881   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7882
7883   switch (SrcI->getOpcode()) {
7884   case Instruction::Add:
7885   case Instruction::Mul:
7886   case Instruction::And:
7887   case Instruction::Or:
7888   case Instruction::Xor:
7889     // If we are discarding information, rewrite.
7890     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7891       // Don't insert two casts if they cannot be eliminated.  We allow 
7892       // two casts to be inserted if the sizes are the same.  This could 
7893       // only be converting signedness, which is a noop.
7894       if (DestBitSize == SrcBitSize || 
7895           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7896           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7897         Instruction::CastOps opcode = CI.getOpcode();
7898         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7899         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
7900         return BinaryOperator::Create(
7901             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7902       }
7903     }
7904
7905     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7906     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7907         SrcI->getOpcode() == Instruction::Xor &&
7908         Op1 == ConstantInt::getTrue() &&
7909         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7910       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
7911       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7912     }
7913     break;
7914   case Instruction::SDiv:
7915   case Instruction::UDiv:
7916   case Instruction::SRem:
7917   case Instruction::URem:
7918     // If we are just changing the sign, rewrite.
7919     if (DestBitSize == SrcBitSize) {
7920       // Don't insert two casts if they cannot be eliminated.  We allow 
7921       // two casts to be inserted if the sizes are the same.  This could 
7922       // only be converting signedness, which is a noop.
7923       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7924           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7925         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
7926                                        Op0, DestTy, *SrcI);
7927         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
7928                                        Op1, DestTy, *SrcI);
7929         return BinaryOperator::Create(
7930           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7931       }
7932     }
7933     break;
7934
7935   case Instruction::Shl:
7936     // Allow changing the sign of the source operand.  Do not allow 
7937     // changing the size of the shift, UNLESS the shift amount is a 
7938     // constant.  We must not change variable sized shifts to a smaller 
7939     // size, because it is undefined to shift more bits out than exist 
7940     // in the value.
7941     if (DestBitSize == SrcBitSize ||
7942         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7943       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7944           Instruction::BitCast : Instruction::Trunc);
7945       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7946       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
7947       return BinaryOperator::CreateShl(Op0c, Op1c);
7948     }
7949     break;
7950   case Instruction::AShr:
7951     // If this is a signed shr, and if all bits shifted in are about to be
7952     // truncated off, turn it into an unsigned shr to allow greater
7953     // simplifications.
7954     if (DestBitSize < SrcBitSize &&
7955         isa<ConstantInt>(Op1)) {
7956       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7957       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7958         // Insert the new logical shift right.
7959         return BinaryOperator::CreateLShr(Op0, Op1);
7960       }
7961     }
7962     break;
7963   }
7964   return 0;
7965 }
7966
7967 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7968   if (Instruction *Result = commonIntCastTransforms(CI))
7969     return Result;
7970   
7971   Value *Src = CI.getOperand(0);
7972   const Type *Ty = CI.getType();
7973   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7974   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7975   
7976   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7977     switch (SrcI->getOpcode()) {
7978     default: break;
7979     case Instruction::LShr:
7980       // We can shrink lshr to something smaller if we know the bits shifted in
7981       // are already zeros.
7982       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7983         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7984         
7985         // Get a mask for the bits shifting in.
7986         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7987         Value* SrcIOp0 = SrcI->getOperand(0);
7988         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7989           if (ShAmt >= DestBitWidth)        // All zeros.
7990             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7991
7992           // Okay, we can shrink this.  Truncate the input, then return a new
7993           // shift.
7994           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7995           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7996                                        Ty, CI);
7997           return BinaryOperator::CreateLShr(V1, V2);
7998         }
7999       } else {     // This is a variable shr.
8000         
8001         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
8002         // more LLVM instructions, but allows '1 << Y' to be hoisted if
8003         // loop-invariant and CSE'd.
8004         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
8005           Value *One = ConstantInt::get(SrcI->getType(), 1);
8006
8007           Value *V = InsertNewInstBefore(
8008               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
8009                                      "tmp"), CI);
8010           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
8011                                                             SrcI->getOperand(0),
8012                                                             "tmp"), CI);
8013           Value *Zero = Constant::getNullValue(V->getType());
8014           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
8015         }
8016       }
8017       break;
8018     }
8019   }
8020   
8021   return 0;
8022 }
8023
8024 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8025 /// in order to eliminate the icmp.
8026 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8027                                              bool DoXform) {
8028   // If we are just checking for a icmp eq of a single bit and zext'ing it
8029   // to an integer, then shift the bit to the appropriate place and then
8030   // cast to integer to avoid the comparison.
8031   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8032     const APInt &Op1CV = Op1C->getValue();
8033       
8034     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8035     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8036     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8037         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8038       if (!DoXform) return ICI;
8039
8040       Value *In = ICI->getOperand(0);
8041       Value *Sh = ConstantInt::get(In->getType(),
8042                                    In->getType()->getPrimitiveSizeInBits()-1);
8043       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8044                                                         In->getName()+".lobit"),
8045                                CI);
8046       if (In->getType() != CI.getType())
8047         In = CastInst::CreateIntegerCast(In, CI.getType(),
8048                                          false/*ZExt*/, "tmp", &CI);
8049
8050       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8051         Constant *One = ConstantInt::get(In->getType(), 1);
8052         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8053                                                          In->getName()+".not"),
8054                                  CI);
8055       }
8056
8057       return ReplaceInstUsesWith(CI, In);
8058     }
8059       
8060       
8061       
8062     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8063     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8064     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8065     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8066     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8067     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8068     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8069     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8070     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8071         // This only works for EQ and NE
8072         ICI->isEquality()) {
8073       // If Op1C some other power of two, convert:
8074       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8075       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8076       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8077       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8078         
8079       APInt KnownZeroMask(~KnownZero);
8080       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8081         if (!DoXform) return ICI;
8082
8083         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8084         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8085           // (X&4) == 2 --> false
8086           // (X&4) != 2 --> true
8087           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8088           Res = ConstantExpr::getZExt(Res, CI.getType());
8089           return ReplaceInstUsesWith(CI, Res);
8090         }
8091           
8092         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8093         Value *In = ICI->getOperand(0);
8094         if (ShiftAmt) {
8095           // Perform a logical shr by shiftamt.
8096           // Insert the shift to put the result in the low bit.
8097           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8098                                   ConstantInt::get(In->getType(), ShiftAmt),
8099                                                    In->getName()+".lobit"), CI);
8100         }
8101           
8102         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8103           Constant *One = ConstantInt::get(In->getType(), 1);
8104           In = BinaryOperator::CreateXor(In, One, "tmp");
8105           InsertNewInstBefore(cast<Instruction>(In), CI);
8106         }
8107           
8108         if (CI.getType() == In->getType())
8109           return ReplaceInstUsesWith(CI, In);
8110         else
8111           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8112       }
8113     }
8114   }
8115
8116   return 0;
8117 }
8118
8119 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8120   // If one of the common conversion will work ..
8121   if (Instruction *Result = commonIntCastTransforms(CI))
8122     return Result;
8123
8124   Value *Src = CI.getOperand(0);
8125
8126   // If this is a cast of a cast
8127   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8128     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8129     // types and if the sizes are just right we can convert this into a logical
8130     // 'and' which will be much cheaper than the pair of casts.
8131     if (isa<TruncInst>(CSrc)) {
8132       // Get the sizes of the types involved
8133       Value *A = CSrc->getOperand(0);
8134       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8135       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8136       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8137       // If we're actually extending zero bits and the trunc is a no-op
8138       if (MidSize < DstSize && SrcSize == DstSize) {
8139         // Replace both of the casts with an And of the type mask.
8140         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8141         Constant *AndConst = ConstantInt::get(AndValue);
8142         Instruction *And = 
8143           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8144         // Unfortunately, if the type changed, we need to cast it back.
8145         if (And->getType() != CI.getType()) {
8146           And->setName(CSrc->getName()+".mask");
8147           InsertNewInstBefore(And, CI);
8148           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8149         }
8150         return And;
8151       }
8152     }
8153   }
8154
8155   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8156     return transformZExtICmp(ICI, CI);
8157
8158   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8159   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8160     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8161     // of the (zext icmp) will be transformed.
8162     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8163     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8164     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8165         (transformZExtICmp(LHS, CI, false) ||
8166          transformZExtICmp(RHS, CI, false))) {
8167       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8168       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8169       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8170     }
8171   }
8172
8173   return 0;
8174 }
8175
8176 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8177   if (Instruction *I = commonIntCastTransforms(CI))
8178     return I;
8179   
8180   Value *Src = CI.getOperand(0);
8181   
8182   // Canonicalize sign-extend from i1 to a select.
8183   if (Src->getType() == Type::Int1Ty)
8184     return SelectInst::Create(Src,
8185                               ConstantInt::getAllOnesValue(CI.getType()),
8186                               Constant::getNullValue(CI.getType()));
8187
8188   // See if the value being truncated is already sign extended.  If so, just
8189   // eliminate the trunc/sext pair.
8190   if (getOpcode(Src) == Instruction::Trunc) {
8191     Value *Op = cast<User>(Src)->getOperand(0);
8192     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8193     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8194     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8195     unsigned NumSignBits = ComputeNumSignBits(Op);
8196
8197     if (OpBits == DestBits) {
8198       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8199       // bits, it is already ready.
8200       if (NumSignBits > DestBits-MidBits)
8201         return ReplaceInstUsesWith(CI, Op);
8202     } else if (OpBits < DestBits) {
8203       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8204       // bits, just sext from i32.
8205       if (NumSignBits > OpBits-MidBits)
8206         return new SExtInst(Op, CI.getType(), "tmp");
8207     } else {
8208       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8209       // bits, just truncate to i32.
8210       if (NumSignBits > OpBits-MidBits)
8211         return new TruncInst(Op, CI.getType(), "tmp");
8212     }
8213   }
8214
8215   // If the input is a shl/ashr pair of a same constant, then this is a sign
8216   // extension from a smaller value.  If we could trust arbitrary bitwidth
8217   // integers, we could turn this into a truncate to the smaller bit and then
8218   // use a sext for the whole extension.  Since we don't, look deeper and check
8219   // for a truncate.  If the source and dest are the same type, eliminate the
8220   // trunc and extend and just do shifts.  For example, turn:
8221   //   %a = trunc i32 %i to i8
8222   //   %b = shl i8 %a, 6
8223   //   %c = ashr i8 %b, 6
8224   //   %d = sext i8 %c to i32
8225   // into:
8226   //   %a = shl i32 %i, 30
8227   //   %d = ashr i32 %a, 30
8228   Value *A = 0;
8229   ConstantInt *BA = 0, *CA = 0;
8230   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8231                         m_ConstantInt(CA))) &&
8232       BA == CA && isa<TruncInst>(A)) {
8233     Value *I = cast<TruncInst>(A)->getOperand(0);
8234     if (I->getType() == CI.getType()) {
8235       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8236       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8237       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8238       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8239       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8240                                                         CI.getName()), CI);
8241       return BinaryOperator::CreateAShr(I, ShAmtV);
8242     }
8243   }
8244   
8245   return 0;
8246 }
8247
8248 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8249 /// in the specified FP type without changing its value.
8250 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8251   bool losesInfo;
8252   APFloat F = CFP->getValueAPF();
8253   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8254   if (!losesInfo)
8255     return ConstantFP::get(F);
8256   return 0;
8257 }
8258
8259 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8260 /// through it until we get the source value.
8261 static Value *LookThroughFPExtensions(Value *V) {
8262   if (Instruction *I = dyn_cast<Instruction>(V))
8263     if (I->getOpcode() == Instruction::FPExt)
8264       return LookThroughFPExtensions(I->getOperand(0));
8265   
8266   // If this value is a constant, return the constant in the smallest FP type
8267   // that can accurately represent it.  This allows us to turn
8268   // (float)((double)X+2.0) into x+2.0f.
8269   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8270     if (CFP->getType() == Type::PPC_FP128Ty)
8271       return V;  // No constant folding of this.
8272     // See if the value can be truncated to float and then reextended.
8273     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8274       return V;
8275     if (CFP->getType() == Type::DoubleTy)
8276       return V;  // Won't shrink.
8277     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8278       return V;
8279     // Don't try to shrink to various long double types.
8280   }
8281   
8282   return V;
8283 }
8284
8285 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8286   if (Instruction *I = commonCastTransforms(CI))
8287     return I;
8288   
8289   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8290   // smaller than the destination type, we can eliminate the truncate by doing
8291   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8292   // many builtins (sqrt, etc).
8293   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8294   if (OpI && OpI->hasOneUse()) {
8295     switch (OpI->getOpcode()) {
8296     default: break;
8297     case Instruction::Add:
8298     case Instruction::Sub:
8299     case Instruction::Mul:
8300     case Instruction::FDiv:
8301     case Instruction::FRem:
8302       const Type *SrcTy = OpI->getType();
8303       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8304       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8305       if (LHSTrunc->getType() != SrcTy && 
8306           RHSTrunc->getType() != SrcTy) {
8307         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8308         // If the source types were both smaller than the destination type of
8309         // the cast, do this xform.
8310         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8311             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8312           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8313                                       CI.getType(), CI);
8314           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8315                                       CI.getType(), CI);
8316           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8317         }
8318       }
8319       break;  
8320     }
8321   }
8322   return 0;
8323 }
8324
8325 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8326   return commonCastTransforms(CI);
8327 }
8328
8329 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8330   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8331   if (OpI == 0)
8332     return commonCastTransforms(FI);
8333
8334   // fptoui(uitofp(X)) --> X
8335   // fptoui(sitofp(X)) --> X
8336   // This is safe if the intermediate type has enough bits in its mantissa to
8337   // accurately represent all values of X.  For example, do not do this with
8338   // i64->float->i64.  This is also safe for sitofp case, because any negative
8339   // 'X' value would cause an undefined result for the fptoui. 
8340   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8341       OpI->getOperand(0)->getType() == FI.getType() &&
8342       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8343                     OpI->getType()->getFPMantissaWidth())
8344     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8345
8346   return commonCastTransforms(FI);
8347 }
8348
8349 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8350   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8351   if (OpI == 0)
8352     return commonCastTransforms(FI);
8353   
8354   // fptosi(sitofp(X)) --> X
8355   // fptosi(uitofp(X)) --> X
8356   // This is safe if the intermediate type has enough bits in its mantissa to
8357   // accurately represent all values of X.  For example, do not do this with
8358   // i64->float->i64.  This is also safe for sitofp case, because any negative
8359   // 'X' value would cause an undefined result for the fptoui. 
8360   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8361       OpI->getOperand(0)->getType() == FI.getType() &&
8362       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8363                     OpI->getType()->getFPMantissaWidth())
8364     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8365   
8366   return commonCastTransforms(FI);
8367 }
8368
8369 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8370   return commonCastTransforms(CI);
8371 }
8372
8373 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8374   return commonCastTransforms(CI);
8375 }
8376
8377 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8378   return commonPointerCastTransforms(CI);
8379 }
8380
8381 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8382   if (Instruction *I = commonCastTransforms(CI))
8383     return I;
8384   
8385   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8386   if (!DestPointee->isSized()) return 0;
8387
8388   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8389   ConstantInt *Cst;
8390   Value *X;
8391   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8392                                     m_ConstantInt(Cst)))) {
8393     // If the source and destination operands have the same type, see if this
8394     // is a single-index GEP.
8395     if (X->getType() == CI.getType()) {
8396       // Get the size of the pointee type.
8397       uint64_t Size = TD->getABITypeSize(DestPointee);
8398
8399       // Convert the constant to intptr type.
8400       APInt Offset = Cst->getValue();
8401       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8402
8403       // If Offset is evenly divisible by Size, we can do this xform.
8404       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8405         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8406         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8407       }
8408     }
8409     // TODO: Could handle other cases, e.g. where add is indexing into field of
8410     // struct etc.
8411   } else if (CI.getOperand(0)->hasOneUse() &&
8412              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8413     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8414     // "inttoptr+GEP" instead of "add+intptr".
8415     
8416     // Get the size of the pointee type.
8417     uint64_t Size = TD->getABITypeSize(DestPointee);
8418     
8419     // Convert the constant to intptr type.
8420     APInt Offset = Cst->getValue();
8421     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8422     
8423     // If Offset is evenly divisible by Size, we can do this xform.
8424     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8425       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8426       
8427       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8428                                                             "tmp"), CI);
8429       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8430     }
8431   }
8432   return 0;
8433 }
8434
8435 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8436   // If the operands are integer typed then apply the integer transforms,
8437   // otherwise just apply the common ones.
8438   Value *Src = CI.getOperand(0);
8439   const Type *SrcTy = Src->getType();
8440   const Type *DestTy = CI.getType();
8441
8442   if (SrcTy->isInteger() && DestTy->isInteger()) {
8443     if (Instruction *Result = commonIntCastTransforms(CI))
8444       return Result;
8445   } else if (isa<PointerType>(SrcTy)) {
8446     if (Instruction *I = commonPointerCastTransforms(CI))
8447       return I;
8448   } else {
8449     if (Instruction *Result = commonCastTransforms(CI))
8450       return Result;
8451   }
8452
8453
8454   // Get rid of casts from one type to the same type. These are useless and can
8455   // be replaced by the operand.
8456   if (DestTy == Src->getType())
8457     return ReplaceInstUsesWith(CI, Src);
8458
8459   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8460     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8461     const Type *DstElTy = DstPTy->getElementType();
8462     const Type *SrcElTy = SrcPTy->getElementType();
8463     
8464     // If the address spaces don't match, don't eliminate the bitcast, which is
8465     // required for changing types.
8466     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8467       return 0;
8468     
8469     // If we are casting a malloc or alloca to a pointer to a type of the same
8470     // size, rewrite the allocation instruction to allocate the "right" type.
8471     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8472       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8473         return V;
8474     
8475     // If the source and destination are pointers, and this cast is equivalent
8476     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8477     // This can enhance SROA and other transforms that want type-safe pointers.
8478     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8479     unsigned NumZeros = 0;
8480     while (SrcElTy != DstElTy && 
8481            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8482            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8483       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8484       ++NumZeros;
8485     }
8486
8487     // If we found a path from the src to dest, create the getelementptr now.
8488     if (SrcElTy == DstElTy) {
8489       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8490       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8491                                        ((Instruction*) NULL));
8492     }
8493   }
8494
8495   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8496     if (SVI->hasOneUse()) {
8497       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8498       // a bitconvert to a vector with the same # elts.
8499       if (isa<VectorType>(DestTy) && 
8500           cast<VectorType>(DestTy)->getNumElements() ==
8501                 SVI->getType()->getNumElements() &&
8502           SVI->getType()->getNumElements() ==
8503             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8504         CastInst *Tmp;
8505         // If either of the operands is a cast from CI.getType(), then
8506         // evaluating the shuffle in the casted destination's type will allow
8507         // us to eliminate at least one cast.
8508         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8509              Tmp->getOperand(0)->getType() == DestTy) ||
8510             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8511              Tmp->getOperand(0)->getType() == DestTy)) {
8512           Value *LHS = InsertCastBefore(Instruction::BitCast,
8513                                         SVI->getOperand(0), DestTy, CI);
8514           Value *RHS = InsertCastBefore(Instruction::BitCast,
8515                                         SVI->getOperand(1), DestTy, CI);
8516           // Return a new shuffle vector.  Use the same element ID's, as we
8517           // know the vector types match #elts.
8518           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8519         }
8520       }
8521     }
8522   }
8523   return 0;
8524 }
8525
8526 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8527 ///   %C = or %A, %B
8528 ///   %D = select %cond, %C, %A
8529 /// into:
8530 ///   %C = select %cond, %B, 0
8531 ///   %D = or %A, %C
8532 ///
8533 /// Assuming that the specified instruction is an operand to the select, return
8534 /// a bitmask indicating which operands of this instruction are foldable if they
8535 /// equal the other incoming value of the select.
8536 ///
8537 static unsigned GetSelectFoldableOperands(Instruction *I) {
8538   switch (I->getOpcode()) {
8539   case Instruction::Add:
8540   case Instruction::Mul:
8541   case Instruction::And:
8542   case Instruction::Or:
8543   case Instruction::Xor:
8544     return 3;              // Can fold through either operand.
8545   case Instruction::Sub:   // Can only fold on the amount subtracted.
8546   case Instruction::Shl:   // Can only fold on the shift amount.
8547   case Instruction::LShr:
8548   case Instruction::AShr:
8549     return 1;
8550   default:
8551     return 0;              // Cannot fold
8552   }
8553 }
8554
8555 /// GetSelectFoldableConstant - For the same transformation as the previous
8556 /// function, return the identity constant that goes into the select.
8557 static Constant *GetSelectFoldableConstant(Instruction *I) {
8558   switch (I->getOpcode()) {
8559   default: assert(0 && "This cannot happen!"); abort();
8560   case Instruction::Add:
8561   case Instruction::Sub:
8562   case Instruction::Or:
8563   case Instruction::Xor:
8564   case Instruction::Shl:
8565   case Instruction::LShr:
8566   case Instruction::AShr:
8567     return Constant::getNullValue(I->getType());
8568   case Instruction::And:
8569     return Constant::getAllOnesValue(I->getType());
8570   case Instruction::Mul:
8571     return ConstantInt::get(I->getType(), 1);
8572   }
8573 }
8574
8575 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8576 /// have the same opcode and only one use each.  Try to simplify this.
8577 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8578                                           Instruction *FI) {
8579   if (TI->getNumOperands() == 1) {
8580     // If this is a non-volatile load or a cast from the same type,
8581     // merge.
8582     if (TI->isCast()) {
8583       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8584         return 0;
8585     } else {
8586       return 0;  // unknown unary op.
8587     }
8588
8589     // Fold this by inserting a select from the input values.
8590     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8591                                            FI->getOperand(0), SI.getName()+".v");
8592     InsertNewInstBefore(NewSI, SI);
8593     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8594                             TI->getType());
8595   }
8596
8597   // Only handle binary operators here.
8598   if (!isa<BinaryOperator>(TI))
8599     return 0;
8600
8601   // Figure out if the operations have any operands in common.
8602   Value *MatchOp, *OtherOpT, *OtherOpF;
8603   bool MatchIsOpZero;
8604   if (TI->getOperand(0) == FI->getOperand(0)) {
8605     MatchOp  = TI->getOperand(0);
8606     OtherOpT = TI->getOperand(1);
8607     OtherOpF = FI->getOperand(1);
8608     MatchIsOpZero = true;
8609   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8610     MatchOp  = TI->getOperand(1);
8611     OtherOpT = TI->getOperand(0);
8612     OtherOpF = FI->getOperand(0);
8613     MatchIsOpZero = false;
8614   } else if (!TI->isCommutative()) {
8615     return 0;
8616   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8617     MatchOp  = TI->getOperand(0);
8618     OtherOpT = TI->getOperand(1);
8619     OtherOpF = FI->getOperand(0);
8620     MatchIsOpZero = true;
8621   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8622     MatchOp  = TI->getOperand(1);
8623     OtherOpT = TI->getOperand(0);
8624     OtherOpF = FI->getOperand(1);
8625     MatchIsOpZero = true;
8626   } else {
8627     return 0;
8628   }
8629
8630   // If we reach here, they do have operations in common.
8631   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8632                                          OtherOpF, SI.getName()+".v");
8633   InsertNewInstBefore(NewSI, SI);
8634
8635   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8636     if (MatchIsOpZero)
8637       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8638     else
8639       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8640   }
8641   assert(0 && "Shouldn't get here");
8642   return 0;
8643 }
8644
8645 /// visitSelectInstWithICmp - Visit a SelectInst that has an
8646 /// ICmpInst as its first operand.
8647 ///
8648 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8649                                                    ICmpInst *ICI) {
8650   bool Changed = false;
8651   ICmpInst::Predicate Pred = ICI->getPredicate();
8652   Value *CmpLHS = ICI->getOperand(0);
8653   Value *CmpRHS = ICI->getOperand(1);
8654   Value *TrueVal = SI.getTrueValue();
8655   Value *FalseVal = SI.getFalseValue();
8656
8657   // Check cases where the comparison is with a constant that
8658   // can be adjusted to fit the min/max idiom. We may edit ICI in
8659   // place here, so make sure the select is the only user.
8660   if (ICI->hasOneUse())
8661     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
8662       switch (Pred) {
8663       default: break;
8664       case ICmpInst::ICMP_ULT:
8665       case ICmpInst::ICMP_SLT: {
8666         // X < MIN ? T : F  -->  F
8667         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8668           return ReplaceInstUsesWith(SI, FalseVal);
8669         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
8670         Constant *AdjustedRHS = SubOne(CI);
8671         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8672             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8673           Pred = ICmpInst::getSwappedPredicate(Pred);
8674           CmpRHS = AdjustedRHS;
8675           std::swap(FalseVal, TrueVal);
8676           ICI->setPredicate(Pred);
8677           ICI->setOperand(1, CmpRHS);
8678           SI.setOperand(1, TrueVal);
8679           SI.setOperand(2, FalseVal);
8680           Changed = true;
8681         }
8682         break;
8683       }
8684       case ICmpInst::ICMP_UGT:
8685       case ICmpInst::ICMP_SGT: {
8686         // X > MAX ? T : F  -->  F
8687         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8688           return ReplaceInstUsesWith(SI, FalseVal);
8689         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
8690         Constant *AdjustedRHS = AddOne(CI);
8691         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8692             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8693           Pred = ICmpInst::getSwappedPredicate(Pred);
8694           CmpRHS = AdjustedRHS;
8695           std::swap(FalseVal, TrueVal);
8696           ICI->setPredicate(Pred);
8697           ICI->setOperand(1, CmpRHS);
8698           SI.setOperand(1, TrueVal);
8699           SI.setOperand(2, FalseVal);
8700           Changed = true;
8701         }
8702         break;
8703       }
8704       }
8705
8706       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
8707       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
8708       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
8709       if (match(TrueVal, m_ConstantInt(-1)) &&
8710           match(FalseVal, m_ConstantInt(0)))
8711         Pred = ICI->getPredicate();
8712       else if (match(TrueVal, m_ConstantInt(0)) &&
8713                match(FalseVal, m_ConstantInt(-1)))
8714         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8715       
8716       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8717         // If we are just checking for a icmp eq of a single bit and zext'ing it
8718         // to an integer, then shift the bit to the appropriate place and then
8719         // cast to integer to avoid the comparison.
8720         const APInt &Op1CV = CI->getValue();
8721     
8722         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
8723         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
8724         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8725             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
8726           Value *In = ICI->getOperand(0);
8727           Value *Sh = ConstantInt::get(In->getType(),
8728                                        In->getType()->getPrimitiveSizeInBits()-1);
8729           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8730                                                           In->getName()+".lobit"),
8731                                    *ICI);
8732           if (In->getType() != SI.getType())
8733             In = CastInst::CreateIntegerCast(In, SI.getType(),
8734                                              true/*SExt*/, "tmp", ICI);
8735     
8736           if (Pred == ICmpInst::ICMP_SGT)
8737             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8738                                        In->getName()+".not"), *ICI);
8739     
8740           return ReplaceInstUsesWith(SI, In);
8741         }
8742       }
8743     }
8744
8745   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8746     // Transform (X == Y) ? X : Y  -> Y
8747     if (Pred == ICmpInst::ICMP_EQ)
8748       return ReplaceInstUsesWith(SI, FalseVal);
8749     // Transform (X != Y) ? X : Y  -> X
8750     if (Pred == ICmpInst::ICMP_NE)
8751       return ReplaceInstUsesWith(SI, TrueVal);
8752     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8753
8754   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8755     // Transform (X == Y) ? Y : X  -> X
8756     if (Pred == ICmpInst::ICMP_EQ)
8757       return ReplaceInstUsesWith(SI, FalseVal);
8758     // Transform (X != Y) ? Y : X  -> Y
8759     if (Pred == ICmpInst::ICMP_NE)
8760       return ReplaceInstUsesWith(SI, TrueVal);
8761     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8762   }
8763
8764   /// NOTE: if we wanted to, this is where to detect integer ABS
8765
8766   return Changed ? &SI : 0;
8767 }
8768
8769 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8770   Value *CondVal = SI.getCondition();
8771   Value *TrueVal = SI.getTrueValue();
8772   Value *FalseVal = SI.getFalseValue();
8773
8774   // select true, X, Y  -> X
8775   // select false, X, Y -> Y
8776   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8777     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8778
8779   // select C, X, X -> X
8780   if (TrueVal == FalseVal)
8781     return ReplaceInstUsesWith(SI, TrueVal);
8782
8783   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8784     return ReplaceInstUsesWith(SI, FalseVal);
8785   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8786     return ReplaceInstUsesWith(SI, TrueVal);
8787   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8788     if (isa<Constant>(TrueVal))
8789       return ReplaceInstUsesWith(SI, TrueVal);
8790     else
8791       return ReplaceInstUsesWith(SI, FalseVal);
8792   }
8793
8794   if (SI.getType() == Type::Int1Ty) {
8795     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8796       if (C->getZExtValue()) {
8797         // Change: A = select B, true, C --> A = or B, C
8798         return BinaryOperator::CreateOr(CondVal, FalseVal);
8799       } else {
8800         // Change: A = select B, false, C --> A = and !B, C
8801         Value *NotCond =
8802           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8803                                              "not."+CondVal->getName()), SI);
8804         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8805       }
8806     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8807       if (C->getZExtValue() == false) {
8808         // Change: A = select B, C, false --> A = and B, C
8809         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8810       } else {
8811         // Change: A = select B, C, true --> A = or !B, C
8812         Value *NotCond =
8813           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8814                                              "not."+CondVal->getName()), SI);
8815         return BinaryOperator::CreateOr(NotCond, TrueVal);
8816       }
8817     }
8818     
8819     // select a, b, a  -> a&b
8820     // select a, a, b  -> a|b
8821     if (CondVal == TrueVal)
8822       return BinaryOperator::CreateOr(CondVal, FalseVal);
8823     else if (CondVal == FalseVal)
8824       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8825   }
8826
8827   // Selecting between two integer constants?
8828   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8829     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8830       // select C, 1, 0 -> zext C to int
8831       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8832         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8833       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8834         // select C, 0, 1 -> zext !C to int
8835         Value *NotCond =
8836           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8837                                                "not."+CondVal->getName()), SI);
8838         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8839       }
8840
8841       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8842
8843         // (x <s 0) ? -1 : 0 -> ashr x, 31
8844         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8845           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8846             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8847               // The comparison constant and the result are not neccessarily the
8848               // same width. Make an all-ones value by inserting a AShr.
8849               Value *X = IC->getOperand(0);
8850               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8851               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8852               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8853                                                         ShAmt, "ones");
8854               InsertNewInstBefore(SRA, SI);
8855
8856               // Then cast to the appropriate width.
8857               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
8858             }
8859           }
8860
8861
8862         // If one of the constants is zero (we know they can't both be) and we
8863         // have an icmp instruction with zero, and we have an 'and' with the
8864         // non-constant value, eliminate this whole mess.  This corresponds to
8865         // cases like this: ((X & 27) ? 27 : 0)
8866         if (TrueValC->isZero() || FalseValC->isZero())
8867           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8868               cast<Constant>(IC->getOperand(1))->isNullValue())
8869             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8870               if (ICA->getOpcode() == Instruction::And &&
8871                   isa<ConstantInt>(ICA->getOperand(1)) &&
8872                   (ICA->getOperand(1) == TrueValC ||
8873                    ICA->getOperand(1) == FalseValC) &&
8874                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8875                 // Okay, now we know that everything is set up, we just don't
8876                 // know whether we have a icmp_ne or icmp_eq and whether the 
8877                 // true or false val is the zero.
8878                 bool ShouldNotVal = !TrueValC->isZero();
8879                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8880                 Value *V = ICA;
8881                 if (ShouldNotVal)
8882                   V = InsertNewInstBefore(BinaryOperator::Create(
8883                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8884                 return ReplaceInstUsesWith(SI, V);
8885               }
8886       }
8887     }
8888
8889   // See if we are selecting two values based on a comparison of the two values.
8890   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8891     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8892       // Transform (X == Y) ? X : Y  -> Y
8893       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8894         // This is not safe in general for floating point:  
8895         // consider X== -0, Y== +0.
8896         // It becomes safe if either operand is a nonzero constant.
8897         ConstantFP *CFPt, *CFPf;
8898         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8899               !CFPt->getValueAPF().isZero()) ||
8900             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8901              !CFPf->getValueAPF().isZero()))
8902         return ReplaceInstUsesWith(SI, FalseVal);
8903       }
8904       // Transform (X != Y) ? X : Y  -> X
8905       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8906         return ReplaceInstUsesWith(SI, TrueVal);
8907       // NOTE: if we wanted to, this is where to detect MIN/MAX
8908
8909     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8910       // Transform (X == Y) ? Y : X  -> X
8911       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8912         // This is not safe in general for floating point:  
8913         // consider X== -0, Y== +0.
8914         // It becomes safe if either operand is a nonzero constant.
8915         ConstantFP *CFPt, *CFPf;
8916         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8917               !CFPt->getValueAPF().isZero()) ||
8918             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8919              !CFPf->getValueAPF().isZero()))
8920           return ReplaceInstUsesWith(SI, FalseVal);
8921       }
8922       // Transform (X != Y) ? Y : X  -> Y
8923       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8924         return ReplaceInstUsesWith(SI, TrueVal);
8925       // NOTE: if we wanted to, this is where to detect MIN/MAX
8926     }
8927     // NOTE: if we wanted to, this is where to detect ABS
8928   }
8929
8930   // See if we are selecting two values based on a comparison of the two values.
8931   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
8932     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
8933       return Result;
8934
8935   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8936     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8937       if (TI->hasOneUse() && FI->hasOneUse()) {
8938         Instruction *AddOp = 0, *SubOp = 0;
8939
8940         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8941         if (TI->getOpcode() == FI->getOpcode())
8942           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8943             return IV;
8944
8945         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8946         // even legal for FP.
8947         if (TI->getOpcode() == Instruction::Sub &&
8948             FI->getOpcode() == Instruction::Add) {
8949           AddOp = FI; SubOp = TI;
8950         } else if (FI->getOpcode() == Instruction::Sub &&
8951                    TI->getOpcode() == Instruction::Add) {
8952           AddOp = TI; SubOp = FI;
8953         }
8954
8955         if (AddOp) {
8956           Value *OtherAddOp = 0;
8957           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8958             OtherAddOp = AddOp->getOperand(1);
8959           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8960             OtherAddOp = AddOp->getOperand(0);
8961           }
8962
8963           if (OtherAddOp) {
8964             // So at this point we know we have (Y -> OtherAddOp):
8965             //        select C, (add X, Y), (sub X, Z)
8966             Value *NegVal;  // Compute -Z
8967             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8968               NegVal = ConstantExpr::getNeg(C);
8969             } else {
8970               NegVal = InsertNewInstBefore(
8971                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8972             }
8973
8974             Value *NewTrueOp = OtherAddOp;
8975             Value *NewFalseOp = NegVal;
8976             if (AddOp != TI)
8977               std::swap(NewTrueOp, NewFalseOp);
8978             Instruction *NewSel =
8979               SelectInst::Create(CondVal, NewTrueOp,
8980                                  NewFalseOp, SI.getName() + ".p");
8981
8982             NewSel = InsertNewInstBefore(NewSel, SI);
8983             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8984           }
8985         }
8986       }
8987
8988   // See if we can fold the select into one of our operands.
8989   if (SI.getType()->isInteger()) {
8990     // See the comment above GetSelectFoldableOperands for a description of the
8991     // transformation we are doing here.
8992     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8993       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8994           !isa<Constant>(FalseVal))
8995         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8996           unsigned OpToFold = 0;
8997           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8998             OpToFold = 1;
8999           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9000             OpToFold = 2;
9001           }
9002
9003           if (OpToFold) {
9004             Constant *C = GetSelectFoldableConstant(TVI);
9005             Instruction *NewSel =
9006               SelectInst::Create(SI.getCondition(),
9007                                  TVI->getOperand(2-OpToFold), C);
9008             InsertNewInstBefore(NewSel, SI);
9009             NewSel->takeName(TVI);
9010             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9011               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9012             else {
9013               assert(0 && "Unknown instruction!!");
9014             }
9015           }
9016         }
9017
9018     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9019       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9020           !isa<Constant>(TrueVal))
9021         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9022           unsigned OpToFold = 0;
9023           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9024             OpToFold = 1;
9025           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9026             OpToFold = 2;
9027           }
9028
9029           if (OpToFold) {
9030             Constant *C = GetSelectFoldableConstant(FVI);
9031             Instruction *NewSel =
9032               SelectInst::Create(SI.getCondition(), C,
9033                                  FVI->getOperand(2-OpToFold));
9034             InsertNewInstBefore(NewSel, SI);
9035             NewSel->takeName(FVI);
9036             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9037               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9038             else
9039               assert(0 && "Unknown instruction!!");
9040           }
9041         }
9042   }
9043
9044   if (BinaryOperator::isNot(CondVal)) {
9045     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9046     SI.setOperand(1, FalseVal);
9047     SI.setOperand(2, TrueVal);
9048     return &SI;
9049   }
9050
9051   return 0;
9052 }
9053
9054 /// EnforceKnownAlignment - If the specified pointer points to an object that
9055 /// we control, modify the object's alignment to PrefAlign. This isn't
9056 /// often possible though. If alignment is important, a more reliable approach
9057 /// is to simply align all global variables and allocation instructions to
9058 /// their preferred alignment from the beginning.
9059 ///
9060 static unsigned EnforceKnownAlignment(Value *V,
9061                                       unsigned Align, unsigned PrefAlign) {
9062
9063   User *U = dyn_cast<User>(V);
9064   if (!U) return Align;
9065
9066   switch (getOpcode(U)) {
9067   default: break;
9068   case Instruction::BitCast:
9069     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9070   case Instruction::GetElementPtr: {
9071     // If all indexes are zero, it is just the alignment of the base pointer.
9072     bool AllZeroOperands = true;
9073     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9074       if (!isa<Constant>(*i) ||
9075           !cast<Constant>(*i)->isNullValue()) {
9076         AllZeroOperands = false;
9077         break;
9078       }
9079
9080     if (AllZeroOperands) {
9081       // Treat this like a bitcast.
9082       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9083     }
9084     break;
9085   }
9086   }
9087
9088   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9089     // If there is a large requested alignment and we can, bump up the alignment
9090     // of the global.
9091     if (!GV->isDeclaration()) {
9092       GV->setAlignment(PrefAlign);
9093       Align = PrefAlign;
9094     }
9095   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9096     // If there is a requested alignment and if this is an alloca, round up.  We
9097     // don't do this for malloc, because some systems can't respect the request.
9098     if (isa<AllocaInst>(AI)) {
9099       AI->setAlignment(PrefAlign);
9100       Align = PrefAlign;
9101     }
9102   }
9103
9104   return Align;
9105 }
9106
9107 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9108 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9109 /// and it is more than the alignment of the ultimate object, see if we can
9110 /// increase the alignment of the ultimate object, making this check succeed.
9111 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9112                                                   unsigned PrefAlign) {
9113   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9114                       sizeof(PrefAlign) * CHAR_BIT;
9115   APInt Mask = APInt::getAllOnesValue(BitWidth);
9116   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9117   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9118   unsigned TrailZ = KnownZero.countTrailingOnes();
9119   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9120
9121   if (PrefAlign > Align)
9122     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9123   
9124     // We don't need to make any adjustment.
9125   return Align;
9126 }
9127
9128 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9129   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9130   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9131   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9132   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9133
9134   if (CopyAlign < MinAlign) {
9135     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9136     return MI;
9137   }
9138   
9139   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9140   // load/store.
9141   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9142   if (MemOpLength == 0) return 0;
9143   
9144   // Source and destination pointer types are always "i8*" for intrinsic.  See
9145   // if the size is something we can handle with a single primitive load/store.
9146   // A single load+store correctly handles overlapping memory in the memmove
9147   // case.
9148   unsigned Size = MemOpLength->getZExtValue();
9149   if (Size == 0) return MI;  // Delete this mem transfer.
9150   
9151   if (Size > 8 || (Size&(Size-1)))
9152     return 0;  // If not 1/2/4/8 bytes, exit.
9153   
9154   // Use an integer load+store unless we can find something better.
9155   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9156   
9157   // Memcpy forces the use of i8* for the source and destination.  That means
9158   // that if you're using memcpy to move one double around, you'll get a cast
9159   // from double* to i8*.  We'd much rather use a double load+store rather than
9160   // an i64 load+store, here because this improves the odds that the source or
9161   // dest address will be promotable.  See if we can find a better type than the
9162   // integer datatype.
9163   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9164     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9165     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9166       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9167       // down through these levels if so.
9168       while (!SrcETy->isSingleValueType()) {
9169         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9170           if (STy->getNumElements() == 1)
9171             SrcETy = STy->getElementType(0);
9172           else
9173             break;
9174         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9175           if (ATy->getNumElements() == 1)
9176             SrcETy = ATy->getElementType();
9177           else
9178             break;
9179         } else
9180           break;
9181       }
9182       
9183       if (SrcETy->isSingleValueType())
9184         NewPtrTy = PointerType::getUnqual(SrcETy);
9185     }
9186   }
9187   
9188   
9189   // If the memcpy/memmove provides better alignment info than we can
9190   // infer, use it.
9191   SrcAlign = std::max(SrcAlign, CopyAlign);
9192   DstAlign = std::max(DstAlign, CopyAlign);
9193   
9194   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9195   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9196   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9197   InsertNewInstBefore(L, *MI);
9198   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9199
9200   // Set the size of the copy to 0, it will be deleted on the next iteration.
9201   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9202   return MI;
9203 }
9204
9205 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9206   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9207   if (MI->getAlignment()->getZExtValue() < Alignment) {
9208     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9209     return MI;
9210   }
9211   
9212   // Extract the length and alignment and fill if they are constant.
9213   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9214   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9215   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9216     return 0;
9217   uint64_t Len = LenC->getZExtValue();
9218   Alignment = MI->getAlignment()->getZExtValue();
9219   
9220   // If the length is zero, this is a no-op
9221   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9222   
9223   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9224   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9225     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9226     
9227     Value *Dest = MI->getDest();
9228     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9229
9230     // Alignment 0 is identity for alignment 1 for memset, but not store.
9231     if (Alignment == 0) Alignment = 1;
9232     
9233     // Extract the fill value and store.
9234     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9235     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9236                                       Alignment), *MI);
9237     
9238     // Set the size of the copy to 0, it will be deleted on the next iteration.
9239     MI->setLength(Constant::getNullValue(LenC->getType()));
9240     return MI;
9241   }
9242
9243   return 0;
9244 }
9245
9246
9247 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9248 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9249 /// the heavy lifting.
9250 ///
9251 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9252   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9253   if (!II) return visitCallSite(&CI);
9254   
9255   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9256   // visitCallSite.
9257   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9258     bool Changed = false;
9259
9260     // memmove/cpy/set of zero bytes is a noop.
9261     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9262       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9263
9264       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9265         if (CI->getZExtValue() == 1) {
9266           // Replace the instruction with just byte operations.  We would
9267           // transform other cases to loads/stores, but we don't know if
9268           // alignment is sufficient.
9269         }
9270     }
9271
9272     // If we have a memmove and the source operation is a constant global,
9273     // then the source and dest pointers can't alias, so we can change this
9274     // into a call to memcpy.
9275     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9276       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9277         if (GVSrc->isConstant()) {
9278           Module *M = CI.getParent()->getParent()->getParent();
9279           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9280           const Type *Tys[1];
9281           Tys[0] = CI.getOperand(3)->getType();
9282           CI.setOperand(0, 
9283                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9284           Changed = true;
9285         }
9286
9287       // memmove(x,x,size) -> noop.
9288       if (MMI->getSource() == MMI->getDest())
9289         return EraseInstFromFunction(CI);
9290     }
9291
9292     // If we can determine a pointer alignment that is bigger than currently
9293     // set, update the alignment.
9294     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9295       if (Instruction *I = SimplifyMemTransfer(MI))
9296         return I;
9297     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9298       if (Instruction *I = SimplifyMemSet(MSI))
9299         return I;
9300     }
9301           
9302     if (Changed) return II;
9303   }
9304   
9305   switch (II->getIntrinsicID()) {
9306   default: break;
9307   case Intrinsic::bswap:
9308     // bswap(bswap(x)) -> x
9309     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9310       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9311         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9312     break;
9313   case Intrinsic::ppc_altivec_lvx:
9314   case Intrinsic::ppc_altivec_lvxl:
9315   case Intrinsic::x86_sse_loadu_ps:
9316   case Intrinsic::x86_sse2_loadu_pd:
9317   case Intrinsic::x86_sse2_loadu_dq:
9318     // Turn PPC lvx     -> load if the pointer is known aligned.
9319     // Turn X86 loadups -> load if the pointer is known aligned.
9320     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9321       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9322                                        PointerType::getUnqual(II->getType()),
9323                                        CI);
9324       return new LoadInst(Ptr);
9325     }
9326     break;
9327   case Intrinsic::ppc_altivec_stvx:
9328   case Intrinsic::ppc_altivec_stvxl:
9329     // Turn stvx -> store if the pointer is known aligned.
9330     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9331       const Type *OpPtrTy = 
9332         PointerType::getUnqual(II->getOperand(1)->getType());
9333       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9334       return new StoreInst(II->getOperand(1), Ptr);
9335     }
9336     break;
9337   case Intrinsic::x86_sse_storeu_ps:
9338   case Intrinsic::x86_sse2_storeu_pd:
9339   case Intrinsic::x86_sse2_storeu_dq:
9340     // Turn X86 storeu -> store if the pointer is known aligned.
9341     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9342       const Type *OpPtrTy = 
9343         PointerType::getUnqual(II->getOperand(2)->getType());
9344       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9345       return new StoreInst(II->getOperand(2), Ptr);
9346     }
9347     break;
9348     
9349   case Intrinsic::x86_sse_cvttss2si: {
9350     // These intrinsics only demands the 0th element of its input vector.  If
9351     // we can simplify the input based on that, do so now.
9352     uint64_t UndefElts;
9353     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
9354                                               UndefElts)) {
9355       II->setOperand(1, V);
9356       return II;
9357     }
9358     break;
9359   }
9360     
9361   case Intrinsic::ppc_altivec_vperm:
9362     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9363     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9364       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9365       
9366       // Check that all of the elements are integer constants or undefs.
9367       bool AllEltsOk = true;
9368       for (unsigned i = 0; i != 16; ++i) {
9369         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9370             !isa<UndefValue>(Mask->getOperand(i))) {
9371           AllEltsOk = false;
9372           break;
9373         }
9374       }
9375       
9376       if (AllEltsOk) {
9377         // Cast the input vectors to byte vectors.
9378         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9379         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9380         Value *Result = UndefValue::get(Op0->getType());
9381         
9382         // Only extract each element once.
9383         Value *ExtractedElts[32];
9384         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9385         
9386         for (unsigned i = 0; i != 16; ++i) {
9387           if (isa<UndefValue>(Mask->getOperand(i)))
9388             continue;
9389           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9390           Idx &= 31;  // Match the hardware behavior.
9391           
9392           if (ExtractedElts[Idx] == 0) {
9393             Instruction *Elt = 
9394               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9395             InsertNewInstBefore(Elt, CI);
9396             ExtractedElts[Idx] = Elt;
9397           }
9398         
9399           // Insert this value into the result vector.
9400           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9401                                              i, "tmp");
9402           InsertNewInstBefore(cast<Instruction>(Result), CI);
9403         }
9404         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9405       }
9406     }
9407     break;
9408
9409   case Intrinsic::stackrestore: {
9410     // If the save is right next to the restore, remove the restore.  This can
9411     // happen when variable allocas are DCE'd.
9412     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9413       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9414         BasicBlock::iterator BI = SS;
9415         if (&*++BI == II)
9416           return EraseInstFromFunction(CI);
9417       }
9418     }
9419     
9420     // Scan down this block to see if there is another stack restore in the
9421     // same block without an intervening call/alloca.
9422     BasicBlock::iterator BI = II;
9423     TerminatorInst *TI = II->getParent()->getTerminator();
9424     bool CannotRemove = false;
9425     for (++BI; &*BI != TI; ++BI) {
9426       if (isa<AllocaInst>(BI)) {
9427         CannotRemove = true;
9428         break;
9429       }
9430       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9431         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9432           // If there is a stackrestore below this one, remove this one.
9433           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9434             return EraseInstFromFunction(CI);
9435           // Otherwise, ignore the intrinsic.
9436         } else {
9437           // If we found a non-intrinsic call, we can't remove the stack
9438           // restore.
9439           CannotRemove = true;
9440           break;
9441         }
9442       }
9443     }
9444     
9445     // If the stack restore is in a return/unwind block and if there are no
9446     // allocas or calls between the restore and the return, nuke the restore.
9447     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9448       return EraseInstFromFunction(CI);
9449     break;
9450   }
9451   }
9452
9453   return visitCallSite(II);
9454 }
9455
9456 // InvokeInst simplification
9457 //
9458 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9459   return visitCallSite(&II);
9460 }
9461
9462 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9463 /// passed through the varargs area, we can eliminate the use of the cast.
9464 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9465                                          const CastInst * const CI,
9466                                          const TargetData * const TD,
9467                                          const int ix) {
9468   if (!CI->isLosslessCast())
9469     return false;
9470
9471   // The size of ByVal arguments is derived from the type, so we
9472   // can't change to a type with a different size.  If the size were
9473   // passed explicitly we could avoid this check.
9474   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9475     return true;
9476
9477   const Type* SrcTy = 
9478             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9479   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9480   if (!SrcTy->isSized() || !DstTy->isSized())
9481     return false;
9482   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9483     return false;
9484   return true;
9485 }
9486
9487 // visitCallSite - Improvements for call and invoke instructions.
9488 //
9489 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9490   bool Changed = false;
9491
9492   // If the callee is a constexpr cast of a function, attempt to move the cast
9493   // to the arguments of the call/invoke.
9494   if (transformConstExprCastCall(CS)) return 0;
9495
9496   Value *Callee = CS.getCalledValue();
9497
9498   if (Function *CalleeF = dyn_cast<Function>(Callee))
9499     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9500       Instruction *OldCall = CS.getInstruction();
9501       // If the call and callee calling conventions don't match, this call must
9502       // be unreachable, as the call is undefined.
9503       new StoreInst(ConstantInt::getTrue(),
9504                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9505                                     OldCall);
9506       if (!OldCall->use_empty())
9507         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9508       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9509         return EraseInstFromFunction(*OldCall);
9510       return 0;
9511     }
9512
9513   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9514     // This instruction is not reachable, just remove it.  We insert a store to
9515     // undef so that we know that this code is not reachable, despite the fact
9516     // that we can't modify the CFG here.
9517     new StoreInst(ConstantInt::getTrue(),
9518                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9519                   CS.getInstruction());
9520
9521     if (!CS.getInstruction()->use_empty())
9522       CS.getInstruction()->
9523         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9524
9525     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9526       // Don't break the CFG, insert a dummy cond branch.
9527       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9528                          ConstantInt::getTrue(), II);
9529     }
9530     return EraseInstFromFunction(*CS.getInstruction());
9531   }
9532
9533   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9534     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9535       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9536         return transformCallThroughTrampoline(CS);
9537
9538   const PointerType *PTy = cast<PointerType>(Callee->getType());
9539   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9540   if (FTy->isVarArg()) {
9541     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9542     // See if we can optimize any arguments passed through the varargs area of
9543     // the call.
9544     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9545            E = CS.arg_end(); I != E; ++I, ++ix) {
9546       CastInst *CI = dyn_cast<CastInst>(*I);
9547       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9548         *I = CI->getOperand(0);
9549         Changed = true;
9550       }
9551     }
9552   }
9553
9554   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9555     // Inline asm calls cannot throw - mark them 'nounwind'.
9556     CS.setDoesNotThrow();
9557     Changed = true;
9558   }
9559
9560   return Changed ? CS.getInstruction() : 0;
9561 }
9562
9563 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9564 // attempt to move the cast to the arguments of the call/invoke.
9565 //
9566 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9567   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9568   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9569   if (CE->getOpcode() != Instruction::BitCast || 
9570       !isa<Function>(CE->getOperand(0)))
9571     return false;
9572   Function *Callee = cast<Function>(CE->getOperand(0));
9573   Instruction *Caller = CS.getInstruction();
9574   const AttrListPtr &CallerPAL = CS.getAttributes();
9575
9576   // Okay, this is a cast from a function to a different type.  Unless doing so
9577   // would cause a type conversion of one of our arguments, change this call to
9578   // be a direct call with arguments casted to the appropriate types.
9579   //
9580   const FunctionType *FT = Callee->getFunctionType();
9581   const Type *OldRetTy = Caller->getType();
9582   const Type *NewRetTy = FT->getReturnType();
9583
9584   if (isa<StructType>(NewRetTy))
9585     return false; // TODO: Handle multiple return values.
9586
9587   // Check to see if we are changing the return type...
9588   if (OldRetTy != NewRetTy) {
9589     if (Callee->isDeclaration() &&
9590         // Conversion is ok if changing from one pointer type to another or from
9591         // a pointer to an integer of the same size.
9592         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9593           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9594       return false;   // Cannot transform this return value.
9595
9596     if (!Caller->use_empty() &&
9597         // void -> non-void is handled specially
9598         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9599       return false;   // Cannot transform this return value.
9600
9601     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9602       Attributes RAttrs = CallerPAL.getRetAttributes();
9603       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9604         return false;   // Attribute not compatible with transformed value.
9605     }
9606
9607     // If the callsite is an invoke instruction, and the return value is used by
9608     // a PHI node in a successor, we cannot change the return type of the call
9609     // because there is no place to put the cast instruction (without breaking
9610     // the critical edge).  Bail out in this case.
9611     if (!Caller->use_empty())
9612       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9613         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9614              UI != E; ++UI)
9615           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9616             if (PN->getParent() == II->getNormalDest() ||
9617                 PN->getParent() == II->getUnwindDest())
9618               return false;
9619   }
9620
9621   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9622   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9623
9624   CallSite::arg_iterator AI = CS.arg_begin();
9625   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9626     const Type *ParamTy = FT->getParamType(i);
9627     const Type *ActTy = (*AI)->getType();
9628
9629     if (!CastInst::isCastable(ActTy, ParamTy))
9630       return false;   // Cannot transform this parameter value.
9631
9632     if (CallerPAL.getParamAttributes(i + 1) 
9633         & Attribute::typeIncompatible(ParamTy))
9634       return false;   // Attribute not compatible with transformed value.
9635
9636     // Converting from one pointer type to another or between a pointer and an
9637     // integer of the same size is safe even if we do not have a body.
9638     bool isConvertible = ActTy == ParamTy ||
9639       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9640        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9641     if (Callee->isDeclaration() && !isConvertible) return false;
9642   }
9643
9644   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9645       Callee->isDeclaration())
9646     return false;   // Do not delete arguments unless we have a function body.
9647
9648   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9649       !CallerPAL.isEmpty())
9650     // In this case we have more arguments than the new function type, but we
9651     // won't be dropping them.  Check that these extra arguments have attributes
9652     // that are compatible with being a vararg call argument.
9653     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9654       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9655         break;
9656       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9657       if (PAttrs & Attribute::VarArgsIncompatible)
9658         return false;
9659     }
9660
9661   // Okay, we decided that this is a safe thing to do: go ahead and start
9662   // inserting cast instructions as necessary...
9663   std::vector<Value*> Args;
9664   Args.reserve(NumActualArgs);
9665   SmallVector<AttributeWithIndex, 8> attrVec;
9666   attrVec.reserve(NumCommonArgs);
9667
9668   // Get any return attributes.
9669   Attributes RAttrs = CallerPAL.getRetAttributes();
9670
9671   // If the return value is not being used, the type may not be compatible
9672   // with the existing attributes.  Wipe out any problematic attributes.
9673   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
9674
9675   // Add the new return attributes.
9676   if (RAttrs)
9677     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
9678
9679   AI = CS.arg_begin();
9680   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9681     const Type *ParamTy = FT->getParamType(i);
9682     if ((*AI)->getType() == ParamTy) {
9683       Args.push_back(*AI);
9684     } else {
9685       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9686           false, ParamTy, false);
9687       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9688       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9689     }
9690
9691     // Add any parameter attributes.
9692     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9693       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9694   }
9695
9696   // If the function takes more arguments than the call was taking, add them
9697   // now...
9698   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9699     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9700
9701   // If we are removing arguments to the function, emit an obnoxious warning...
9702   if (FT->getNumParams() < NumActualArgs) {
9703     if (!FT->isVarArg()) {
9704       cerr << "WARNING: While resolving call to function '"
9705            << Callee->getName() << "' arguments were dropped!\n";
9706     } else {
9707       // Add all of the arguments in their promoted form to the arg list...
9708       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9709         const Type *PTy = getPromotedType((*AI)->getType());
9710         if (PTy != (*AI)->getType()) {
9711           // Must promote to pass through va_arg area!
9712           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9713                                                                 PTy, false);
9714           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9715           InsertNewInstBefore(Cast, *Caller);
9716           Args.push_back(Cast);
9717         } else {
9718           Args.push_back(*AI);
9719         }
9720
9721         // Add any parameter attributes.
9722         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9723           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9724       }
9725     }
9726   }
9727
9728   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
9729     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9730
9731   if (NewRetTy == Type::VoidTy)
9732     Caller->setName("");   // Void type should not have a name.
9733
9734   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
9735
9736   Instruction *NC;
9737   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9738     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9739                             Args.begin(), Args.end(),
9740                             Caller->getName(), Caller);
9741     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9742     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
9743   } else {
9744     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9745                           Caller->getName(), Caller);
9746     CallInst *CI = cast<CallInst>(Caller);
9747     if (CI->isTailCall())
9748       cast<CallInst>(NC)->setTailCall();
9749     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9750     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
9751   }
9752
9753   // Insert a cast of the return type as necessary.
9754   Value *NV = NC;
9755   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9756     if (NV->getType() != Type::VoidTy) {
9757       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9758                                                             OldRetTy, false);
9759       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9760
9761       // If this is an invoke instruction, we should insert it after the first
9762       // non-phi, instruction in the normal successor block.
9763       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9764         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9765         InsertNewInstBefore(NC, *I);
9766       } else {
9767         // Otherwise, it's a call, just insert cast right after the call instr
9768         InsertNewInstBefore(NC, *Caller);
9769       }
9770       AddUsersToWorkList(*Caller);
9771     } else {
9772       NV = UndefValue::get(Caller->getType());
9773     }
9774   }
9775
9776   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9777     Caller->replaceAllUsesWith(NV);
9778   Caller->eraseFromParent();
9779   RemoveFromWorkList(Caller);
9780   return true;
9781 }
9782
9783 // transformCallThroughTrampoline - Turn a call to a function created by the
9784 // init_trampoline intrinsic into a direct call to the underlying function.
9785 //
9786 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9787   Value *Callee = CS.getCalledValue();
9788   const PointerType *PTy = cast<PointerType>(Callee->getType());
9789   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9790   const AttrListPtr &Attrs = CS.getAttributes();
9791
9792   // If the call already has the 'nest' attribute somewhere then give up -
9793   // otherwise 'nest' would occur twice after splicing in the chain.
9794   if (Attrs.hasAttrSomewhere(Attribute::Nest))
9795     return 0;
9796
9797   IntrinsicInst *Tramp =
9798     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9799
9800   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9801   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9802   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9803
9804   const AttrListPtr &NestAttrs = NestF->getAttributes();
9805   if (!NestAttrs.isEmpty()) {
9806     unsigned NestIdx = 1;
9807     const Type *NestTy = 0;
9808     Attributes NestAttr = Attribute::None;
9809
9810     // Look for a parameter marked with the 'nest' attribute.
9811     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9812          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9813       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
9814         // Record the parameter type and any other attributes.
9815         NestTy = *I;
9816         NestAttr = NestAttrs.getParamAttributes(NestIdx);
9817         break;
9818       }
9819
9820     if (NestTy) {
9821       Instruction *Caller = CS.getInstruction();
9822       std::vector<Value*> NewArgs;
9823       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9824
9825       SmallVector<AttributeWithIndex, 8> NewAttrs;
9826       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9827
9828       // Insert the nest argument into the call argument list, which may
9829       // mean appending it.  Likewise for attributes.
9830
9831       // Add any result attributes.
9832       if (Attributes Attr = Attrs.getRetAttributes())
9833         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
9834
9835       {
9836         unsigned Idx = 1;
9837         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9838         do {
9839           if (Idx == NestIdx) {
9840             // Add the chain argument and attributes.
9841             Value *NestVal = Tramp->getOperand(3);
9842             if (NestVal->getType() != NestTy)
9843               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9844             NewArgs.push_back(NestVal);
9845             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
9846           }
9847
9848           if (I == E)
9849             break;
9850
9851           // Add the original argument and attributes.
9852           NewArgs.push_back(*I);
9853           if (Attributes Attr = Attrs.getParamAttributes(Idx))
9854             NewAttrs.push_back
9855               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9856
9857           ++Idx, ++I;
9858         } while (1);
9859       }
9860
9861       // Add any function attributes.
9862       if (Attributes Attr = Attrs.getFnAttributes())
9863         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9864
9865       // The trampoline may have been bitcast to a bogus type (FTy).
9866       // Handle this by synthesizing a new function type, equal to FTy
9867       // with the chain parameter inserted.
9868
9869       std::vector<const Type*> NewTypes;
9870       NewTypes.reserve(FTy->getNumParams()+1);
9871
9872       // Insert the chain's type into the list of parameter types, which may
9873       // mean appending it.
9874       {
9875         unsigned Idx = 1;
9876         FunctionType::param_iterator I = FTy->param_begin(),
9877           E = FTy->param_end();
9878
9879         do {
9880           if (Idx == NestIdx)
9881             // Add the chain's type.
9882             NewTypes.push_back(NestTy);
9883
9884           if (I == E)
9885             break;
9886
9887           // Add the original type.
9888           NewTypes.push_back(*I);
9889
9890           ++Idx, ++I;
9891         } while (1);
9892       }
9893
9894       // Replace the trampoline call with a direct call.  Let the generic
9895       // code sort out any function type mismatches.
9896       FunctionType *NewFTy =
9897         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9898       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9899         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9900       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
9901
9902       Instruction *NewCaller;
9903       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9904         NewCaller = InvokeInst::Create(NewCallee,
9905                                        II->getNormalDest(), II->getUnwindDest(),
9906                                        NewArgs.begin(), NewArgs.end(),
9907                                        Caller->getName(), Caller);
9908         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9909         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
9910       } else {
9911         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9912                                      Caller->getName(), Caller);
9913         if (cast<CallInst>(Caller)->isTailCall())
9914           cast<CallInst>(NewCaller)->setTailCall();
9915         cast<CallInst>(NewCaller)->
9916           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9917         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
9918       }
9919       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9920         Caller->replaceAllUsesWith(NewCaller);
9921       Caller->eraseFromParent();
9922       RemoveFromWorkList(Caller);
9923       return 0;
9924     }
9925   }
9926
9927   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9928   // parameter, there is no need to adjust the argument list.  Let the generic
9929   // code sort out any function type mismatches.
9930   Constant *NewCallee =
9931     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9932   CS.setCalledFunction(NewCallee);
9933   return CS.getInstruction();
9934 }
9935
9936 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9937 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9938 /// and a single binop.
9939 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9940   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9941   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
9942   unsigned Opc = FirstInst->getOpcode();
9943   Value *LHSVal = FirstInst->getOperand(0);
9944   Value *RHSVal = FirstInst->getOperand(1);
9945     
9946   const Type *LHSType = LHSVal->getType();
9947   const Type *RHSType = RHSVal->getType();
9948   
9949   // Scan to see if all operands are the same opcode, all have one use, and all
9950   // kill their operands (i.e. the operands have one use).
9951   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
9952     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9953     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9954         // Verify type of the LHS matches so we don't fold cmp's of different
9955         // types or GEP's with different index types.
9956         I->getOperand(0)->getType() != LHSType ||
9957         I->getOperand(1)->getType() != RHSType)
9958       return 0;
9959
9960     // If they are CmpInst instructions, check their predicates
9961     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9962       if (cast<CmpInst>(I)->getPredicate() !=
9963           cast<CmpInst>(FirstInst)->getPredicate())
9964         return 0;
9965     
9966     // Keep track of which operand needs a phi node.
9967     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9968     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9969   }
9970   
9971   // Otherwise, this is safe to transform!
9972   
9973   Value *InLHS = FirstInst->getOperand(0);
9974   Value *InRHS = FirstInst->getOperand(1);
9975   PHINode *NewLHS = 0, *NewRHS = 0;
9976   if (LHSVal == 0) {
9977     NewLHS = PHINode::Create(LHSType,
9978                              FirstInst->getOperand(0)->getName() + ".pn");
9979     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9980     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9981     InsertNewInstBefore(NewLHS, PN);
9982     LHSVal = NewLHS;
9983   }
9984   
9985   if (RHSVal == 0) {
9986     NewRHS = PHINode::Create(RHSType,
9987                              FirstInst->getOperand(1)->getName() + ".pn");
9988     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9989     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9990     InsertNewInstBefore(NewRHS, PN);
9991     RHSVal = NewRHS;
9992   }
9993   
9994   // Add all operands to the new PHIs.
9995   if (NewLHS || NewRHS) {
9996     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9997       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
9998       if (NewLHS) {
9999         Value *NewInLHS = InInst->getOperand(0);
10000         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10001       }
10002       if (NewRHS) {
10003         Value *NewInRHS = InInst->getOperand(1);
10004         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10005       }
10006     }
10007   }
10008     
10009   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10010     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10011   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10012   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10013                          RHSVal);
10014 }
10015
10016 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10017   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10018   
10019   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10020                                         FirstInst->op_end());
10021   
10022   // Scan to see if all operands are the same opcode, all have one use, and all
10023   // kill their operands (i.e. the operands have one use).
10024   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10025     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10026     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10027       GEP->getNumOperands() != FirstInst->getNumOperands())
10028       return 0;
10029
10030     // Compare the operand lists.
10031     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10032       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10033         continue;
10034       
10035       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10036       // if one of the PHIs has a constant for the index.  The index may be
10037       // substantially cheaper to compute for the constants, so making it a
10038       // variable index could pessimize the path.  This also handles the case
10039       // for struct indices, which must always be constant.
10040       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10041           isa<ConstantInt>(GEP->getOperand(op)))
10042         return 0;
10043       
10044       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10045         return 0;
10046       FixedOperands[op] = 0;  // Needs a PHI.
10047     }
10048   }
10049   
10050   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10051   // that is variable.
10052   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10053   
10054   bool HasAnyPHIs = false;
10055   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10056     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10057     Value *FirstOp = FirstInst->getOperand(i);
10058     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10059                                      FirstOp->getName()+".pn");
10060     InsertNewInstBefore(NewPN, PN);
10061     
10062     NewPN->reserveOperandSpace(e);
10063     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10064     OperandPhis[i] = NewPN;
10065     FixedOperands[i] = NewPN;
10066     HasAnyPHIs = true;
10067   }
10068
10069   
10070   // Add all operands to the new PHIs.
10071   if (HasAnyPHIs) {
10072     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10073       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10074       BasicBlock *InBB = PN.getIncomingBlock(i);
10075       
10076       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10077         if (PHINode *OpPhi = OperandPhis[op])
10078           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10079     }
10080   }
10081   
10082   Value *Base = FixedOperands[0];
10083   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10084                                    FixedOperands.end());
10085 }
10086
10087
10088 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
10089 /// of the block that defines it.  This means that it must be obvious the value
10090 /// of the load is not changed from the point of the load to the end of the
10091 /// block it is in.
10092 ///
10093 /// Finally, it is safe, but not profitable, to sink a load targetting a
10094 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10095 /// to a register.
10096 static bool isSafeToSinkLoad(LoadInst *L) {
10097   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10098   
10099   for (++BBI; BBI != E; ++BBI)
10100     if (BBI->mayWriteToMemory())
10101       return false;
10102   
10103   // Check for non-address taken alloca.  If not address-taken already, it isn't
10104   // profitable to do this xform.
10105   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10106     bool isAddressTaken = false;
10107     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10108          UI != E; ++UI) {
10109       if (isa<LoadInst>(UI)) continue;
10110       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10111         // If storing TO the alloca, then the address isn't taken.
10112         if (SI->getOperand(1) == AI) continue;
10113       }
10114       isAddressTaken = true;
10115       break;
10116     }
10117     
10118     if (!isAddressTaken)
10119       return false;
10120   }
10121   
10122   return true;
10123 }
10124
10125
10126 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10127 // operator and they all are only used by the PHI, PHI together their
10128 // inputs, and do the operation once, to the result of the PHI.
10129 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10130   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10131
10132   // Scan the instruction, looking for input operations that can be folded away.
10133   // If all input operands to the phi are the same instruction (e.g. a cast from
10134   // the same type or "+42") we can pull the operation through the PHI, reducing
10135   // code size and simplifying code.
10136   Constant *ConstantOp = 0;
10137   const Type *CastSrcTy = 0;
10138   bool isVolatile = false;
10139   if (isa<CastInst>(FirstInst)) {
10140     CastSrcTy = FirstInst->getOperand(0)->getType();
10141   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10142     // Can fold binop, compare or shift here if the RHS is a constant, 
10143     // otherwise call FoldPHIArgBinOpIntoPHI.
10144     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10145     if (ConstantOp == 0)
10146       return FoldPHIArgBinOpIntoPHI(PN);
10147   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10148     isVolatile = LI->isVolatile();
10149     // We can't sink the load if the loaded value could be modified between the
10150     // load and the PHI.
10151     if (LI->getParent() != PN.getIncomingBlock(0) ||
10152         !isSafeToSinkLoad(LI))
10153       return 0;
10154     
10155     // If the PHI is of volatile loads and the load block has multiple
10156     // successors, sinking it would remove a load of the volatile value from
10157     // the path through the other successor.
10158     if (isVolatile &&
10159         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10160       return 0;
10161     
10162   } else if (isa<GetElementPtrInst>(FirstInst)) {
10163     return FoldPHIArgGEPIntoPHI(PN);
10164   } else {
10165     return 0;  // Cannot fold this operation.
10166   }
10167
10168   // Check to see if all arguments are the same operation.
10169   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10170     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10171     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10172     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10173       return 0;
10174     if (CastSrcTy) {
10175       if (I->getOperand(0)->getType() != CastSrcTy)
10176         return 0;  // Cast operation must match.
10177     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10178       // We can't sink the load if the loaded value could be modified between 
10179       // the load and the PHI.
10180       if (LI->isVolatile() != isVolatile ||
10181           LI->getParent() != PN.getIncomingBlock(i) ||
10182           !isSafeToSinkLoad(LI))
10183         return 0;
10184       
10185       // If the PHI is of volatile loads and the load block has multiple
10186       // successors, sinking it would remove a load of the volatile value from
10187       // the path through the other successor.
10188       if (isVolatile &&
10189           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10190         return 0;
10191
10192       
10193     } else if (I->getOperand(1) != ConstantOp) {
10194       return 0;
10195     }
10196   }
10197
10198   // Okay, they are all the same operation.  Create a new PHI node of the
10199   // correct type, and PHI together all of the LHS's of the instructions.
10200   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10201                                    PN.getName()+".in");
10202   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10203
10204   Value *InVal = FirstInst->getOperand(0);
10205   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10206
10207   // Add all operands to the new PHI.
10208   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10209     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10210     if (NewInVal != InVal)
10211       InVal = 0;
10212     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10213   }
10214
10215   Value *PhiVal;
10216   if (InVal) {
10217     // The new PHI unions all of the same values together.  This is really
10218     // common, so we handle it intelligently here for compile-time speed.
10219     PhiVal = InVal;
10220     delete NewPN;
10221   } else {
10222     InsertNewInstBefore(NewPN, PN);
10223     PhiVal = NewPN;
10224   }
10225
10226   // Insert and return the new operation.
10227   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10228     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10229   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10230     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10231   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10232     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10233                            PhiVal, ConstantOp);
10234   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10235   
10236   // If this was a volatile load that we are merging, make sure to loop through
10237   // and mark all the input loads as non-volatile.  If we don't do this, we will
10238   // insert a new volatile load and the old ones will not be deletable.
10239   if (isVolatile)
10240     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10241       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10242   
10243   return new LoadInst(PhiVal, "", isVolatile);
10244 }
10245
10246 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10247 /// that is dead.
10248 static bool DeadPHICycle(PHINode *PN,
10249                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10250   if (PN->use_empty()) return true;
10251   if (!PN->hasOneUse()) return false;
10252
10253   // Remember this node, and if we find the cycle, return.
10254   if (!PotentiallyDeadPHIs.insert(PN))
10255     return true;
10256   
10257   // Don't scan crazily complex things.
10258   if (PotentiallyDeadPHIs.size() == 16)
10259     return false;
10260
10261   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10262     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10263
10264   return false;
10265 }
10266
10267 /// PHIsEqualValue - Return true if this phi node is always equal to
10268 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10269 ///   z = some value; x = phi (y, z); y = phi (x, z)
10270 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10271                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10272   // See if we already saw this PHI node.
10273   if (!ValueEqualPHIs.insert(PN))
10274     return true;
10275   
10276   // Don't scan crazily complex things.
10277   if (ValueEqualPHIs.size() == 16)
10278     return false;
10279  
10280   // Scan the operands to see if they are either phi nodes or are equal to
10281   // the value.
10282   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10283     Value *Op = PN->getIncomingValue(i);
10284     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10285       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10286         return false;
10287     } else if (Op != NonPhiInVal)
10288       return false;
10289   }
10290   
10291   return true;
10292 }
10293
10294
10295 // PHINode simplification
10296 //
10297 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10298   // If LCSSA is around, don't mess with Phi nodes
10299   if (MustPreserveLCSSA) return 0;
10300   
10301   if (Value *V = PN.hasConstantValue())
10302     return ReplaceInstUsesWith(PN, V);
10303
10304   // If all PHI operands are the same operation, pull them through the PHI,
10305   // reducing code size.
10306   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10307       isa<Instruction>(PN.getIncomingValue(1)) &&
10308       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10309       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10310       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10311       // than themselves more than once.
10312       PN.getIncomingValue(0)->hasOneUse())
10313     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10314       return Result;
10315
10316   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10317   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10318   // PHI)... break the cycle.
10319   if (PN.hasOneUse()) {
10320     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10321     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10322       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10323       PotentiallyDeadPHIs.insert(&PN);
10324       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10325         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10326     }
10327    
10328     // If this phi has a single use, and if that use just computes a value for
10329     // the next iteration of a loop, delete the phi.  This occurs with unused
10330     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10331     // common case here is good because the only other things that catch this
10332     // are induction variable analysis (sometimes) and ADCE, which is only run
10333     // late.
10334     if (PHIUser->hasOneUse() &&
10335         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10336         PHIUser->use_back() == &PN) {
10337       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10338     }
10339   }
10340
10341   // We sometimes end up with phi cycles that non-obviously end up being the
10342   // same value, for example:
10343   //   z = some value; x = phi (y, z); y = phi (x, z)
10344   // where the phi nodes don't necessarily need to be in the same block.  Do a
10345   // quick check to see if the PHI node only contains a single non-phi value, if
10346   // so, scan to see if the phi cycle is actually equal to that value.
10347   {
10348     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10349     // Scan for the first non-phi operand.
10350     while (InValNo != NumOperandVals && 
10351            isa<PHINode>(PN.getIncomingValue(InValNo)))
10352       ++InValNo;
10353
10354     if (InValNo != NumOperandVals) {
10355       Value *NonPhiInVal = PN.getOperand(InValNo);
10356       
10357       // Scan the rest of the operands to see if there are any conflicts, if so
10358       // there is no need to recursively scan other phis.
10359       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10360         Value *OpVal = PN.getIncomingValue(InValNo);
10361         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10362           break;
10363       }
10364       
10365       // If we scanned over all operands, then we have one unique value plus
10366       // phi values.  Scan PHI nodes to see if they all merge in each other or
10367       // the value.
10368       if (InValNo == NumOperandVals) {
10369         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10370         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10371           return ReplaceInstUsesWith(PN, NonPhiInVal);
10372       }
10373     }
10374   }
10375   return 0;
10376 }
10377
10378 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10379                                    Instruction *InsertPoint,
10380                                    InstCombiner *IC) {
10381   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10382   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10383   // We must cast correctly to the pointer type. Ensure that we
10384   // sign extend the integer value if it is smaller as this is
10385   // used for address computation.
10386   Instruction::CastOps opcode = 
10387      (VTySize < PtrSize ? Instruction::SExt :
10388       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10389   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10390 }
10391
10392
10393 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10394   Value *PtrOp = GEP.getOperand(0);
10395   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10396   // If so, eliminate the noop.
10397   if (GEP.getNumOperands() == 1)
10398     return ReplaceInstUsesWith(GEP, PtrOp);
10399
10400   if (isa<UndefValue>(GEP.getOperand(0)))
10401     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10402
10403   bool HasZeroPointerIndex = false;
10404   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10405     HasZeroPointerIndex = C->isNullValue();
10406
10407   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10408     return ReplaceInstUsesWith(GEP, PtrOp);
10409
10410   // Eliminate unneeded casts for indices.
10411   bool MadeChange = false;
10412   
10413   gep_type_iterator GTI = gep_type_begin(GEP);
10414   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10415        i != e; ++i, ++GTI) {
10416     if (isa<SequentialType>(*GTI)) {
10417       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10418         if (CI->getOpcode() == Instruction::ZExt ||
10419             CI->getOpcode() == Instruction::SExt) {
10420           const Type *SrcTy = CI->getOperand(0)->getType();
10421           // We can eliminate a cast from i32 to i64 iff the target 
10422           // is a 32-bit pointer target.
10423           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10424             MadeChange = true;
10425             *i = CI->getOperand(0);
10426           }
10427         }
10428       }
10429       // If we are using a wider index than needed for this platform, shrink it
10430       // to what we need.  If narrower, sign-extend it to what we need.
10431       // If the incoming value needs a cast instruction,
10432       // insert it.  This explicit cast can make subsequent optimizations more
10433       // obvious.
10434       Value *Op = *i;
10435       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10436         if (Constant *C = dyn_cast<Constant>(Op)) {
10437           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10438           MadeChange = true;
10439         } else {
10440           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10441                                 GEP);
10442           *i = Op;
10443           MadeChange = true;
10444         }
10445       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10446         if (Constant *C = dyn_cast<Constant>(Op)) {
10447           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10448           MadeChange = true;
10449         } else {
10450           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10451                                 GEP);
10452           *i = Op;
10453           MadeChange = true;
10454         }
10455       }
10456     }
10457   }
10458   if (MadeChange) return &GEP;
10459
10460   // If this GEP instruction doesn't move the pointer, and if the input operand
10461   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10462   // real input to the dest type.
10463   if (GEP.hasAllZeroIndices()) {
10464     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10465       // If the bitcast is of an allocation, and the allocation will be
10466       // converted to match the type of the cast, don't touch this.
10467       if (isa<AllocationInst>(BCI->getOperand(0))) {
10468         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10469         if (Instruction *I = visitBitCast(*BCI)) {
10470           if (I != BCI) {
10471             I->takeName(BCI);
10472             BCI->getParent()->getInstList().insert(BCI, I);
10473             ReplaceInstUsesWith(*BCI, I);
10474           }
10475           return &GEP;
10476         }
10477       }
10478       return new BitCastInst(BCI->getOperand(0), GEP.getType());
10479     }
10480   }
10481   
10482   // Combine Indices - If the source pointer to this getelementptr instruction
10483   // is a getelementptr instruction, combine the indices of the two
10484   // getelementptr instructions into a single instruction.
10485   //
10486   SmallVector<Value*, 8> SrcGEPOperands;
10487   if (User *Src = dyn_castGetElementPtr(PtrOp))
10488     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10489
10490   if (!SrcGEPOperands.empty()) {
10491     // Note that if our source is a gep chain itself that we wait for that
10492     // chain to be resolved before we perform this transformation.  This
10493     // avoids us creating a TON of code in some cases.
10494     //
10495     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10496         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10497       return 0;   // Wait until our source is folded to completion.
10498
10499     SmallVector<Value*, 8> Indices;
10500
10501     // Find out whether the last index in the source GEP is a sequential idx.
10502     bool EndsWithSequential = false;
10503     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10504            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10505       EndsWithSequential = !isa<StructType>(*I);
10506
10507     // Can we combine the two pointer arithmetics offsets?
10508     if (EndsWithSequential) {
10509       // Replace: gep (gep %P, long B), long A, ...
10510       // With:    T = long A+B; gep %P, T, ...
10511       //
10512       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10513       if (SO1 == Constant::getNullValue(SO1->getType())) {
10514         Sum = GO1;
10515       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10516         Sum = SO1;
10517       } else {
10518         // If they aren't the same type, convert both to an integer of the
10519         // target's pointer size.
10520         if (SO1->getType() != GO1->getType()) {
10521           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10522             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10523           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10524             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10525           } else {
10526             unsigned PS = TD->getPointerSizeInBits();
10527             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10528               // Convert GO1 to SO1's type.
10529               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10530
10531             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10532               // Convert SO1 to GO1's type.
10533               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10534             } else {
10535               const Type *PT = TD->getIntPtrType();
10536               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10537               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10538             }
10539           }
10540         }
10541         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10542           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10543         else {
10544           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10545           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10546         }
10547       }
10548
10549       // Recycle the GEP we already have if possible.
10550       if (SrcGEPOperands.size() == 2) {
10551         GEP.setOperand(0, SrcGEPOperands[0]);
10552         GEP.setOperand(1, Sum);
10553         return &GEP;
10554       } else {
10555         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10556                        SrcGEPOperands.end()-1);
10557         Indices.push_back(Sum);
10558         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10559       }
10560     } else if (isa<Constant>(*GEP.idx_begin()) &&
10561                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10562                SrcGEPOperands.size() != 1) {
10563       // Otherwise we can do the fold if the first index of the GEP is a zero
10564       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10565                      SrcGEPOperands.end());
10566       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10567     }
10568
10569     if (!Indices.empty())
10570       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10571                                        Indices.end(), GEP.getName());
10572
10573   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10574     // GEP of global variable.  If all of the indices for this GEP are
10575     // constants, we can promote this to a constexpr instead of an instruction.
10576
10577     // Scan for nonconstants...
10578     SmallVector<Constant*, 8> Indices;
10579     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10580     for (; I != E && isa<Constant>(*I); ++I)
10581       Indices.push_back(cast<Constant>(*I));
10582
10583     if (I == E) {  // If they are all constants...
10584       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10585                                                     &Indices[0],Indices.size());
10586
10587       // Replace all uses of the GEP with the new constexpr...
10588       return ReplaceInstUsesWith(GEP, CE);
10589     }
10590   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10591     if (!isa<PointerType>(X->getType())) {
10592       // Not interesting.  Source pointer must be a cast from pointer.
10593     } else if (HasZeroPointerIndex) {
10594       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10595       // into     : GEP [10 x i8]* X, i32 0, ...
10596       //
10597       // This occurs when the program declares an array extern like "int X[];"
10598       //
10599       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10600       const PointerType *XTy = cast<PointerType>(X->getType());
10601       if (const ArrayType *XATy =
10602           dyn_cast<ArrayType>(XTy->getElementType()))
10603         if (const ArrayType *CATy =
10604             dyn_cast<ArrayType>(CPTy->getElementType()))
10605           if (CATy->getElementType() == XATy->getElementType()) {
10606             // At this point, we know that the cast source type is a pointer
10607             // to an array of the same type as the destination pointer
10608             // array.  Because the array type is never stepped over (there
10609             // is a leading zero) we can fold the cast into this GEP.
10610             GEP.setOperand(0, X);
10611             return &GEP;
10612           }
10613     } else if (GEP.getNumOperands() == 2) {
10614       // Transform things like:
10615       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10616       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10617       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10618       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10619       if (isa<ArrayType>(SrcElTy) &&
10620           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10621           TD->getABITypeSize(ResElTy)) {
10622         Value *Idx[2];
10623         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10624         Idx[1] = GEP.getOperand(1);
10625         Value *V = InsertNewInstBefore(
10626                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10627         // V and GEP are both pointer types --> BitCast
10628         return new BitCastInst(V, GEP.getType());
10629       }
10630       
10631       // Transform things like:
10632       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10633       //   (where tmp = 8*tmp2) into:
10634       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10635       
10636       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10637         uint64_t ArrayEltSize =
10638             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
10639         
10640         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10641         // allow either a mul, shift, or constant here.
10642         Value *NewIdx = 0;
10643         ConstantInt *Scale = 0;
10644         if (ArrayEltSize == 1) {
10645           NewIdx = GEP.getOperand(1);
10646           Scale = ConstantInt::get(NewIdx->getType(), 1);
10647         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10648           NewIdx = ConstantInt::get(CI->getType(), 1);
10649           Scale = CI;
10650         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10651           if (Inst->getOpcode() == Instruction::Shl &&
10652               isa<ConstantInt>(Inst->getOperand(1))) {
10653             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10654             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10655             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10656             NewIdx = Inst->getOperand(0);
10657           } else if (Inst->getOpcode() == Instruction::Mul &&
10658                      isa<ConstantInt>(Inst->getOperand(1))) {
10659             Scale = cast<ConstantInt>(Inst->getOperand(1));
10660             NewIdx = Inst->getOperand(0);
10661           }
10662         }
10663         
10664         // If the index will be to exactly the right offset with the scale taken
10665         // out, perform the transformation. Note, we don't know whether Scale is
10666         // signed or not. We'll use unsigned version of division/modulo
10667         // operation after making sure Scale doesn't have the sign bit set.
10668         if (Scale && Scale->getSExtValue() >= 0LL &&
10669             Scale->getZExtValue() % ArrayEltSize == 0) {
10670           Scale = ConstantInt::get(Scale->getType(),
10671                                    Scale->getZExtValue() / ArrayEltSize);
10672           if (Scale->getZExtValue() != 1) {
10673             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10674                                                        false /*ZExt*/);
10675             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10676             NewIdx = InsertNewInstBefore(Sc, GEP);
10677           }
10678
10679           // Insert the new GEP instruction.
10680           Value *Idx[2];
10681           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10682           Idx[1] = NewIdx;
10683           Instruction *NewGEP =
10684             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10685           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10686           // The NewGEP must be pointer typed, so must the old one -> BitCast
10687           return new BitCastInst(NewGEP, GEP.getType());
10688         }
10689       }
10690     }
10691   }
10692
10693   return 0;
10694 }
10695
10696 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10697   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10698   if (AI.isArrayAllocation()) {  // Check C != 1
10699     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10700       const Type *NewTy = 
10701         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10702       AllocationInst *New = 0;
10703
10704       // Create and insert the replacement instruction...
10705       if (isa<MallocInst>(AI))
10706         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10707       else {
10708         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10709         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10710       }
10711
10712       InsertNewInstBefore(New, AI);
10713
10714       // Scan to the end of the allocation instructions, to skip over a block of
10715       // allocas if possible...
10716       //
10717       BasicBlock::iterator It = New;
10718       while (isa<AllocationInst>(*It)) ++It;
10719
10720       // Now that I is pointing to the first non-allocation-inst in the block,
10721       // insert our getelementptr instruction...
10722       //
10723       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10724       Value *Idx[2];
10725       Idx[0] = NullIdx;
10726       Idx[1] = NullIdx;
10727       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10728                                            New->getName()+".sub", It);
10729
10730       // Now make everything use the getelementptr instead of the original
10731       // allocation.
10732       return ReplaceInstUsesWith(AI, V);
10733     } else if (isa<UndefValue>(AI.getArraySize())) {
10734       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10735     }
10736   }
10737
10738   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10739   // Note that we only do this for alloca's, because malloc should allocate and
10740   // return a unique pointer, even for a zero byte allocation.
10741   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
10742       TD->getABITypeSize(AI.getAllocatedType()) == 0)
10743     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10744
10745   return 0;
10746 }
10747
10748 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10749   Value *Op = FI.getOperand(0);
10750
10751   // free undef -> unreachable.
10752   if (isa<UndefValue>(Op)) {
10753     // Insert a new store to null because we cannot modify the CFG here.
10754     new StoreInst(ConstantInt::getTrue(),
10755                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10756     return EraseInstFromFunction(FI);
10757   }
10758   
10759   // If we have 'free null' delete the instruction.  This can happen in stl code
10760   // when lots of inlining happens.
10761   if (isa<ConstantPointerNull>(Op))
10762     return EraseInstFromFunction(FI);
10763   
10764   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10765   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10766     FI.setOperand(0, CI->getOperand(0));
10767     return &FI;
10768   }
10769   
10770   // Change free (gep X, 0,0,0,0) into free(X)
10771   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10772     if (GEPI->hasAllZeroIndices()) {
10773       AddToWorkList(GEPI);
10774       FI.setOperand(0, GEPI->getOperand(0));
10775       return &FI;
10776     }
10777   }
10778   
10779   // Change free(malloc) into nothing, if the malloc has a single use.
10780   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10781     if (MI->hasOneUse()) {
10782       EraseInstFromFunction(FI);
10783       return EraseInstFromFunction(*MI);
10784     }
10785
10786   return 0;
10787 }
10788
10789
10790 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10791 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10792                                         const TargetData *TD) {
10793   User *CI = cast<User>(LI.getOperand(0));
10794   Value *CastOp = CI->getOperand(0);
10795
10796   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10797     // Instead of loading constant c string, use corresponding integer value
10798     // directly if string length is small enough.
10799     std::string Str;
10800     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10801       unsigned len = Str.length();
10802       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10803       unsigned numBits = Ty->getPrimitiveSizeInBits();
10804       // Replace LI with immediate integer store.
10805       if ((numBits >> 3) == len + 1) {
10806         APInt StrVal(numBits, 0);
10807         APInt SingleChar(numBits, 0);
10808         if (TD->isLittleEndian()) {
10809           for (signed i = len-1; i >= 0; i--) {
10810             SingleChar = (uint64_t) Str[i];
10811             StrVal = (StrVal << 8) | SingleChar;
10812           }
10813         } else {
10814           for (unsigned i = 0; i < len; i++) {
10815             SingleChar = (uint64_t) Str[i];
10816             StrVal = (StrVal << 8) | SingleChar;
10817           }
10818           // Append NULL at the end.
10819           SingleChar = 0;
10820           StrVal = (StrVal << 8) | SingleChar;
10821         }
10822         Value *NL = ConstantInt::get(StrVal);
10823         return IC.ReplaceInstUsesWith(LI, NL);
10824       }
10825     }
10826   }
10827
10828   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10829   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10830     const Type *SrcPTy = SrcTy->getElementType();
10831
10832     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10833          isa<VectorType>(DestPTy)) {
10834       // If the source is an array, the code below will not succeed.  Check to
10835       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10836       // constants.
10837       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10838         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10839           if (ASrcTy->getNumElements() != 0) {
10840             Value *Idxs[2];
10841             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10842             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10843             SrcTy = cast<PointerType>(CastOp->getType());
10844             SrcPTy = SrcTy->getElementType();
10845           }
10846
10847       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10848             isa<VectorType>(SrcPTy)) &&
10849           // Do not allow turning this into a load of an integer, which is then
10850           // casted to a pointer, this pessimizes pointer analysis a lot.
10851           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10852           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10853                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10854
10855         // Okay, we are casting from one integer or pointer type to another of
10856         // the same size.  Instead of casting the pointer before the load, cast
10857         // the result of the loaded value.
10858         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10859                                                              CI->getName(),
10860                                                          LI.isVolatile()),LI);
10861         // Now cast the result of the load.
10862         return new BitCastInst(NewLoad, LI.getType());
10863       }
10864     }
10865   }
10866   return 0;
10867 }
10868
10869 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10870 /// from this value cannot trap.  If it is not obviously safe to load from the
10871 /// specified pointer, we do a quick local scan of the basic block containing
10872 /// ScanFrom, to determine if the address is already accessed.
10873 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10874   // If it is an alloca it is always safe to load from.
10875   if (isa<AllocaInst>(V)) return true;
10876
10877   // If it is a global variable it is mostly safe to load from.
10878   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10879     // Don't try to evaluate aliases.  External weak GV can be null.
10880     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10881
10882   // Otherwise, be a little bit agressive by scanning the local block where we
10883   // want to check to see if the pointer is already being loaded or stored
10884   // from/to.  If so, the previous load or store would have already trapped,
10885   // so there is no harm doing an extra load (also, CSE will later eliminate
10886   // the load entirely).
10887   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10888
10889   while (BBI != E) {
10890     --BBI;
10891
10892     // If we see a free or a call (which might do a free) the pointer could be
10893     // marked invalid.
10894     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10895       return false;
10896     
10897     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10898       if (LI->getOperand(0) == V) return true;
10899     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10900       if (SI->getOperand(1) == V) return true;
10901     }
10902
10903   }
10904   return false;
10905 }
10906
10907 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10908   Value *Op = LI.getOperand(0);
10909
10910   // Attempt to improve the alignment.
10911   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10912   if (KnownAlign >
10913       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10914                                 LI.getAlignment()))
10915     LI.setAlignment(KnownAlign);
10916
10917   // load (cast X) --> cast (load X) iff safe
10918   if (isa<CastInst>(Op))
10919     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10920       return Res;
10921
10922   // None of the following transforms are legal for volatile loads.
10923   if (LI.isVolatile()) return 0;
10924   
10925   // Do really simple store-to-load forwarding and load CSE, to catch cases
10926   // where there are several consequtive memory accesses to the same location,
10927   // separated by a few arithmetic operations.
10928   BasicBlock::iterator BBI = &LI;
10929   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
10930     return ReplaceInstUsesWith(LI, AvailableVal);
10931
10932   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10933     const Value *GEPI0 = GEPI->getOperand(0);
10934     // TODO: Consider a target hook for valid address spaces for this xform.
10935     if (isa<ConstantPointerNull>(GEPI0) &&
10936         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10937       // Insert a new store to null instruction before the load to indicate
10938       // that this code is not reachable.  We do this instead of inserting
10939       // an unreachable instruction directly because we cannot modify the
10940       // CFG.
10941       new StoreInst(UndefValue::get(LI.getType()),
10942                     Constant::getNullValue(Op->getType()), &LI);
10943       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10944     }
10945   } 
10946
10947   if (Constant *C = dyn_cast<Constant>(Op)) {
10948     // load null/undef -> undef
10949     // TODO: Consider a target hook for valid address spaces for this xform.
10950     if (isa<UndefValue>(C) || (C->isNullValue() && 
10951         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10952       // Insert a new store to null instruction before the load to indicate that
10953       // this code is not reachable.  We do this instead of inserting an
10954       // unreachable instruction directly because we cannot modify the CFG.
10955       new StoreInst(UndefValue::get(LI.getType()),
10956                     Constant::getNullValue(Op->getType()), &LI);
10957       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10958     }
10959
10960     // Instcombine load (constant global) into the value loaded.
10961     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10962       if (GV->isConstant() && !GV->isDeclaration())
10963         return ReplaceInstUsesWith(LI, GV->getInitializer());
10964
10965     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10966     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10967       if (CE->getOpcode() == Instruction::GetElementPtr) {
10968         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10969           if (GV->isConstant() && !GV->isDeclaration())
10970             if (Constant *V = 
10971                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10972               return ReplaceInstUsesWith(LI, V);
10973         if (CE->getOperand(0)->isNullValue()) {
10974           // Insert a new store to null instruction before the load to indicate
10975           // that this code is not reachable.  We do this instead of inserting
10976           // an unreachable instruction directly because we cannot modify the
10977           // CFG.
10978           new StoreInst(UndefValue::get(LI.getType()),
10979                         Constant::getNullValue(Op->getType()), &LI);
10980           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10981         }
10982
10983       } else if (CE->isCast()) {
10984         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10985           return Res;
10986       }
10987     }
10988   }
10989     
10990   // If this load comes from anywhere in a constant global, and if the global
10991   // is all undef or zero, we know what it loads.
10992   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
10993     if (GV->isConstant() && GV->hasInitializer()) {
10994       if (GV->getInitializer()->isNullValue())
10995         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10996       else if (isa<UndefValue>(GV->getInitializer()))
10997         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10998     }
10999   }
11000
11001   if (Op->hasOneUse()) {
11002     // Change select and PHI nodes to select values instead of addresses: this
11003     // helps alias analysis out a lot, allows many others simplifications, and
11004     // exposes redundancy in the code.
11005     //
11006     // Note that we cannot do the transformation unless we know that the
11007     // introduced loads cannot trap!  Something like this is valid as long as
11008     // the condition is always false: load (select bool %C, int* null, int* %G),
11009     // but it would not be valid if we transformed it to load from null
11010     // unconditionally.
11011     //
11012     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11013       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11014       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11015           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11016         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11017                                      SI->getOperand(1)->getName()+".val"), LI);
11018         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11019                                      SI->getOperand(2)->getName()+".val"), LI);
11020         return SelectInst::Create(SI->getCondition(), V1, V2);
11021       }
11022
11023       // load (select (cond, null, P)) -> load P
11024       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11025         if (C->isNullValue()) {
11026           LI.setOperand(0, SI->getOperand(2));
11027           return &LI;
11028         }
11029
11030       // load (select (cond, P, null)) -> load P
11031       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11032         if (C->isNullValue()) {
11033           LI.setOperand(0, SI->getOperand(1));
11034           return &LI;
11035         }
11036     }
11037   }
11038   return 0;
11039 }
11040
11041 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11042 /// when possible.
11043 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11044   User *CI = cast<User>(SI.getOperand(1));
11045   Value *CastOp = CI->getOperand(0);
11046
11047   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11048   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11049     const Type *SrcPTy = SrcTy->getElementType();
11050
11051     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
11052       // If the source is an array, the code below will not succeed.  Check to
11053       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11054       // constants.
11055       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11056         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11057           if (ASrcTy->getNumElements() != 0) {
11058             Value* Idxs[2];
11059             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11060             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11061             SrcTy = cast<PointerType>(CastOp->getType());
11062             SrcPTy = SrcTy->getElementType();
11063           }
11064
11065       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
11066           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11067                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11068
11069         // Okay, we are casting from one integer or pointer type to another of
11070         // the same size.  Instead of casting the pointer before 
11071         // the store, cast the value to be stored.
11072         Value *NewCast;
11073         Value *SIOp0 = SI.getOperand(0);
11074         Instruction::CastOps opcode = Instruction::BitCast;
11075         const Type* CastSrcTy = SIOp0->getType();
11076         const Type* CastDstTy = SrcPTy;
11077         if (isa<PointerType>(CastDstTy)) {
11078           if (CastSrcTy->isInteger())
11079             opcode = Instruction::IntToPtr;
11080         } else if (isa<IntegerType>(CastDstTy)) {
11081           if (isa<PointerType>(SIOp0->getType()))
11082             opcode = Instruction::PtrToInt;
11083         }
11084         if (Constant *C = dyn_cast<Constant>(SIOp0))
11085           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11086         else
11087           NewCast = IC.InsertNewInstBefore(
11088             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11089             SI);
11090         return new StoreInst(NewCast, CastOp);
11091       }
11092     }
11093   }
11094   return 0;
11095 }
11096
11097 /// equivalentAddressValues - Test if A and B will obviously have the same
11098 /// value. This includes recognizing that %t0 and %t1 will have the same
11099 /// value in code like this:
11100 ///   %t0 = getelementptr @a, 0, 3
11101 ///   store i32 0, i32* %t0
11102 ///   %t1 = getelementptr @a, 0, 3
11103 ///   %t2 = load i32* %t1
11104 ///
11105 static bool equivalentAddressValues(Value *A, Value *B) {
11106   // Test if the values are trivially equivalent.
11107   if (A == B) return true;
11108   
11109   // Test if the values come form identical arithmetic instructions.
11110   if (isa<BinaryOperator>(A) ||
11111       isa<CastInst>(A) ||
11112       isa<PHINode>(A) ||
11113       isa<GetElementPtrInst>(A))
11114     if (Instruction *BI = dyn_cast<Instruction>(B))
11115       if (cast<Instruction>(A)->isIdenticalTo(BI))
11116         return true;
11117   
11118   // Otherwise they may not be equivalent.
11119   return false;
11120 }
11121
11122 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11123   Value *Val = SI.getOperand(0);
11124   Value *Ptr = SI.getOperand(1);
11125
11126   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11127     EraseInstFromFunction(SI);
11128     ++NumCombined;
11129     return 0;
11130   }
11131   
11132   // If the RHS is an alloca with a single use, zapify the store, making the
11133   // alloca dead.
11134   if (Ptr->hasOneUse() && !SI.isVolatile()) {
11135     if (isa<AllocaInst>(Ptr)) {
11136       EraseInstFromFunction(SI);
11137       ++NumCombined;
11138       return 0;
11139     }
11140     
11141     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11142       if (isa<AllocaInst>(GEP->getOperand(0)) &&
11143           GEP->getOperand(0)->hasOneUse()) {
11144         EraseInstFromFunction(SI);
11145         ++NumCombined;
11146         return 0;
11147       }
11148   }
11149
11150   // Attempt to improve the alignment.
11151   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11152   if (KnownAlign >
11153       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11154                                 SI.getAlignment()))
11155     SI.setAlignment(KnownAlign);
11156
11157   // Do really simple DSE, to catch cases where there are several consequtive
11158   // stores to the same location, separated by a few arithmetic operations. This
11159   // situation often occurs with bitfield accesses.
11160   BasicBlock::iterator BBI = &SI;
11161   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11162        --ScanInsts) {
11163     --BBI;
11164     
11165     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11166       // Prev store isn't volatile, and stores to the same location?
11167       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11168                                                           SI.getOperand(1))) {
11169         ++NumDeadStore;
11170         ++BBI;
11171         EraseInstFromFunction(*PrevSI);
11172         continue;
11173       }
11174       break;
11175     }
11176     
11177     // If this is a load, we have to stop.  However, if the loaded value is from
11178     // the pointer we're loading and is producing the pointer we're storing,
11179     // then *this* store is dead (X = load P; store X -> P).
11180     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11181       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11182           !SI.isVolatile()) {
11183         EraseInstFromFunction(SI);
11184         ++NumCombined;
11185         return 0;
11186       }
11187       // Otherwise, this is a load from some other location.  Stores before it
11188       // may not be dead.
11189       break;
11190     }
11191     
11192     // Don't skip over loads or things that can modify memory.
11193     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11194       break;
11195   }
11196   
11197   
11198   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11199
11200   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11201   if (isa<ConstantPointerNull>(Ptr)) {
11202     if (!isa<UndefValue>(Val)) {
11203       SI.setOperand(0, UndefValue::get(Val->getType()));
11204       if (Instruction *U = dyn_cast<Instruction>(Val))
11205         AddToWorkList(U);  // Dropped a use.
11206       ++NumCombined;
11207     }
11208     return 0;  // Do not modify these!
11209   }
11210
11211   // store undef, Ptr -> noop
11212   if (isa<UndefValue>(Val)) {
11213     EraseInstFromFunction(SI);
11214     ++NumCombined;
11215     return 0;
11216   }
11217
11218   // If the pointer destination is a cast, see if we can fold the cast into the
11219   // source instead.
11220   if (isa<CastInst>(Ptr))
11221     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11222       return Res;
11223   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11224     if (CE->isCast())
11225       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11226         return Res;
11227
11228   
11229   // If this store is the last instruction in the basic block, and if the block
11230   // ends with an unconditional branch, try to move it to the successor block.
11231   BBI = &SI; ++BBI;
11232   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11233     if (BI->isUnconditional())
11234       if (SimplifyStoreAtEndOfBlock(SI))
11235         return 0;  // xform done!
11236   
11237   return 0;
11238 }
11239
11240 /// SimplifyStoreAtEndOfBlock - Turn things like:
11241 ///   if () { *P = v1; } else { *P = v2 }
11242 /// into a phi node with a store in the successor.
11243 ///
11244 /// Simplify things like:
11245 ///   *P = v1; if () { *P = v2; }
11246 /// into a phi node with a store in the successor.
11247 ///
11248 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11249   BasicBlock *StoreBB = SI.getParent();
11250   
11251   // Check to see if the successor block has exactly two incoming edges.  If
11252   // so, see if the other predecessor contains a store to the same location.
11253   // if so, insert a PHI node (if needed) and move the stores down.
11254   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11255   
11256   // Determine whether Dest has exactly two predecessors and, if so, compute
11257   // the other predecessor.
11258   pred_iterator PI = pred_begin(DestBB);
11259   BasicBlock *OtherBB = 0;
11260   if (*PI != StoreBB)
11261     OtherBB = *PI;
11262   ++PI;
11263   if (PI == pred_end(DestBB))
11264     return false;
11265   
11266   if (*PI != StoreBB) {
11267     if (OtherBB)
11268       return false;
11269     OtherBB = *PI;
11270   }
11271   if (++PI != pred_end(DestBB))
11272     return false;
11273
11274   // Bail out if all the relevant blocks aren't distinct (this can happen,
11275   // for example, if SI is in an infinite loop)
11276   if (StoreBB == DestBB || OtherBB == DestBB)
11277     return false;
11278
11279   // Verify that the other block ends in a branch and is not otherwise empty.
11280   BasicBlock::iterator BBI = OtherBB->getTerminator();
11281   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11282   if (!OtherBr || BBI == OtherBB->begin())
11283     return false;
11284   
11285   // If the other block ends in an unconditional branch, check for the 'if then
11286   // else' case.  there is an instruction before the branch.
11287   StoreInst *OtherStore = 0;
11288   if (OtherBr->isUnconditional()) {
11289     // If this isn't a store, or isn't a store to the same location, bail out.
11290     --BBI;
11291     OtherStore = dyn_cast<StoreInst>(BBI);
11292     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11293       return false;
11294   } else {
11295     // Otherwise, the other block ended with a conditional branch. If one of the
11296     // destinations is StoreBB, then we have the if/then case.
11297     if (OtherBr->getSuccessor(0) != StoreBB && 
11298         OtherBr->getSuccessor(1) != StoreBB)
11299       return false;
11300     
11301     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11302     // if/then triangle.  See if there is a store to the same ptr as SI that
11303     // lives in OtherBB.
11304     for (;; --BBI) {
11305       // Check to see if we find the matching store.
11306       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11307         if (OtherStore->getOperand(1) != SI.getOperand(1))
11308           return false;
11309         break;
11310       }
11311       // If we find something that may be using or overwriting the stored
11312       // value, or if we run out of instructions, we can't do the xform.
11313       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11314           BBI == OtherBB->begin())
11315         return false;
11316     }
11317     
11318     // In order to eliminate the store in OtherBr, we have to
11319     // make sure nothing reads or overwrites the stored value in
11320     // StoreBB.
11321     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11322       // FIXME: This should really be AA driven.
11323       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11324         return false;
11325     }
11326   }
11327   
11328   // Insert a PHI node now if we need it.
11329   Value *MergedVal = OtherStore->getOperand(0);
11330   if (MergedVal != SI.getOperand(0)) {
11331     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11332     PN->reserveOperandSpace(2);
11333     PN->addIncoming(SI.getOperand(0), SI.getParent());
11334     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11335     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11336   }
11337   
11338   // Advance to a place where it is safe to insert the new store and
11339   // insert it.
11340   BBI = DestBB->getFirstNonPHI();
11341   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11342                                     OtherStore->isVolatile()), *BBI);
11343   
11344   // Nuke the old stores.
11345   EraseInstFromFunction(SI);
11346   EraseInstFromFunction(*OtherStore);
11347   ++NumCombined;
11348   return true;
11349 }
11350
11351
11352 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11353   // Change br (not X), label True, label False to: br X, label False, True
11354   Value *X = 0;
11355   BasicBlock *TrueDest;
11356   BasicBlock *FalseDest;
11357   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11358       !isa<Constant>(X)) {
11359     // Swap Destinations and condition...
11360     BI.setCondition(X);
11361     BI.setSuccessor(0, FalseDest);
11362     BI.setSuccessor(1, TrueDest);
11363     return &BI;
11364   }
11365
11366   // Cannonicalize fcmp_one -> fcmp_oeq
11367   FCmpInst::Predicate FPred; Value *Y;
11368   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11369                              TrueDest, FalseDest)))
11370     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11371          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11372       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11373       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11374       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11375       NewSCC->takeName(I);
11376       // Swap Destinations and condition...
11377       BI.setCondition(NewSCC);
11378       BI.setSuccessor(0, FalseDest);
11379       BI.setSuccessor(1, TrueDest);
11380       RemoveFromWorkList(I);
11381       I->eraseFromParent();
11382       AddToWorkList(NewSCC);
11383       return &BI;
11384     }
11385
11386   // Cannonicalize icmp_ne -> icmp_eq
11387   ICmpInst::Predicate IPred;
11388   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11389                       TrueDest, FalseDest)))
11390     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11391          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11392          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11393       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11394       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11395       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11396       NewSCC->takeName(I);
11397       // Swap Destinations and condition...
11398       BI.setCondition(NewSCC);
11399       BI.setSuccessor(0, FalseDest);
11400       BI.setSuccessor(1, TrueDest);
11401       RemoveFromWorkList(I);
11402       I->eraseFromParent();;
11403       AddToWorkList(NewSCC);
11404       return &BI;
11405     }
11406
11407   return 0;
11408 }
11409
11410 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11411   Value *Cond = SI.getCondition();
11412   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11413     if (I->getOpcode() == Instruction::Add)
11414       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11415         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11416         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11417           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11418                                                 AddRHS));
11419         SI.setOperand(0, I->getOperand(0));
11420         AddToWorkList(I);
11421         return &SI;
11422       }
11423   }
11424   return 0;
11425 }
11426
11427 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11428   Value *Agg = EV.getAggregateOperand();
11429
11430   if (!EV.hasIndices())
11431     return ReplaceInstUsesWith(EV, Agg);
11432
11433   if (Constant *C = dyn_cast<Constant>(Agg)) {
11434     if (isa<UndefValue>(C))
11435       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11436       
11437     if (isa<ConstantAggregateZero>(C))
11438       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11439
11440     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11441       // Extract the element indexed by the first index out of the constant
11442       Value *V = C->getOperand(*EV.idx_begin());
11443       if (EV.getNumIndices() > 1)
11444         // Extract the remaining indices out of the constant indexed by the
11445         // first index
11446         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11447       else
11448         return ReplaceInstUsesWith(EV, V);
11449     }
11450     return 0; // Can't handle other constants
11451   } 
11452   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11453     // We're extracting from an insertvalue instruction, compare the indices
11454     const unsigned *exti, *exte, *insi, *inse;
11455     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11456          exte = EV.idx_end(), inse = IV->idx_end();
11457          exti != exte && insi != inse;
11458          ++exti, ++insi) {
11459       if (*insi != *exti)
11460         // The insert and extract both reference distinctly different elements.
11461         // This means the extract is not influenced by the insert, and we can
11462         // replace the aggregate operand of the extract with the aggregate
11463         // operand of the insert. i.e., replace
11464         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11465         // %E = extractvalue { i32, { i32 } } %I, 0
11466         // with
11467         // %E = extractvalue { i32, { i32 } } %A, 0
11468         return ExtractValueInst::Create(IV->getAggregateOperand(),
11469                                         EV.idx_begin(), EV.idx_end());
11470     }
11471     if (exti == exte && insi == inse)
11472       // Both iterators are at the end: Index lists are identical. Replace
11473       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11474       // %C = extractvalue { i32, { i32 } } %B, 1, 0
11475       // with "i32 42"
11476       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11477     if (exti == exte) {
11478       // The extract list is a prefix of the insert list. i.e. replace
11479       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11480       // %E = extractvalue { i32, { i32 } } %I, 1
11481       // with
11482       // %X = extractvalue { i32, { i32 } } %A, 1
11483       // %E = insertvalue { i32 } %X, i32 42, 0
11484       // by switching the order of the insert and extract (though the
11485       // insertvalue should be left in, since it may have other uses).
11486       Value *NewEV = InsertNewInstBefore(
11487         ExtractValueInst::Create(IV->getAggregateOperand(),
11488                                  EV.idx_begin(), EV.idx_end()),
11489         EV);
11490       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11491                                      insi, inse);
11492     }
11493     if (insi == inse)
11494       // The insert list is a prefix of the extract list
11495       // We can simply remove the common indices from the extract and make it
11496       // operate on the inserted value instead of the insertvalue result.
11497       // i.e., replace
11498       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11499       // %E = extractvalue { i32, { i32 } } %I, 1, 0
11500       // with
11501       // %E extractvalue { i32 } { i32 42 }, 0
11502       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
11503                                       exti, exte);
11504   }
11505   // Can't simplify extracts from other values. Note that nested extracts are
11506   // already simplified implicitely by the above (extract ( extract (insert) )
11507   // will be translated into extract ( insert ( extract ) ) first and then just
11508   // the value inserted, if appropriate).
11509   return 0;
11510 }
11511
11512 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11513 /// is to leave as a vector operation.
11514 static bool CheapToScalarize(Value *V, bool isConstant) {
11515   if (isa<ConstantAggregateZero>(V)) 
11516     return true;
11517   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11518     if (isConstant) return true;
11519     // If all elts are the same, we can extract.
11520     Constant *Op0 = C->getOperand(0);
11521     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11522       if (C->getOperand(i) != Op0)
11523         return false;
11524     return true;
11525   }
11526   Instruction *I = dyn_cast<Instruction>(V);
11527   if (!I) return false;
11528   
11529   // Insert element gets simplified to the inserted element or is deleted if
11530   // this is constant idx extract element and its a constant idx insertelt.
11531   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11532       isa<ConstantInt>(I->getOperand(2)))
11533     return true;
11534   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11535     return true;
11536   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11537     if (BO->hasOneUse() &&
11538         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11539          CheapToScalarize(BO->getOperand(1), isConstant)))
11540       return true;
11541   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11542     if (CI->hasOneUse() &&
11543         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11544          CheapToScalarize(CI->getOperand(1), isConstant)))
11545       return true;
11546   
11547   return false;
11548 }
11549
11550 /// Read and decode a shufflevector mask.
11551 ///
11552 /// It turns undef elements into values that are larger than the number of
11553 /// elements in the input.
11554 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11555   unsigned NElts = SVI->getType()->getNumElements();
11556   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11557     return std::vector<unsigned>(NElts, 0);
11558   if (isa<UndefValue>(SVI->getOperand(2)))
11559     return std::vector<unsigned>(NElts, 2*NElts);
11560
11561   std::vector<unsigned> Result;
11562   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11563   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11564     if (isa<UndefValue>(*i))
11565       Result.push_back(NElts*2);  // undef -> 8
11566     else
11567       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
11568   return Result;
11569 }
11570
11571 /// FindScalarElement - Given a vector and an element number, see if the scalar
11572 /// value is already around as a register, for example if it were inserted then
11573 /// extracted from the vector.
11574 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11575   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11576   const VectorType *PTy = cast<VectorType>(V->getType());
11577   unsigned Width = PTy->getNumElements();
11578   if (EltNo >= Width)  // Out of range access.
11579     return UndefValue::get(PTy->getElementType());
11580   
11581   if (isa<UndefValue>(V))
11582     return UndefValue::get(PTy->getElementType());
11583   else if (isa<ConstantAggregateZero>(V))
11584     return Constant::getNullValue(PTy->getElementType());
11585   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11586     return CP->getOperand(EltNo);
11587   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11588     // If this is an insert to a variable element, we don't know what it is.
11589     if (!isa<ConstantInt>(III->getOperand(2))) 
11590       return 0;
11591     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11592     
11593     // If this is an insert to the element we are looking for, return the
11594     // inserted value.
11595     if (EltNo == IIElt) 
11596       return III->getOperand(1);
11597     
11598     // Otherwise, the insertelement doesn't modify the value, recurse on its
11599     // vector input.
11600     return FindScalarElement(III->getOperand(0), EltNo);
11601   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11602     unsigned LHSWidth =
11603       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11604     unsigned InEl = getShuffleMask(SVI)[EltNo];
11605     if (InEl < LHSWidth)
11606       return FindScalarElement(SVI->getOperand(0), InEl);
11607     else if (InEl < LHSWidth*2)
11608       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
11609     else
11610       return UndefValue::get(PTy->getElementType());
11611   }
11612   
11613   // Otherwise, we don't know.
11614   return 0;
11615 }
11616
11617 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11618   // If vector val is undef, replace extract with scalar undef.
11619   if (isa<UndefValue>(EI.getOperand(0)))
11620     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11621
11622   // If vector val is constant 0, replace extract with scalar 0.
11623   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11624     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11625   
11626   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11627     // If vector val is constant with all elements the same, replace EI with
11628     // that element. When the elements are not identical, we cannot replace yet
11629     // (we do that below, but only when the index is constant).
11630     Constant *op0 = C->getOperand(0);
11631     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11632       if (C->getOperand(i) != op0) {
11633         op0 = 0; 
11634         break;
11635       }
11636     if (op0)
11637       return ReplaceInstUsesWith(EI, op0);
11638   }
11639   
11640   // If extracting a specified index from the vector, see if we can recursively
11641   // find a previously computed scalar that was inserted into the vector.
11642   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11643     unsigned IndexVal = IdxC->getZExtValue();
11644     unsigned VectorWidth = 
11645       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11646       
11647     // If this is extracting an invalid index, turn this into undef, to avoid
11648     // crashing the code below.
11649     if (IndexVal >= VectorWidth)
11650       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11651     
11652     // This instruction only demands the single element from the input vector.
11653     // If the input vector has a single use, simplify it based on this use
11654     // property.
11655     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11656       uint64_t UndefElts;
11657       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11658                                                 1 << IndexVal,
11659                                                 UndefElts)) {
11660         EI.setOperand(0, V);
11661         return &EI;
11662       }
11663     }
11664     
11665     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11666       return ReplaceInstUsesWith(EI, Elt);
11667     
11668     // If the this extractelement is directly using a bitcast from a vector of
11669     // the same number of elements, see if we can find the source element from
11670     // it.  In this case, we will end up needing to bitcast the scalars.
11671     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11672       if (const VectorType *VT = 
11673               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11674         if (VT->getNumElements() == VectorWidth)
11675           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11676             return new BitCastInst(Elt, EI.getType());
11677     }
11678   }
11679   
11680   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11681     if (I->hasOneUse()) {
11682       // Push extractelement into predecessor operation if legal and
11683       // profitable to do so
11684       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11685         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11686         if (CheapToScalarize(BO, isConstantElt)) {
11687           ExtractElementInst *newEI0 = 
11688             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11689                                    EI.getName()+".lhs");
11690           ExtractElementInst *newEI1 =
11691             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11692                                    EI.getName()+".rhs");
11693           InsertNewInstBefore(newEI0, EI);
11694           InsertNewInstBefore(newEI1, EI);
11695           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11696         }
11697       } else if (isa<LoadInst>(I)) {
11698         unsigned AS = 
11699           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11700         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11701                                          PointerType::get(EI.getType(), AS),EI);
11702         GetElementPtrInst *GEP =
11703           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11704         InsertNewInstBefore(GEP, EI);
11705         return new LoadInst(GEP);
11706       }
11707     }
11708     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11709       // Extracting the inserted element?
11710       if (IE->getOperand(2) == EI.getOperand(1))
11711         return ReplaceInstUsesWith(EI, IE->getOperand(1));
11712       // If the inserted and extracted elements are constants, they must not
11713       // be the same value, extract from the pre-inserted value instead.
11714       if (isa<Constant>(IE->getOperand(2)) &&
11715           isa<Constant>(EI.getOperand(1))) {
11716         AddUsesToWorkList(EI);
11717         EI.setOperand(0, IE->getOperand(0));
11718         return &EI;
11719       }
11720     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11721       // If this is extracting an element from a shufflevector, figure out where
11722       // it came from and extract from the appropriate input element instead.
11723       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11724         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11725         Value *Src;
11726         unsigned LHSWidth =
11727           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11728
11729         if (SrcIdx < LHSWidth)
11730           Src = SVI->getOperand(0);
11731         else if (SrcIdx < LHSWidth*2) {
11732           SrcIdx -= LHSWidth;
11733           Src = SVI->getOperand(1);
11734         } else {
11735           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11736         }
11737         return new ExtractElementInst(Src, SrcIdx);
11738       }
11739     }
11740   }
11741   return 0;
11742 }
11743
11744 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11745 /// elements from either LHS or RHS, return the shuffle mask and true. 
11746 /// Otherwise, return false.
11747 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11748                                          std::vector<Constant*> &Mask) {
11749   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11750          "Invalid CollectSingleShuffleElements");
11751   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11752
11753   if (isa<UndefValue>(V)) {
11754     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11755     return true;
11756   } else if (V == LHS) {
11757     for (unsigned i = 0; i != NumElts; ++i)
11758       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11759     return true;
11760   } else if (V == RHS) {
11761     for (unsigned i = 0; i != NumElts; ++i)
11762       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11763     return true;
11764   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11765     // If this is an insert of an extract from some other vector, include it.
11766     Value *VecOp    = IEI->getOperand(0);
11767     Value *ScalarOp = IEI->getOperand(1);
11768     Value *IdxOp    = IEI->getOperand(2);
11769     
11770     if (!isa<ConstantInt>(IdxOp))
11771       return false;
11772     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11773     
11774     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
11775       // Okay, we can handle this if the vector we are insertinting into is
11776       // transitively ok.
11777       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11778         // If so, update the mask to reflect the inserted undef.
11779         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11780         return true;
11781       }      
11782     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11783       if (isa<ConstantInt>(EI->getOperand(1)) &&
11784           EI->getOperand(0)->getType() == V->getType()) {
11785         unsigned ExtractedIdx =
11786           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11787         
11788         // This must be extracting from either LHS or RHS.
11789         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11790           // Okay, we can handle this if the vector we are insertinting into is
11791           // transitively ok.
11792           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11793             // If so, update the mask to reflect the inserted value.
11794             if (EI->getOperand(0) == LHS) {
11795               Mask[InsertedIdx % NumElts] = 
11796                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11797             } else {
11798               assert(EI->getOperand(0) == RHS);
11799               Mask[InsertedIdx % NumElts] = 
11800                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11801               
11802             }
11803             return true;
11804           }
11805         }
11806       }
11807     }
11808   }
11809   // TODO: Handle shufflevector here!
11810   
11811   return false;
11812 }
11813
11814 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11815 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
11816 /// that computes V and the LHS value of the shuffle.
11817 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11818                                      Value *&RHS) {
11819   assert(isa<VectorType>(V->getType()) && 
11820          (RHS == 0 || V->getType() == RHS->getType()) &&
11821          "Invalid shuffle!");
11822   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11823
11824   if (isa<UndefValue>(V)) {
11825     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11826     return V;
11827   } else if (isa<ConstantAggregateZero>(V)) {
11828     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11829     return V;
11830   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11831     // If this is an insert of an extract from some other vector, include it.
11832     Value *VecOp    = IEI->getOperand(0);
11833     Value *ScalarOp = IEI->getOperand(1);
11834     Value *IdxOp    = IEI->getOperand(2);
11835     
11836     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11837       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11838           EI->getOperand(0)->getType() == V->getType()) {
11839         unsigned ExtractedIdx =
11840           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11841         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11842         
11843         // Either the extracted from or inserted into vector must be RHSVec,
11844         // otherwise we'd end up with a shuffle of three inputs.
11845         if (EI->getOperand(0) == RHS || RHS == 0) {
11846           RHS = EI->getOperand(0);
11847           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11848           Mask[InsertedIdx % NumElts] = 
11849             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11850           return V;
11851         }
11852         
11853         if (VecOp == RHS) {
11854           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11855           // Everything but the extracted element is replaced with the RHS.
11856           for (unsigned i = 0; i != NumElts; ++i) {
11857             if (i != InsertedIdx)
11858               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11859           }
11860           return V;
11861         }
11862         
11863         // If this insertelement is a chain that comes from exactly these two
11864         // vectors, return the vector and the effective shuffle.
11865         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11866           return EI->getOperand(0);
11867         
11868       }
11869     }
11870   }
11871   // TODO: Handle shufflevector here!
11872   
11873   // Otherwise, can't do anything fancy.  Return an identity vector.
11874   for (unsigned i = 0; i != NumElts; ++i)
11875     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11876   return V;
11877 }
11878
11879 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11880   Value *VecOp    = IE.getOperand(0);
11881   Value *ScalarOp = IE.getOperand(1);
11882   Value *IdxOp    = IE.getOperand(2);
11883   
11884   // Inserting an undef or into an undefined place, remove this.
11885   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11886     ReplaceInstUsesWith(IE, VecOp);
11887   
11888   // If the inserted element was extracted from some other vector, and if the 
11889   // indexes are constant, try to turn this into a shufflevector operation.
11890   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11891     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11892         EI->getOperand(0)->getType() == IE.getType()) {
11893       unsigned NumVectorElts = IE.getType()->getNumElements();
11894       unsigned ExtractedIdx =
11895         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11896       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11897       
11898       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11899         return ReplaceInstUsesWith(IE, VecOp);
11900       
11901       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11902         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11903       
11904       // If we are extracting a value from a vector, then inserting it right
11905       // back into the same place, just use the input vector.
11906       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11907         return ReplaceInstUsesWith(IE, VecOp);      
11908       
11909       // We could theoretically do this for ANY input.  However, doing so could
11910       // turn chains of insertelement instructions into a chain of shufflevector
11911       // instructions, and right now we do not merge shufflevectors.  As such,
11912       // only do this in a situation where it is clear that there is benefit.
11913       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11914         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11915         // the values of VecOp, except then one read from EIOp0.
11916         // Build a new shuffle mask.
11917         std::vector<Constant*> Mask;
11918         if (isa<UndefValue>(VecOp))
11919           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11920         else {
11921           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11922           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11923                                                        NumVectorElts));
11924         } 
11925         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11926         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11927                                      ConstantVector::get(Mask));
11928       }
11929       
11930       // If this insertelement isn't used by some other insertelement, turn it
11931       // (and any insertelements it points to), into one big shuffle.
11932       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11933         std::vector<Constant*> Mask;
11934         Value *RHS = 0;
11935         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11936         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11937         // We now have a shuffle of LHS, RHS, Mask.
11938         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11939       }
11940     }
11941   }
11942
11943   return 0;
11944 }
11945
11946
11947 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11948   Value *LHS = SVI.getOperand(0);
11949   Value *RHS = SVI.getOperand(1);
11950   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11951
11952   bool MadeChange = false;
11953
11954   // Undefined shuffle mask -> undefined value.
11955   if (isa<UndefValue>(SVI.getOperand(2)))
11956     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11957
11958   uint64_t UndefElts;
11959   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
11960
11961   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
11962     return 0;
11963
11964   uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
11965   if (VWidth <= 64 &&
11966       SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
11967     LHS = SVI.getOperand(0);
11968     RHS = SVI.getOperand(1);
11969     MadeChange = true;
11970   }
11971   
11972   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11973   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11974   if (LHS == RHS || isa<UndefValue>(LHS)) {
11975     if (isa<UndefValue>(LHS) && LHS == RHS) {
11976       // shuffle(undef,undef,mask) -> undef.
11977       return ReplaceInstUsesWith(SVI, LHS);
11978     }
11979     
11980     // Remap any references to RHS to use LHS.
11981     std::vector<Constant*> Elts;
11982     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11983       if (Mask[i] >= 2*e)
11984         Elts.push_back(UndefValue::get(Type::Int32Ty));
11985       else {
11986         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11987             (Mask[i] <  e && isa<UndefValue>(LHS))) {
11988           Mask[i] = 2*e;     // Turn into undef.
11989           Elts.push_back(UndefValue::get(Type::Int32Ty));
11990         } else {
11991           Mask[i] = Mask[i] % e;  // Force to LHS.
11992           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11993         }
11994       }
11995     }
11996     SVI.setOperand(0, SVI.getOperand(1));
11997     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11998     SVI.setOperand(2, ConstantVector::get(Elts));
11999     LHS = SVI.getOperand(0);
12000     RHS = SVI.getOperand(1);
12001     MadeChange = true;
12002   }
12003   
12004   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12005   bool isLHSID = true, isRHSID = true;
12006     
12007   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12008     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12009     // Is this an identity shuffle of the LHS value?
12010     isLHSID &= (Mask[i] == i);
12011       
12012     // Is this an identity shuffle of the RHS value?
12013     isRHSID &= (Mask[i]-e == i);
12014   }
12015
12016   // Eliminate identity shuffles.
12017   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12018   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12019   
12020   // If the LHS is a shufflevector itself, see if we can combine it with this
12021   // one without producing an unusual shuffle.  Here we are really conservative:
12022   // we are absolutely afraid of producing a shuffle mask not in the input
12023   // program, because the code gen may not be smart enough to turn a merged
12024   // shuffle into two specific shuffles: it may produce worse code.  As such,
12025   // we only merge two shuffles if the result is one of the two input shuffle
12026   // masks.  In this case, merging the shuffles just removes one instruction,
12027   // which we know is safe.  This is good for things like turning:
12028   // (splat(splat)) -> splat.
12029   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12030     if (isa<UndefValue>(RHS)) {
12031       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12032
12033       std::vector<unsigned> NewMask;
12034       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12035         if (Mask[i] >= 2*e)
12036           NewMask.push_back(2*e);
12037         else
12038           NewMask.push_back(LHSMask[Mask[i]]);
12039       
12040       // If the result mask is equal to the src shuffle or this shuffle mask, do
12041       // the replacement.
12042       if (NewMask == LHSMask || NewMask == Mask) {
12043         std::vector<Constant*> Elts;
12044         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12045           if (NewMask[i] >= e*2) {
12046             Elts.push_back(UndefValue::get(Type::Int32Ty));
12047           } else {
12048             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12049           }
12050         }
12051         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12052                                      LHSSVI->getOperand(1),
12053                                      ConstantVector::get(Elts));
12054       }
12055     }
12056   }
12057
12058   return MadeChange ? &SVI : 0;
12059 }
12060
12061
12062
12063
12064 /// TryToSinkInstruction - Try to move the specified instruction from its
12065 /// current block into the beginning of DestBlock, which can only happen if it's
12066 /// safe to move the instruction past all of the instructions between it and the
12067 /// end of its block.
12068 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12069   assert(I->hasOneUse() && "Invariants didn't hold!");
12070
12071   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12072   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12073     return false;
12074
12075   // Do not sink alloca instructions out of the entry block.
12076   if (isa<AllocaInst>(I) && I->getParent() ==
12077         &DestBlock->getParent()->getEntryBlock())
12078     return false;
12079
12080   // We can only sink load instructions if there is nothing between the load and
12081   // the end of block that could change the value.
12082   if (I->mayReadFromMemory()) {
12083     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12084          Scan != E; ++Scan)
12085       if (Scan->mayWriteToMemory())
12086         return false;
12087   }
12088
12089   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12090
12091   I->moveBefore(InsertPos);
12092   ++NumSunkInst;
12093   return true;
12094 }
12095
12096
12097 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12098 /// all reachable code to the worklist.
12099 ///
12100 /// This has a couple of tricks to make the code faster and more powerful.  In
12101 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12102 /// them to the worklist (this significantly speeds up instcombine on code where
12103 /// many instructions are dead or constant).  Additionally, if we find a branch
12104 /// whose condition is a known constant, we only visit the reachable successors.
12105 ///
12106 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12107                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12108                                        InstCombiner &IC,
12109                                        const TargetData *TD) {
12110   SmallVector<BasicBlock*, 256> Worklist;
12111   Worklist.push_back(BB);
12112
12113   while (!Worklist.empty()) {
12114     BB = Worklist.back();
12115     Worklist.pop_back();
12116     
12117     // We have now visited this block!  If we've already been here, ignore it.
12118     if (!Visited.insert(BB)) continue;
12119
12120     DbgInfoIntrinsic *DBI_Prev = NULL;
12121     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12122       Instruction *Inst = BBI++;
12123       
12124       // DCE instruction if trivially dead.
12125       if (isInstructionTriviallyDead(Inst)) {
12126         ++NumDeadInst;
12127         DOUT << "IC: DCE: " << *Inst;
12128         Inst->eraseFromParent();
12129         continue;
12130       }
12131       
12132       // ConstantProp instruction if trivially constant.
12133       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12134         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12135         Inst->replaceAllUsesWith(C);
12136         ++NumConstProp;
12137         Inst->eraseFromParent();
12138         continue;
12139       }
12140      
12141       // If there are two consecutive llvm.dbg.stoppoint calls then
12142       // it is likely that the optimizer deleted code in between these
12143       // two intrinsics. 
12144       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12145       if (DBI_Next) {
12146         if (DBI_Prev
12147             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12148             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12149           IC.RemoveFromWorkList(DBI_Prev);
12150           DBI_Prev->eraseFromParent();
12151         }
12152         DBI_Prev = DBI_Next;
12153       }
12154
12155       IC.AddToWorkList(Inst);
12156     }
12157
12158     // Recursively visit successors.  If this is a branch or switch on a
12159     // constant, only visit the reachable successor.
12160     TerminatorInst *TI = BB->getTerminator();
12161     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12162       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12163         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12164         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12165         Worklist.push_back(ReachableBB);
12166         continue;
12167       }
12168     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12169       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12170         // See if this is an explicit destination.
12171         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12172           if (SI->getCaseValue(i) == Cond) {
12173             BasicBlock *ReachableBB = SI->getSuccessor(i);
12174             Worklist.push_back(ReachableBB);
12175             continue;
12176           }
12177         
12178         // Otherwise it is the default destination.
12179         Worklist.push_back(SI->getSuccessor(0));
12180         continue;
12181       }
12182     }
12183     
12184     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12185       Worklist.push_back(TI->getSuccessor(i));
12186   }
12187 }
12188
12189 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12190   bool Changed = false;
12191   TD = &getAnalysis<TargetData>();
12192   
12193   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12194              << F.getNameStr() << "\n");
12195
12196   {
12197     // Do a depth-first traversal of the function, populate the worklist with
12198     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12199     // track of which blocks we visit.
12200     SmallPtrSet<BasicBlock*, 64> Visited;
12201     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12202
12203     // Do a quick scan over the function.  If we find any blocks that are
12204     // unreachable, remove any instructions inside of them.  This prevents
12205     // the instcombine code from having to deal with some bad special cases.
12206     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12207       if (!Visited.count(BB)) {
12208         Instruction *Term = BB->getTerminator();
12209         while (Term != BB->begin()) {   // Remove instrs bottom-up
12210           BasicBlock::iterator I = Term; --I;
12211
12212           DOUT << "IC: DCE: " << *I;
12213           ++NumDeadInst;
12214
12215           if (!I->use_empty())
12216             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12217           I->eraseFromParent();
12218         }
12219       }
12220   }
12221
12222   while (!Worklist.empty()) {
12223     Instruction *I = RemoveOneFromWorkList();
12224     if (I == 0) continue;  // skip null values.
12225
12226     // Check to see if we can DCE the instruction.
12227     if (isInstructionTriviallyDead(I)) {
12228       // Add operands to the worklist.
12229       if (I->getNumOperands() < 4)
12230         AddUsesToWorkList(*I);
12231       ++NumDeadInst;
12232
12233       DOUT << "IC: DCE: " << *I;
12234
12235       I->eraseFromParent();
12236       RemoveFromWorkList(I);
12237       continue;
12238     }
12239
12240     // Instruction isn't dead, see if we can constant propagate it.
12241     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12242       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12243
12244       // Add operands to the worklist.
12245       AddUsesToWorkList(*I);
12246       ReplaceInstUsesWith(*I, C);
12247
12248       ++NumConstProp;
12249       I->eraseFromParent();
12250       RemoveFromWorkList(I);
12251       continue;
12252     }
12253
12254     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12255       // See if we can constant fold its operands.
12256       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
12257         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
12258           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12259             i->set(NewC);
12260         }
12261       }
12262     }
12263
12264     // See if we can trivially sink this instruction to a successor basic block.
12265     if (I->hasOneUse()) {
12266       BasicBlock *BB = I->getParent();
12267       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12268       if (UserParent != BB) {
12269         bool UserIsSuccessor = false;
12270         // See if the user is one of our successors.
12271         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12272           if (*SI == UserParent) {
12273             UserIsSuccessor = true;
12274             break;
12275           }
12276
12277         // If the user is one of our immediate successors, and if that successor
12278         // only has us as a predecessors (we'd have to split the critical edge
12279         // otherwise), we can keep going.
12280         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12281             next(pred_begin(UserParent)) == pred_end(UserParent))
12282           // Okay, the CFG is simple enough, try to sink this instruction.
12283           Changed |= TryToSinkInstruction(I, UserParent);
12284       }
12285     }
12286
12287     // Now that we have an instruction, try combining it to simplify it...
12288 #ifndef NDEBUG
12289     std::string OrigI;
12290 #endif
12291     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12292     if (Instruction *Result = visit(*I)) {
12293       ++NumCombined;
12294       // Should we replace the old instruction with a new one?
12295       if (Result != I) {
12296         DOUT << "IC: Old = " << *I
12297              << "    New = " << *Result;
12298
12299         // Everything uses the new instruction now.
12300         I->replaceAllUsesWith(Result);
12301
12302         // Push the new instruction and any users onto the worklist.
12303         AddToWorkList(Result);
12304         AddUsersToWorkList(*Result);
12305
12306         // Move the name to the new instruction first.
12307         Result->takeName(I);
12308
12309         // Insert the new instruction into the basic block...
12310         BasicBlock *InstParent = I->getParent();
12311         BasicBlock::iterator InsertPos = I;
12312
12313         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12314           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12315             ++InsertPos;
12316
12317         InstParent->getInstList().insert(InsertPos, Result);
12318
12319         // Make sure that we reprocess all operands now that we reduced their
12320         // use counts.
12321         AddUsesToWorkList(*I);
12322
12323         // Instructions can end up on the worklist more than once.  Make sure
12324         // we do not process an instruction that has been deleted.
12325         RemoveFromWorkList(I);
12326
12327         // Erase the old instruction.
12328         InstParent->getInstList().erase(I);
12329       } else {
12330 #ifndef NDEBUG
12331         DOUT << "IC: Mod = " << OrigI
12332              << "    New = " << *I;
12333 #endif
12334
12335         // If the instruction was modified, it's possible that it is now dead.
12336         // if so, remove it.
12337         if (isInstructionTriviallyDead(I)) {
12338           // Make sure we process all operands now that we are reducing their
12339           // use counts.
12340           AddUsesToWorkList(*I);
12341
12342           // Instructions may end up in the worklist more than once.  Erase all
12343           // occurrences of this instruction.
12344           RemoveFromWorkList(I);
12345           I->eraseFromParent();
12346         } else {
12347           AddToWorkList(I);
12348           AddUsersToWorkList(*I);
12349         }
12350       }
12351       Changed = true;
12352     }
12353   }
12354
12355   assert(WorklistMap.empty() && "Worklist empty, but map not?");
12356     
12357   // Do an explicit clear, this shrinks the map if needed.
12358   WorklistMap.clear();
12359   return Changed;
12360 }
12361
12362
12363 bool InstCombiner::runOnFunction(Function &F) {
12364   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12365   
12366   bool EverMadeChange = false;
12367
12368   // Iterate while there is work to do.
12369   unsigned Iteration = 0;
12370   while (DoOneIteration(F, Iteration++))
12371     EverMadeChange = true;
12372   return EverMadeChange;
12373 }
12374
12375 FunctionPass *llvm::createInstructionCombiningPass() {
12376   return new InstCombiner();
12377 }
12378
12379