Generalize the zext(trunc(t) & C) instcombine to work even with
[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 *visitFAdd(BinaryOperator &I);
171     Instruction *visitSub(BinaryOperator &I);
172     Instruction *visitFSub(BinaryOperator &I);
173     Instruction *visitMul(BinaryOperator &I);
174     Instruction *visitFMul(BinaryOperator &I);
175     Instruction *visitURem(BinaryOperator &I);
176     Instruction *visitSRem(BinaryOperator &I);
177     Instruction *visitFRem(BinaryOperator &I);
178     bool SimplifyDivRemOfSelect(BinaryOperator &I);
179     Instruction *commonRemTransforms(BinaryOperator &I);
180     Instruction *commonIRemTransforms(BinaryOperator &I);
181     Instruction *commonDivTransforms(BinaryOperator &I);
182     Instruction *commonIDivTransforms(BinaryOperator &I);
183     Instruction *visitUDiv(BinaryOperator &I);
184     Instruction *visitSDiv(BinaryOperator &I);
185     Instruction *visitFDiv(BinaryOperator &I);
186     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
187     Instruction *visitAnd(BinaryOperator &I);
188     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
189     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
190                                      Value *A, Value *B, Value *C);
191     Instruction *visitOr (BinaryOperator &I);
192     Instruction *visitXor(BinaryOperator &I);
193     Instruction *visitShl(BinaryOperator &I);
194     Instruction *visitAShr(BinaryOperator &I);
195     Instruction *visitLShr(BinaryOperator &I);
196     Instruction *commonShiftTransforms(BinaryOperator &I);
197     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
198                                       Constant *RHSC);
199     Instruction *visitFCmpInst(FCmpInst &I);
200     Instruction *visitICmpInst(ICmpInst &I);
201     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
202     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
203                                                 Instruction *LHS,
204                                                 ConstantInt *RHS);
205     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
206                                 ConstantInt *DivRHS);
207
208     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
209                              ICmpInst::Predicate Cond, Instruction &I);
210     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
211                                      BinaryOperator &I);
212     Instruction *commonCastTransforms(CastInst &CI);
213     Instruction *commonIntCastTransforms(CastInst &CI);
214     Instruction *commonPointerCastTransforms(CastInst &CI);
215     Instruction *visitTrunc(TruncInst &CI);
216     Instruction *visitZExt(ZExtInst &CI);
217     Instruction *visitSExt(SExtInst &CI);
218     Instruction *visitFPTrunc(FPTruncInst &CI);
219     Instruction *visitFPExt(CastInst &CI);
220     Instruction *visitFPToUI(FPToUIInst &FI);
221     Instruction *visitFPToSI(FPToSIInst &FI);
222     Instruction *visitUIToFP(CastInst &CI);
223     Instruction *visitSIToFP(CastInst &CI);
224     Instruction *visitPtrToInt(PtrToIntInst &CI);
225     Instruction *visitIntToPtr(IntToPtrInst &CI);
226     Instruction *visitBitCast(BitCastInst &CI);
227     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
228                                 Instruction *FI);
229     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
230     Instruction *visitSelectInst(SelectInst &SI);
231     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
232     Instruction *visitCallInst(CallInst &CI);
233     Instruction *visitInvokeInst(InvokeInst &II);
234     Instruction *visitPHINode(PHINode &PN);
235     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
236     Instruction *visitAllocationInst(AllocationInst &AI);
237     Instruction *visitFreeInst(FreeInst &FI);
238     Instruction *visitLoadInst(LoadInst &LI);
239     Instruction *visitStoreInst(StoreInst &SI);
240     Instruction *visitBranchInst(BranchInst &BI);
241     Instruction *visitSwitchInst(SwitchInst &SI);
242     Instruction *visitInsertElementInst(InsertElementInst &IE);
243     Instruction *visitExtractElementInst(ExtractElementInst &EI);
244     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
245     Instruction *visitExtractValueInst(ExtractValueInst &EV);
246
247     // visitInstruction - Specify what to return for unhandled instructions...
248     Instruction *visitInstruction(Instruction &I) { return 0; }
249
250   private:
251     Instruction *visitCallSite(CallSite CS);
252     bool transformConstExprCastCall(CallSite CS);
253     Instruction *transformCallThroughTrampoline(CallSite CS);
254     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
255                                    bool DoXform = true);
256     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
257     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
258
259
260   public:
261     // InsertNewInstBefore - insert an instruction New before instruction Old
262     // in the program.  Add the new instruction to the worklist.
263     //
264     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
265       assert(New && New->getParent() == 0 &&
266              "New instruction already inserted into a basic block!");
267       BasicBlock *BB = Old.getParent();
268       BB->getInstList().insert(&Old, New);  // Insert inst
269       AddToWorkList(New);
270       return New;
271     }
272
273     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
274     /// This also adds the cast to the worklist.  Finally, this returns the
275     /// cast.
276     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
277                             Instruction &Pos) {
278       if (V->getType() == Ty) return V;
279
280       if (Constant *CV = dyn_cast<Constant>(V))
281         return ConstantExpr::getCast(opc, CV, Ty);
282       
283       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
284       AddToWorkList(C);
285       return C;
286     }
287         
288     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
289       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
290     }
291
292
293     // ReplaceInstUsesWith - This method is to be used when an instruction is
294     // found to be dead, replacable with another preexisting expression.  Here
295     // we add all uses of I to the worklist, replace all uses of I with the new
296     // value, then return I, so that the inst combiner will know that I was
297     // modified.
298     //
299     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
300       AddUsersToWorkList(I);         // Add all modified instrs to worklist
301       if (&I != V) {
302         I.replaceAllUsesWith(V);
303         return &I;
304       } else {
305         // If we are replacing the instruction with itself, this must be in a
306         // segment of unreachable code, so just clobber the instruction.
307         I.replaceAllUsesWith(UndefValue::get(I.getType()));
308         return &I;
309       }
310     }
311
312     // EraseInstFromFunction - When dealing with an instruction that has side
313     // effects or produces a void value, we can't rely on DCE to delete the
314     // instruction.  Instead, visit methods should return the value returned by
315     // this function.
316     Instruction *EraseInstFromFunction(Instruction &I) {
317       assert(I.use_empty() && "Cannot erase instruction that is used!");
318       AddUsesToWorkList(I);
319       RemoveFromWorkList(&I);
320       I.eraseFromParent();
321       return 0;  // Don't do anything with FI
322     }
323         
324     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
325                            APInt &KnownOne, unsigned Depth = 0) const {
326       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
327     }
328     
329     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
330                            unsigned Depth = 0) const {
331       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
332     }
333     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
334       return llvm::ComputeNumSignBits(Op, TD, Depth);
335     }
336
337   private:
338
339     /// SimplifyCommutative - This performs a few simplifications for 
340     /// commutative operators.
341     bool SimplifyCommutative(BinaryOperator &I);
342
343     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
344     /// most-complex to least-complex order.
345     bool SimplifyCompare(CmpInst &I);
346
347     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
348     /// based on the demanded bits.
349     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
350                                    APInt& KnownZero, APInt& KnownOne,
351                                    unsigned Depth);
352     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
353                               APInt& KnownZero, APInt& KnownOne,
354                               unsigned Depth=0);
355         
356     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
357     /// SimplifyDemandedBits knows about.  See if the instruction has any
358     /// properties that allow us to simplify its operands.
359     bool SimplifyDemandedInstructionBits(Instruction &Inst);
360         
361     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
362                                       APInt& UndefElts, unsigned Depth = 0);
363       
364     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
365     // PHI node as operand #0, see if we can fold the instruction into the PHI
366     // (which is only possible if all operands to the PHI are constants).
367     Instruction *FoldOpIntoPhi(Instruction &I);
368
369     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
370     // operator and they all are only used by the PHI, PHI together their
371     // inputs, and do the operation once, to the result of the PHI.
372     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
373     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
374     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
375
376     
377     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
378                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
379     
380     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
381                               bool isSub, Instruction &I);
382     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
383                                  bool isSigned, bool Inside, Instruction &IB);
384     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
385     Instruction *MatchBSwap(BinaryOperator &I);
386     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
387     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
388     Instruction *SimplifyMemSet(MemSetInst *MI);
389
390
391     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
392
393     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
394                                     unsigned CastOpc, int &NumCastsRemoved);
395     unsigned GetOrEnforceKnownAlignment(Value *V,
396                                         unsigned PrefAlign = 0);
397
398   };
399 }
400
401 char InstCombiner::ID = 0;
402 static RegisterPass<InstCombiner>
403 X("instcombine", "Combine redundant instructions");
404
405 // getComplexity:  Assign a complexity or rank value to LLVM Values...
406 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
407 static unsigned getComplexity(Value *V) {
408   if (isa<Instruction>(V)) {
409     if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
410         BinaryOperator::isNot(V))
411       return 3;
412     return 4;
413   }
414   if (isa<Argument>(V)) return 3;
415   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
416 }
417
418 // isOnlyUse - Return true if this instruction will be deleted if we stop using
419 // it.
420 static bool isOnlyUse(Value *V) {
421   return V->hasOneUse() || isa<Constant>(V);
422 }
423
424 // getPromotedType - Return the specified type promoted as it would be to pass
425 // though a va_arg area...
426 static const Type *getPromotedType(const Type *Ty) {
427   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
428     if (ITy->getBitWidth() < 32)
429       return Type::Int32Ty;
430   }
431   return Ty;
432 }
433
434 /// getBitCastOperand - If the specified operand is a CastInst, a constant
435 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
436 /// operand value, otherwise return null.
437 static Value *getBitCastOperand(Value *V) {
438   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
439     // BitCastInst?
440     return I->getOperand(0);
441   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
442     // GetElementPtrInst?
443     if (GEP->hasAllZeroIndices())
444       return GEP->getOperand(0);
445   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
446     if (CE->getOpcode() == Instruction::BitCast)
447       // BitCast ConstantExp?
448       return CE->getOperand(0);
449     else if (CE->getOpcode() == Instruction::GetElementPtr) {
450       // GetElementPtr ConstantExp?
451       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
452            I != E; ++I) {
453         ConstantInt *CI = dyn_cast<ConstantInt>(I);
454         if (!CI || !CI->isZero())
455           // Any non-zero indices? Not cast-like.
456           return 0;
457       }
458       // All-zero indices? This is just like casting.
459       return CE->getOperand(0);
460     }
461   }
462   return 0;
463 }
464
465 /// This function is a wrapper around CastInst::isEliminableCastPair. It
466 /// simply extracts arguments and returns what that function returns.
467 static Instruction::CastOps 
468 isEliminableCastPair(
469   const CastInst *CI, ///< The first cast instruction
470   unsigned opcode,       ///< The opcode of the second cast instruction
471   const Type *DstTy,     ///< The target type for the second cast instruction
472   TargetData *TD         ///< The target data for pointer size
473 ) {
474   
475   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
476   const Type *MidTy = CI->getType();                  // B from above
477
478   // Get the opcodes of the two Cast instructions
479   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
480   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
481
482   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
483                                                 DstTy, TD->getIntPtrType());
484   
485   // We don't want to form an inttoptr or ptrtoint that converts to an integer
486   // type that differs from the pointer size.
487   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
488       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
489     Res = 0;
490   
491   return Instruction::CastOps(Res);
492 }
493
494 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
495 /// in any code being generated.  It does not require codegen if V is simple
496 /// enough or if the cast can be folded into other casts.
497 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
498                               const Type *Ty, TargetData *TD) {
499   if (V->getType() == Ty || isa<Constant>(V)) return false;
500   
501   // If this is another cast that can be eliminated, it isn't codegen either.
502   if (const CastInst *CI = dyn_cast<CastInst>(V))
503     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
504       return false;
505   return true;
506 }
507
508 // SimplifyCommutative - This performs a few simplifications for commutative
509 // operators:
510 //
511 //  1. Order operands such that they are listed from right (least complex) to
512 //     left (most complex).  This puts constants before unary operators before
513 //     binary operators.
514 //
515 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
516 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
517 //
518 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
519   bool Changed = false;
520   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
521     Changed = !I.swapOperands();
522
523   if (!I.isAssociative()) return Changed;
524   Instruction::BinaryOps Opcode = I.getOpcode();
525   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
526     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
527       if (isa<Constant>(I.getOperand(1))) {
528         Constant *Folded = ConstantExpr::get(I.getOpcode(),
529                                              cast<Constant>(I.getOperand(1)),
530                                              cast<Constant>(Op->getOperand(1)));
531         I.setOperand(0, Op->getOperand(0));
532         I.setOperand(1, Folded);
533         return true;
534       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
535         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
536             isOnlyUse(Op) && isOnlyUse(Op1)) {
537           Constant *C1 = cast<Constant>(Op->getOperand(1));
538           Constant *C2 = cast<Constant>(Op1->getOperand(1));
539
540           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
541           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
542           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
543                                                     Op1->getOperand(0),
544                                                     Op1->getName(), &I);
545           AddToWorkList(New);
546           I.setOperand(0, New);
547           I.setOperand(1, Folded);
548           return true;
549         }
550     }
551   return Changed;
552 }
553
554 /// SimplifyCompare - For a CmpInst this function just orders the operands
555 /// so that theyare listed from right (least complex) to left (most complex).
556 /// This puts constants before unary operators before binary operators.
557 bool InstCombiner::SimplifyCompare(CmpInst &I) {
558   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
559     return false;
560   I.swapOperands();
561   // Compare instructions are not associative so there's nothing else we can do.
562   return true;
563 }
564
565 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
566 // if the LHS is a constant zero (which is the 'negate' form).
567 //
568 static inline Value *dyn_castNegVal(Value *V) {
569   if (BinaryOperator::isNeg(V))
570     return BinaryOperator::getNegArgument(V);
571
572   // Constants can be considered to be negated values if they can be folded.
573   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
574     return ConstantExpr::getNeg(C);
575
576   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
577     if (C->getType()->getElementType()->isInteger())
578       return ConstantExpr::getNeg(C);
579
580   return 0;
581 }
582
583 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
584 // instruction if the LHS is a constant negative zero (which is the 'negate'
585 // form).
586 //
587 static inline Value *dyn_castFNegVal(Value *V) {
588   if (BinaryOperator::isFNeg(V))
589     return BinaryOperator::getFNegArgument(V);
590
591   // Constants can be considered to be negated values if they can be folded.
592   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
593     return ConstantExpr::getFNeg(C);
594
595   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
596     if (C->getType()->getElementType()->isFloatingPoint())
597       return ConstantExpr::getFNeg(C);
598
599   return 0;
600 }
601
602 static inline Value *dyn_castNotVal(Value *V) {
603   if (BinaryOperator::isNot(V))
604     return BinaryOperator::getNotArgument(V);
605
606   // Constants can be considered to be not'ed values...
607   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
608     return ConstantInt::get(~C->getValue());
609   return 0;
610 }
611
612 // dyn_castFoldableMul - If this value is a multiply that can be folded into
613 // other computations (because it has a constant operand), return the
614 // non-constant operand of the multiply, and set CST to point to the multiplier.
615 // Otherwise, return null.
616 //
617 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
618   if (V->hasOneUse() && V->getType()->isInteger())
619     if (Instruction *I = dyn_cast<Instruction>(V)) {
620       if (I->getOpcode() == Instruction::Mul)
621         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
622           return I->getOperand(0);
623       if (I->getOpcode() == Instruction::Shl)
624         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
625           // The multiplier is really 1 << CST.
626           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
627           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
628           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
629           return I->getOperand(0);
630         }
631     }
632   return 0;
633 }
634
635 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
636 /// expression, return it.
637 static User *dyn_castGetElementPtr(Value *V) {
638   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
639   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
640     if (CE->getOpcode() == Instruction::GetElementPtr)
641       return cast<User>(V);
642   return false;
643 }
644
645 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
646 /// opcode value. Otherwise return UserOp1.
647 static unsigned getOpcode(const Value *V) {
648   if (const Instruction *I = dyn_cast<Instruction>(V))
649     return I->getOpcode();
650   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
651     return CE->getOpcode();
652   // Use UserOp1 to mean there's no opcode.
653   return Instruction::UserOp1;
654 }
655
656 /// AddOne - Add one to a ConstantInt
657 static Constant *AddOne(Constant *C) {
658   return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
659 }
660 /// SubOne - Subtract one from a ConstantInt
661 static Constant *SubOne(ConstantInt *C) {
662   return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
663 }
664 /// MultiplyOverflows - True if the multiply can not be expressed in an int
665 /// this size.
666 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
667   uint32_t W = C1->getBitWidth();
668   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
669   if (sign) {
670     LHSExt.sext(W * 2);
671     RHSExt.sext(W * 2);
672   } else {
673     LHSExt.zext(W * 2);
674     RHSExt.zext(W * 2);
675   }
676
677   APInt MulExt = LHSExt * RHSExt;
678
679   if (sign) {
680     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
681     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
682     return MulExt.slt(Min) || MulExt.sgt(Max);
683   } else 
684     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
685 }
686
687
688 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
689 /// specified instruction is a constant integer.  If so, check to see if there
690 /// are any bits set in the constant that are not demanded.  If so, shrink the
691 /// constant and return true.
692 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
693                                    APInt Demanded) {
694   assert(I && "No instruction?");
695   assert(OpNo < I->getNumOperands() && "Operand index too large");
696
697   // If the operand is not a constant integer, nothing to do.
698   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
699   if (!OpC) return false;
700
701   // If there are no bits set that aren't demanded, nothing to do.
702   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
703   if ((~Demanded & OpC->getValue()) == 0)
704     return false;
705
706   // This instruction is producing bits that are not demanded. Shrink the RHS.
707   Demanded &= OpC->getValue();
708   I->setOperand(OpNo, ConstantInt::get(Demanded));
709   return true;
710 }
711
712 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
713 // set of known zero and one bits, compute the maximum and minimum values that
714 // could have the specified known zero and known one bits, returning them in
715 // min/max.
716 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
717                                                    const APInt& KnownOne,
718                                                    APInt& Min, APInt& Max) {
719   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
720          KnownZero.getBitWidth() == Min.getBitWidth() &&
721          KnownZero.getBitWidth() == Max.getBitWidth() &&
722          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
723   APInt UnknownBits = ~(KnownZero|KnownOne);
724
725   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
726   // bit if it is unknown.
727   Min = KnownOne;
728   Max = KnownOne|UnknownBits;
729   
730   if (UnknownBits.isNegative()) { // Sign bit is unknown
731     Min.set(Min.getBitWidth()-1);
732     Max.clear(Max.getBitWidth()-1);
733   }
734 }
735
736 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
737 // a set of known zero and one bits, compute the maximum and minimum values that
738 // could have the specified known zero and known one bits, returning them in
739 // min/max.
740 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
741                                                      const APInt &KnownOne,
742                                                      APInt &Min, APInt &Max) {
743   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
744          KnownZero.getBitWidth() == Min.getBitWidth() &&
745          KnownZero.getBitWidth() == Max.getBitWidth() &&
746          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
747   APInt UnknownBits = ~(KnownZero|KnownOne);
748   
749   // The minimum value is when the unknown bits are all zeros.
750   Min = KnownOne;
751   // The maximum value is when the unknown bits are all ones.
752   Max = KnownOne|UnknownBits;
753 }
754
755 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
756 /// SimplifyDemandedBits knows about.  See if the instruction has any
757 /// properties that allow us to simplify its operands.
758 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
759   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
760   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
761   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
762   
763   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
764                                      KnownZero, KnownOne, 0);
765   if (V == 0) return false;
766   if (V == &Inst) return true;
767   ReplaceInstUsesWith(Inst, V);
768   return true;
769 }
770
771 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
772 /// specified instruction operand if possible, updating it in place.  It returns
773 /// true if it made any change and false otherwise.
774 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
775                                         APInt &KnownZero, APInt &KnownOne,
776                                         unsigned Depth) {
777   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
778                                           KnownZero, KnownOne, Depth);
779   if (NewVal == 0) return false;
780   U.set(NewVal);
781   return true;
782 }
783
784
785 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
786 /// value based on the demanded bits.  When this function is called, it is known
787 /// that only the bits set in DemandedMask of the result of V are ever used
788 /// downstream. Consequently, depending on the mask and V, it may be possible
789 /// to replace V with a constant or one of its operands. In such cases, this
790 /// function does the replacement and returns true. In all other cases, it
791 /// returns false after analyzing the expression and setting KnownOne and known
792 /// to be one in the expression.  KnownZero contains all the bits that are known
793 /// to be zero in the expression. These are provided to potentially allow the
794 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
795 /// the expression. KnownOne and KnownZero always follow the invariant that 
796 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
797 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
798 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
799 /// and KnownOne must all be the same.
800 ///
801 /// This returns null if it did not change anything and it permits no
802 /// simplification.  This returns V itself if it did some simplification of V's
803 /// operands based on the information about what bits are demanded. This returns
804 /// some other non-null value if it found out that V is equal to another value
805 /// in the context where the specified bits are demanded, but not for all users.
806 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
807                                              APInt &KnownZero, APInt &KnownOne,
808                                              unsigned Depth) {
809   assert(V != 0 && "Null pointer of Value???");
810   assert(Depth <= 6 && "Limit Search Depth");
811   uint32_t BitWidth = DemandedMask.getBitWidth();
812   const Type *VTy = V->getType();
813   assert((TD || !isa<PointerType>(VTy)) &&
814          "SimplifyDemandedBits needs to know bit widths!");
815   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
816          (!VTy->isIntOrIntVector() ||
817           VTy->getScalarSizeInBits() == BitWidth) &&
818          KnownZero.getBitWidth() == BitWidth &&
819          KnownOne.getBitWidth() == BitWidth &&
820          "Value *V, DemandedMask, KnownZero and KnownOne "
821          "must have same BitWidth");
822   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
823     // We know all of the bits for a constant!
824     KnownOne = CI->getValue() & DemandedMask;
825     KnownZero = ~KnownOne & DemandedMask;
826     return 0;
827   }
828   if (isa<ConstantPointerNull>(V)) {
829     // We know all of the bits for a constant!
830     KnownOne.clear();
831     KnownZero = DemandedMask;
832     return 0;
833   }
834
835   KnownZero.clear();
836   KnownOne.clear();
837   if (DemandedMask == 0) {   // Not demanding any bits from V.
838     if (isa<UndefValue>(V))
839       return 0;
840     return UndefValue::get(VTy);
841   }
842   
843   if (Depth == 6)        // Limit search depth.
844     return 0;
845   
846   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
847   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
848
849   Instruction *I = dyn_cast<Instruction>(V);
850   if (!I) {
851     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
852     return 0;        // Only analyze instructions.
853   }
854
855   // If there are multiple uses of this value and we aren't at the root, then
856   // we can't do any simplifications of the operands, because DemandedMask
857   // only reflects the bits demanded by *one* of the users.
858   if (Depth != 0 && !I->hasOneUse()) {
859     // Despite the fact that we can't simplify this instruction in all User's
860     // context, we can at least compute the knownzero/knownone bits, and we can
861     // do simplifications that apply to *just* the one user if we know that
862     // this instruction has a simpler value in that context.
863     if (I->getOpcode() == Instruction::And) {
864       // If either the LHS or the RHS are Zero, the result is zero.
865       ComputeMaskedBits(I->getOperand(1), DemandedMask,
866                         RHSKnownZero, RHSKnownOne, Depth+1);
867       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
868                         LHSKnownZero, LHSKnownOne, Depth+1);
869       
870       // If all of the demanded bits are known 1 on one side, return the other.
871       // These bits cannot contribute to the result of the 'and' in this
872       // context.
873       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
874           (DemandedMask & ~LHSKnownZero))
875         return I->getOperand(0);
876       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
877           (DemandedMask & ~RHSKnownZero))
878         return I->getOperand(1);
879       
880       // If all of the demanded bits in the inputs are known zeros, return zero.
881       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
882         return Constant::getNullValue(VTy);
883       
884     } else if (I->getOpcode() == Instruction::Or) {
885       // We can simplify (X|Y) -> X or Y in the user's context if we know that
886       // only bits from X or Y are demanded.
887       
888       // If either the LHS or the RHS are One, the result is One.
889       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
890                         RHSKnownZero, RHSKnownOne, Depth+1);
891       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
892                         LHSKnownZero, LHSKnownOne, Depth+1);
893       
894       // If all of the demanded bits are known zero on one side, return the
895       // other.  These bits cannot contribute to the result of the 'or' in this
896       // context.
897       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
898           (DemandedMask & ~LHSKnownOne))
899         return I->getOperand(0);
900       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
901           (DemandedMask & ~RHSKnownOne))
902         return I->getOperand(1);
903       
904       // If all of the potentially set bits on one side are known to be set on
905       // the other side, just use the 'other' side.
906       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
907           (DemandedMask & (~RHSKnownZero)))
908         return I->getOperand(0);
909       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
910           (DemandedMask & (~LHSKnownZero)))
911         return I->getOperand(1);
912     }
913     
914     // Compute the KnownZero/KnownOne bits to simplify things downstream.
915     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
916     return 0;
917   }
918   
919   // If this is the root being simplified, allow it to have multiple uses,
920   // just set the DemandedMask to all bits so that we can try to simplify the
921   // operands.  This allows visitTruncInst (for example) to simplify the
922   // operand of a trunc without duplicating all the logic below.
923   if (Depth == 0 && !V->hasOneUse())
924     DemandedMask = APInt::getAllOnesValue(BitWidth);
925   
926   switch (I->getOpcode()) {
927   default:
928     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
929     break;
930   case Instruction::And:
931     // If either the LHS or the RHS are Zero, the result is zero.
932     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
933                              RHSKnownZero, RHSKnownOne, Depth+1) ||
934         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
935                              LHSKnownZero, LHSKnownOne, Depth+1))
936       return I;
937     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
938     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
939
940     // If all of the demanded bits are known 1 on one side, return the other.
941     // These bits cannot contribute to the result of the 'and'.
942     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
943         (DemandedMask & ~LHSKnownZero))
944       return I->getOperand(0);
945     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
946         (DemandedMask & ~RHSKnownZero))
947       return I->getOperand(1);
948     
949     // If all of the demanded bits in the inputs are known zeros, return zero.
950     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
951       return Constant::getNullValue(VTy);
952       
953     // If the RHS is a constant, see if we can simplify it.
954     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
955       return I;
956       
957     // Output known-1 bits are only known if set in both the LHS & RHS.
958     RHSKnownOne &= LHSKnownOne;
959     // Output known-0 are known to be clear if zero in either the LHS | RHS.
960     RHSKnownZero |= LHSKnownZero;
961     break;
962   case Instruction::Or:
963     // If either the LHS or the RHS are One, the result is One.
964     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
965                              RHSKnownZero, RHSKnownOne, Depth+1) ||
966         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
967                              LHSKnownZero, LHSKnownOne, Depth+1))
968       return I;
969     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
970     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
971     
972     // If all of the demanded bits are known zero on one side, return the other.
973     // These bits cannot contribute to the result of the 'or'.
974     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
975         (DemandedMask & ~LHSKnownOne))
976       return I->getOperand(0);
977     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
978         (DemandedMask & ~RHSKnownOne))
979       return I->getOperand(1);
980
981     // If all of the potentially set bits on one side are known to be set on
982     // the other side, just use the 'other' side.
983     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
984         (DemandedMask & (~RHSKnownZero)))
985       return I->getOperand(0);
986     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
987         (DemandedMask & (~LHSKnownZero)))
988       return I->getOperand(1);
989         
990     // If the RHS is a constant, see if we can simplify it.
991     if (ShrinkDemandedConstant(I, 1, DemandedMask))
992       return I;
993           
994     // Output known-0 bits are only known if clear in both the LHS & RHS.
995     RHSKnownZero &= LHSKnownZero;
996     // Output known-1 are known to be set if set in either the LHS | RHS.
997     RHSKnownOne |= LHSKnownOne;
998     break;
999   case Instruction::Xor: {
1000     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1001                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1002         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1003                              LHSKnownZero, LHSKnownOne, Depth+1))
1004       return I;
1005     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1006     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1007     
1008     // If all of the demanded bits are known zero on one side, return the other.
1009     // These bits cannot contribute to the result of the 'xor'.
1010     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1011       return I->getOperand(0);
1012     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1013       return I->getOperand(1);
1014     
1015     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1016     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1017                          (RHSKnownOne & LHSKnownOne);
1018     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1019     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1020                         (RHSKnownOne & LHSKnownZero);
1021     
1022     // If all of the demanded bits are known to be zero on one side or the
1023     // other, turn this into an *inclusive* or.
1024     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1025     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1026       Instruction *Or =
1027         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1028                                  I->getName());
1029       return InsertNewInstBefore(Or, *I);
1030     }
1031     
1032     // If all of the demanded bits on one side are known, and all of the set
1033     // bits on that side are also known to be set on the other side, turn this
1034     // into an AND, as we know the bits will be cleared.
1035     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1036     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1037       // all known
1038       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1039         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1040         Instruction *And = 
1041           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1042         return InsertNewInstBefore(And, *I);
1043       }
1044     }
1045     
1046     // If the RHS is a constant, see if we can simplify it.
1047     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1048     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1049       return I;
1050     
1051     RHSKnownZero = KnownZeroOut;
1052     RHSKnownOne  = KnownOneOut;
1053     break;
1054   }
1055   case Instruction::Select:
1056     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1057                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1058         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1059                              LHSKnownZero, LHSKnownOne, Depth+1))
1060       return I;
1061     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1062     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1063     
1064     // If the operands are constants, see if we can simplify them.
1065     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1066         ShrinkDemandedConstant(I, 2, DemandedMask))
1067       return I;
1068     
1069     // Only known if known in both the LHS and RHS.
1070     RHSKnownOne &= LHSKnownOne;
1071     RHSKnownZero &= LHSKnownZero;
1072     break;
1073   case Instruction::Trunc: {
1074     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1075     DemandedMask.zext(truncBf);
1076     RHSKnownZero.zext(truncBf);
1077     RHSKnownOne.zext(truncBf);
1078     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1079                              RHSKnownZero, RHSKnownOne, Depth+1))
1080       return I;
1081     DemandedMask.trunc(BitWidth);
1082     RHSKnownZero.trunc(BitWidth);
1083     RHSKnownOne.trunc(BitWidth);
1084     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1085     break;
1086   }
1087   case Instruction::BitCast:
1088     if (!I->getOperand(0)->getType()->isInteger())
1089       return false;  // vector->int or fp->int?
1090     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1091                              RHSKnownZero, RHSKnownOne, Depth+1))
1092       return I;
1093     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1094     break;
1095   case Instruction::ZExt: {
1096     // Compute the bits in the result that are not present in the input.
1097     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1098     
1099     DemandedMask.trunc(SrcBitWidth);
1100     RHSKnownZero.trunc(SrcBitWidth);
1101     RHSKnownOne.trunc(SrcBitWidth);
1102     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1103                              RHSKnownZero, RHSKnownOne, Depth+1))
1104       return I;
1105     DemandedMask.zext(BitWidth);
1106     RHSKnownZero.zext(BitWidth);
1107     RHSKnownOne.zext(BitWidth);
1108     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1109     // The top bits are known to be zero.
1110     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1111     break;
1112   }
1113   case Instruction::SExt: {
1114     // Compute the bits in the result that are not present in the input.
1115     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1116     
1117     APInt InputDemandedBits = DemandedMask & 
1118                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1119
1120     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1121     // If any of the sign extended bits are demanded, we know that the sign
1122     // bit is demanded.
1123     if ((NewBits & DemandedMask) != 0)
1124       InputDemandedBits.set(SrcBitWidth-1);
1125       
1126     InputDemandedBits.trunc(SrcBitWidth);
1127     RHSKnownZero.trunc(SrcBitWidth);
1128     RHSKnownOne.trunc(SrcBitWidth);
1129     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1130                              RHSKnownZero, RHSKnownOne, Depth+1))
1131       return I;
1132     InputDemandedBits.zext(BitWidth);
1133     RHSKnownZero.zext(BitWidth);
1134     RHSKnownOne.zext(BitWidth);
1135     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1136       
1137     // If the sign bit of the input is known set or clear, then we know the
1138     // top bits of the result.
1139
1140     // If the input sign bit is known zero, or if the NewBits are not demanded
1141     // convert this into a zero extension.
1142     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1143       // Convert to ZExt cast
1144       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1145       return InsertNewInstBefore(NewCast, *I);
1146     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1147       RHSKnownOne |= NewBits;
1148     }
1149     break;
1150   }
1151   case Instruction::Add: {
1152     // Figure out what the input bits are.  If the top bits of the and result
1153     // are not demanded, then the add doesn't demand them from its input
1154     // either.
1155     unsigned NLZ = DemandedMask.countLeadingZeros();
1156       
1157     // If there is a constant on the RHS, there are a variety of xformations
1158     // we can do.
1159     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1160       // If null, this should be simplified elsewhere.  Some of the xforms here
1161       // won't work if the RHS is zero.
1162       if (RHS->isZero())
1163         break;
1164       
1165       // If the top bit of the output is demanded, demand everything from the
1166       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1167       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1168
1169       // Find information about known zero/one bits in the input.
1170       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1171                                LHSKnownZero, LHSKnownOne, Depth+1))
1172         return I;
1173
1174       // If the RHS of the add has bits set that can't affect the input, reduce
1175       // the constant.
1176       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1177         return I;
1178       
1179       // Avoid excess work.
1180       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1181         break;
1182       
1183       // Turn it into OR if input bits are zero.
1184       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1185         Instruction *Or =
1186           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1187                                    I->getName());
1188         return InsertNewInstBefore(Or, *I);
1189       }
1190       
1191       // We can say something about the output known-zero and known-one bits,
1192       // depending on potential carries from the input constant and the
1193       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1194       // bits set and the RHS constant is 0x01001, then we know we have a known
1195       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1196       
1197       // To compute this, we first compute the potential carry bits.  These are
1198       // the bits which may be modified.  I'm not aware of a better way to do
1199       // this scan.
1200       const APInt &RHSVal = RHS->getValue();
1201       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1202       
1203       // Now that we know which bits have carries, compute the known-1/0 sets.
1204       
1205       // Bits are known one if they are known zero in one operand and one in the
1206       // other, and there is no input carry.
1207       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1208                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1209       
1210       // Bits are known zero if they are known zero in both operands and there
1211       // is no input carry.
1212       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1213     } else {
1214       // If the high-bits of this ADD are not demanded, then it does not demand
1215       // the high bits of its LHS or RHS.
1216       if (DemandedMask[BitWidth-1] == 0) {
1217         // Right fill the mask of bits for this ADD to demand the most
1218         // significant bit and all those below it.
1219         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1220         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1221                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1222             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1223                                  LHSKnownZero, LHSKnownOne, Depth+1))
1224           return I;
1225       }
1226     }
1227     break;
1228   }
1229   case Instruction::Sub:
1230     // If the high-bits of this SUB are not demanded, then it does not demand
1231     // the high bits of its LHS or RHS.
1232     if (DemandedMask[BitWidth-1] == 0) {
1233       // Right fill the mask of bits for this SUB to demand the most
1234       // significant bit and all those below it.
1235       uint32_t NLZ = DemandedMask.countLeadingZeros();
1236       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1237       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1238                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1239           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1240                                LHSKnownZero, LHSKnownOne, Depth+1))
1241         return I;
1242     }
1243     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1244     // the known zeros and ones.
1245     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1246     break;
1247   case Instruction::Shl:
1248     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1249       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1250       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1251       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1252                                RHSKnownZero, RHSKnownOne, Depth+1))
1253         return I;
1254       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1255       RHSKnownZero <<= ShiftAmt;
1256       RHSKnownOne  <<= ShiftAmt;
1257       // low bits known zero.
1258       if (ShiftAmt)
1259         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1260     }
1261     break;
1262   case Instruction::LShr:
1263     // For a logical shift right
1264     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1265       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1266       
1267       // Unsigned shift right.
1268       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1269       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1270                                RHSKnownZero, RHSKnownOne, Depth+1))
1271         return I;
1272       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1273       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1274       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1275       if (ShiftAmt) {
1276         // Compute the new bits that are at the top now.
1277         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1278         RHSKnownZero |= HighBits;  // high bits known zero.
1279       }
1280     }
1281     break;
1282   case Instruction::AShr:
1283     // If this is an arithmetic shift right and only the low-bit is set, we can
1284     // always convert this into a logical shr, even if the shift amount is
1285     // variable.  The low bit of the shift cannot be an input sign bit unless
1286     // the shift amount is >= the size of the datatype, which is undefined.
1287     if (DemandedMask == 1) {
1288       // Perform the logical shift right.
1289       Instruction *NewVal = BinaryOperator::CreateLShr(
1290                         I->getOperand(0), I->getOperand(1), I->getName());
1291       return InsertNewInstBefore(NewVal, *I);
1292     }    
1293
1294     // If the sign bit is the only bit demanded by this ashr, then there is no
1295     // need to do it, the shift doesn't change the high bit.
1296     if (DemandedMask.isSignBit())
1297       return I->getOperand(0);
1298     
1299     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1300       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1301       
1302       // Signed shift right.
1303       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1304       // If any of the "high bits" are demanded, we should set the sign bit as
1305       // demanded.
1306       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1307         DemandedMaskIn.set(BitWidth-1);
1308       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1309                                RHSKnownZero, RHSKnownOne, Depth+1))
1310         return I;
1311       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1312       // Compute the new bits that are at the top now.
1313       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1314       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1315       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1316         
1317       // Handle the sign bits.
1318       APInt SignBit(APInt::getSignBit(BitWidth));
1319       // Adjust to where it is now in the mask.
1320       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1321         
1322       // If the input sign bit is known to be zero, or if none of the top bits
1323       // are demanded, turn this into an unsigned shift right.
1324       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1325           (HighBits & ~DemandedMask) == HighBits) {
1326         // Perform the logical shift right.
1327         Instruction *NewVal = BinaryOperator::CreateLShr(
1328                           I->getOperand(0), SA, I->getName());
1329         return InsertNewInstBefore(NewVal, *I);
1330       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1331         RHSKnownOne |= HighBits;
1332       }
1333     }
1334     break;
1335   case Instruction::SRem:
1336     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1337       APInt RA = Rem->getValue().abs();
1338       if (RA.isPowerOf2()) {
1339         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1340           return I->getOperand(0);
1341
1342         APInt LowBits = RA - 1;
1343         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1344         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1345                                  LHSKnownZero, LHSKnownOne, Depth+1))
1346           return I;
1347
1348         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1349           LHSKnownZero |= ~LowBits;
1350
1351         KnownZero |= LHSKnownZero & DemandedMask;
1352
1353         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1354       }
1355     }
1356     break;
1357   case Instruction::URem: {
1358     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1359     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1360     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1361                              KnownZero2, KnownOne2, Depth+1) ||
1362         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1363                              KnownZero2, KnownOne2, Depth+1))
1364       return I;
1365
1366     unsigned Leaders = KnownZero2.countLeadingOnes();
1367     Leaders = std::max(Leaders,
1368                        KnownZero2.countLeadingOnes());
1369     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1370     break;
1371   }
1372   case Instruction::Call:
1373     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1374       switch (II->getIntrinsicID()) {
1375       default: break;
1376       case Intrinsic::bswap: {
1377         // If the only bits demanded come from one byte of the bswap result,
1378         // just shift the input byte into position to eliminate the bswap.
1379         unsigned NLZ = DemandedMask.countLeadingZeros();
1380         unsigned NTZ = DemandedMask.countTrailingZeros();
1381           
1382         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1383         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1384         // have 14 leading zeros, round to 8.
1385         NLZ &= ~7;
1386         NTZ &= ~7;
1387         // If we need exactly one byte, we can do this transformation.
1388         if (BitWidth-NLZ-NTZ == 8) {
1389           unsigned ResultBit = NTZ;
1390           unsigned InputBit = BitWidth-NTZ-8;
1391           
1392           // Replace this with either a left or right shift to get the byte into
1393           // the right place.
1394           Instruction *NewVal;
1395           if (InputBit > ResultBit)
1396             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1397                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1398           else
1399             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1400                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1401           NewVal->takeName(I);
1402           return InsertNewInstBefore(NewVal, *I);
1403         }
1404           
1405         // TODO: Could compute known zero/one bits based on the input.
1406         break;
1407       }
1408       }
1409     }
1410     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1411     break;
1412   }
1413   
1414   // If the client is only demanding bits that we know, return the known
1415   // constant.
1416   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1417     Constant *C = ConstantInt::get(RHSKnownOne);
1418     if (isa<PointerType>(V->getType()))
1419       C = ConstantExpr::getIntToPtr(C, V->getType());
1420     return C;
1421   }
1422   return false;
1423 }
1424
1425
1426 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1427 /// any number of elements. DemandedElts contains the set of elements that are
1428 /// actually used by the caller.  This method analyzes which elements of the
1429 /// operand are undef and returns that information in UndefElts.
1430 ///
1431 /// If the information about demanded elements can be used to simplify the
1432 /// operation, the operation is simplified, then the resultant value is
1433 /// returned.  This returns null if no change was made.
1434 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1435                                                 APInt& UndefElts,
1436                                                 unsigned Depth) {
1437   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1438   APInt EltMask(APInt::getAllOnesValue(VWidth));
1439   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1440
1441   if (isa<UndefValue>(V)) {
1442     // If the entire vector is undefined, just return this info.
1443     UndefElts = EltMask;
1444     return 0;
1445   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1446     UndefElts = EltMask;
1447     return UndefValue::get(V->getType());
1448   }
1449
1450   UndefElts = 0;
1451   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1452     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1453     Constant *Undef = UndefValue::get(EltTy);
1454
1455     std::vector<Constant*> Elts;
1456     for (unsigned i = 0; i != VWidth; ++i)
1457       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1458         Elts.push_back(Undef);
1459         UndefElts.set(i);
1460       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1461         Elts.push_back(Undef);
1462         UndefElts.set(i);
1463       } else {                               // Otherwise, defined.
1464         Elts.push_back(CP->getOperand(i));
1465       }
1466
1467     // If we changed the constant, return it.
1468     Constant *NewCP = ConstantVector::get(Elts);
1469     return NewCP != CP ? NewCP : 0;
1470   } else if (isa<ConstantAggregateZero>(V)) {
1471     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1472     // set to undef.
1473     
1474     // Check if this is identity. If so, return 0 since we are not simplifying
1475     // anything.
1476     if (DemandedElts == ((1ULL << VWidth) -1))
1477       return 0;
1478     
1479     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1480     Constant *Zero = Constant::getNullValue(EltTy);
1481     Constant *Undef = UndefValue::get(EltTy);
1482     std::vector<Constant*> Elts;
1483     for (unsigned i = 0; i != VWidth; ++i) {
1484       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1485       Elts.push_back(Elt);
1486     }
1487     UndefElts = DemandedElts ^ EltMask;
1488     return ConstantVector::get(Elts);
1489   }
1490   
1491   // Limit search depth.
1492   if (Depth == 10)
1493     return 0;
1494
1495   // If multiple users are using the root value, procede with
1496   // simplification conservatively assuming that all elements
1497   // are needed.
1498   if (!V->hasOneUse()) {
1499     // Quit if we find multiple users of a non-root value though.
1500     // They'll be handled when it's their turn to be visited by
1501     // the main instcombine process.
1502     if (Depth != 0)
1503       // TODO: Just compute the UndefElts information recursively.
1504       return 0;
1505
1506     // Conservatively assume that all elements are needed.
1507     DemandedElts = EltMask;
1508   }
1509   
1510   Instruction *I = dyn_cast<Instruction>(V);
1511   if (!I) return 0;        // Only analyze instructions.
1512   
1513   bool MadeChange = false;
1514   APInt UndefElts2(VWidth, 0);
1515   Value *TmpV;
1516   switch (I->getOpcode()) {
1517   default: break;
1518     
1519   case Instruction::InsertElement: {
1520     // If this is a variable index, we don't know which element it overwrites.
1521     // demand exactly the same input as we produce.
1522     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1523     if (Idx == 0) {
1524       // Note that we can't propagate undef elt info, because we don't know
1525       // which elt is getting updated.
1526       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1527                                         UndefElts2, Depth+1);
1528       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1529       break;
1530     }
1531     
1532     // If this is inserting an element that isn't demanded, remove this
1533     // insertelement.
1534     unsigned IdxNo = Idx->getZExtValue();
1535     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1536       return AddSoonDeadInstToWorklist(*I, 0);
1537     
1538     // Otherwise, the element inserted overwrites whatever was there, so the
1539     // input demanded set is simpler than the output set.
1540     APInt DemandedElts2 = DemandedElts;
1541     DemandedElts2.clear(IdxNo);
1542     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1543                                       UndefElts, Depth+1);
1544     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1545
1546     // The inserted element is defined.
1547     UndefElts.clear(IdxNo);
1548     break;
1549   }
1550   case Instruction::ShuffleVector: {
1551     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1552     uint64_t LHSVWidth =
1553       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1554     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1555     for (unsigned i = 0; i < VWidth; i++) {
1556       if (DemandedElts[i]) {
1557         unsigned MaskVal = Shuffle->getMaskValue(i);
1558         if (MaskVal != -1u) {
1559           assert(MaskVal < LHSVWidth * 2 &&
1560                  "shufflevector mask index out of range!");
1561           if (MaskVal < LHSVWidth)
1562             LeftDemanded.set(MaskVal);
1563           else
1564             RightDemanded.set(MaskVal - LHSVWidth);
1565         }
1566       }
1567     }
1568
1569     APInt UndefElts4(LHSVWidth, 0);
1570     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1571                                       UndefElts4, Depth+1);
1572     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1573
1574     APInt UndefElts3(LHSVWidth, 0);
1575     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1576                                       UndefElts3, Depth+1);
1577     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1578
1579     bool NewUndefElts = false;
1580     for (unsigned i = 0; i < VWidth; i++) {
1581       unsigned MaskVal = Shuffle->getMaskValue(i);
1582       if (MaskVal == -1u) {
1583         UndefElts.set(i);
1584       } else if (MaskVal < LHSVWidth) {
1585         if (UndefElts4[MaskVal]) {
1586           NewUndefElts = true;
1587           UndefElts.set(i);
1588         }
1589       } else {
1590         if (UndefElts3[MaskVal - LHSVWidth]) {
1591           NewUndefElts = true;
1592           UndefElts.set(i);
1593         }
1594       }
1595     }
1596
1597     if (NewUndefElts) {
1598       // Add additional discovered undefs.
1599       std::vector<Constant*> Elts;
1600       for (unsigned i = 0; i < VWidth; ++i) {
1601         if (UndefElts[i])
1602           Elts.push_back(UndefValue::get(Type::Int32Ty));
1603         else
1604           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1605                                           Shuffle->getMaskValue(i)));
1606       }
1607       I->setOperand(2, ConstantVector::get(Elts));
1608       MadeChange = true;
1609     }
1610     break;
1611   }
1612   case Instruction::BitCast: {
1613     // Vector->vector casts only.
1614     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1615     if (!VTy) break;
1616     unsigned InVWidth = VTy->getNumElements();
1617     APInt InputDemandedElts(InVWidth, 0);
1618     unsigned Ratio;
1619
1620     if (VWidth == InVWidth) {
1621       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1622       // elements as are demanded of us.
1623       Ratio = 1;
1624       InputDemandedElts = DemandedElts;
1625     } else if (VWidth > InVWidth) {
1626       // Untested so far.
1627       break;
1628       
1629       // If there are more elements in the result than there are in the source,
1630       // then an input element is live if any of the corresponding output
1631       // elements are live.
1632       Ratio = VWidth/InVWidth;
1633       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1634         if (DemandedElts[OutIdx])
1635           InputDemandedElts.set(OutIdx/Ratio);
1636       }
1637     } else {
1638       // Untested so far.
1639       break;
1640       
1641       // If there are more elements in the source than there are in the result,
1642       // then an input element is live if the corresponding output element is
1643       // live.
1644       Ratio = InVWidth/VWidth;
1645       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1646         if (DemandedElts[InIdx/Ratio])
1647           InputDemandedElts.set(InIdx);
1648     }
1649     
1650     // div/rem demand all inputs, because they don't want divide by zero.
1651     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1652                                       UndefElts2, Depth+1);
1653     if (TmpV) {
1654       I->setOperand(0, TmpV);
1655       MadeChange = true;
1656     }
1657     
1658     UndefElts = UndefElts2;
1659     if (VWidth > InVWidth) {
1660       assert(0 && "Unimp");
1661       // If there are more elements in the result than there are in the source,
1662       // then an output element is undef if the corresponding input element is
1663       // undef.
1664       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1665         if (UndefElts2[OutIdx/Ratio])
1666           UndefElts.set(OutIdx);
1667     } else if (VWidth < InVWidth) {
1668       assert(0 && "Unimp");
1669       // If there are more elements in the source than there are in the result,
1670       // then a result element is undef if all of the corresponding input
1671       // elements are undef.
1672       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1673       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1674         if (!UndefElts2[InIdx])            // Not undef?
1675           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1676     }
1677     break;
1678   }
1679   case Instruction::And:
1680   case Instruction::Or:
1681   case Instruction::Xor:
1682   case Instruction::Add:
1683   case Instruction::Sub:
1684   case Instruction::Mul:
1685     // div/rem demand all inputs, because they don't want divide by zero.
1686     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1687                                       UndefElts, Depth+1);
1688     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1689     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1690                                       UndefElts2, Depth+1);
1691     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1692       
1693     // Output elements are undefined if both are undefined.  Consider things
1694     // like undef&0.  The result is known zero, not undef.
1695     UndefElts &= UndefElts2;
1696     break;
1697     
1698   case Instruction::Call: {
1699     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1700     if (!II) break;
1701     switch (II->getIntrinsicID()) {
1702     default: break;
1703       
1704     // Binary vector operations that work column-wise.  A dest element is a
1705     // function of the corresponding input elements from the two inputs.
1706     case Intrinsic::x86_sse_sub_ss:
1707     case Intrinsic::x86_sse_mul_ss:
1708     case Intrinsic::x86_sse_min_ss:
1709     case Intrinsic::x86_sse_max_ss:
1710     case Intrinsic::x86_sse2_sub_sd:
1711     case Intrinsic::x86_sse2_mul_sd:
1712     case Intrinsic::x86_sse2_min_sd:
1713     case Intrinsic::x86_sse2_max_sd:
1714       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1715                                         UndefElts, Depth+1);
1716       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1717       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1718                                         UndefElts2, Depth+1);
1719       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1720
1721       // If only the low elt is demanded and this is a scalarizable intrinsic,
1722       // scalarize it now.
1723       if (DemandedElts == 1) {
1724         switch (II->getIntrinsicID()) {
1725         default: break;
1726         case Intrinsic::x86_sse_sub_ss:
1727         case Intrinsic::x86_sse_mul_ss:
1728         case Intrinsic::x86_sse2_sub_sd:
1729         case Intrinsic::x86_sse2_mul_sd:
1730           // TODO: Lower MIN/MAX/ABS/etc
1731           Value *LHS = II->getOperand(1);
1732           Value *RHS = II->getOperand(2);
1733           // Extract the element as scalars.
1734           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1735           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1736           
1737           switch (II->getIntrinsicID()) {
1738           default: assert(0 && "Case stmts out of sync!");
1739           case Intrinsic::x86_sse_sub_ss:
1740           case Intrinsic::x86_sse2_sub_sd:
1741             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1742                                                         II->getName()), *II);
1743             break;
1744           case Intrinsic::x86_sse_mul_ss:
1745           case Intrinsic::x86_sse2_mul_sd:
1746             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1747                                                          II->getName()), *II);
1748             break;
1749           }
1750           
1751           Instruction *New =
1752             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1753                                       II->getName());
1754           InsertNewInstBefore(New, *II);
1755           AddSoonDeadInstToWorklist(*II, 0);
1756           return New;
1757         }            
1758       }
1759         
1760       // Output elements are undefined if both are undefined.  Consider things
1761       // like undef&0.  The result is known zero, not undef.
1762       UndefElts &= UndefElts2;
1763       break;
1764     }
1765     break;
1766   }
1767   }
1768   return MadeChange ? I : 0;
1769 }
1770
1771
1772 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1773 /// function is designed to check a chain of associative operators for a
1774 /// potential to apply a certain optimization.  Since the optimization may be
1775 /// applicable if the expression was reassociated, this checks the chain, then
1776 /// reassociates the expression as necessary to expose the optimization
1777 /// opportunity.  This makes use of a special Functor, which must define
1778 /// 'shouldApply' and 'apply' methods.
1779 ///
1780 template<typename Functor>
1781 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1782   unsigned Opcode = Root.getOpcode();
1783   Value *LHS = Root.getOperand(0);
1784
1785   // Quick check, see if the immediate LHS matches...
1786   if (F.shouldApply(LHS))
1787     return F.apply(Root);
1788
1789   // Otherwise, if the LHS is not of the same opcode as the root, return.
1790   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1791   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1792     // Should we apply this transform to the RHS?
1793     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1794
1795     // If not to the RHS, check to see if we should apply to the LHS...
1796     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1797       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1798       ShouldApply = true;
1799     }
1800
1801     // If the functor wants to apply the optimization to the RHS of LHSI,
1802     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1803     if (ShouldApply) {
1804       // Now all of the instructions are in the current basic block, go ahead
1805       // and perform the reassociation.
1806       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1807
1808       // First move the selected RHS to the LHS of the root...
1809       Root.setOperand(0, LHSI->getOperand(1));
1810
1811       // Make what used to be the LHS of the root be the user of the root...
1812       Value *ExtraOperand = TmpLHSI->getOperand(1);
1813       if (&Root == TmpLHSI) {
1814         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1815         return 0;
1816       }
1817       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1818       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1819       BasicBlock::iterator ARI = &Root; ++ARI;
1820       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1821       ARI = Root;
1822
1823       // Now propagate the ExtraOperand down the chain of instructions until we
1824       // get to LHSI.
1825       while (TmpLHSI != LHSI) {
1826         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1827         // Move the instruction to immediately before the chain we are
1828         // constructing to avoid breaking dominance properties.
1829         NextLHSI->moveBefore(ARI);
1830         ARI = NextLHSI;
1831
1832         Value *NextOp = NextLHSI->getOperand(1);
1833         NextLHSI->setOperand(1, ExtraOperand);
1834         TmpLHSI = NextLHSI;
1835         ExtraOperand = NextOp;
1836       }
1837
1838       // Now that the instructions are reassociated, have the functor perform
1839       // the transformation...
1840       return F.apply(Root);
1841     }
1842
1843     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1844   }
1845   return 0;
1846 }
1847
1848 namespace {
1849
1850 // AddRHS - Implements: X + X --> X << 1
1851 struct AddRHS {
1852   Value *RHS;
1853   AddRHS(Value *rhs) : RHS(rhs) {}
1854   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1855   Instruction *apply(BinaryOperator &Add) const {
1856     return BinaryOperator::CreateShl(Add.getOperand(0),
1857                                      ConstantInt::get(Add.getType(), 1));
1858   }
1859 };
1860
1861 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1862 //                 iff C1&C2 == 0
1863 struct AddMaskingAnd {
1864   Constant *C2;
1865   AddMaskingAnd(Constant *c) : C2(c) {}
1866   bool shouldApply(Value *LHS) const {
1867     ConstantInt *C1;
1868     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1869            ConstantExpr::getAnd(C1, C2)->isNullValue();
1870   }
1871   Instruction *apply(BinaryOperator &Add) const {
1872     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1873   }
1874 };
1875
1876 }
1877
1878 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1879                                              InstCombiner *IC) {
1880   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1881     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1882   }
1883
1884   // Figure out if the constant is the left or the right argument.
1885   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1886   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1887
1888   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1889     if (ConstIsRHS)
1890       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1891     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1892   }
1893
1894   Value *Op0 = SO, *Op1 = ConstOperand;
1895   if (!ConstIsRHS)
1896     std::swap(Op0, Op1);
1897   Instruction *New;
1898   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1899     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1900   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1901     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1902                           SO->getName()+".cmp");
1903   else {
1904     assert(0 && "Unknown binary instruction type!");
1905     abort();
1906   }
1907   return IC->InsertNewInstBefore(New, I);
1908 }
1909
1910 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1911 // constant as the other operand, try to fold the binary operator into the
1912 // select arguments.  This also works for Cast instructions, which obviously do
1913 // not have a second operand.
1914 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1915                                      InstCombiner *IC) {
1916   // Don't modify shared select instructions
1917   if (!SI->hasOneUse()) return 0;
1918   Value *TV = SI->getOperand(1);
1919   Value *FV = SI->getOperand(2);
1920
1921   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1922     // Bool selects with constant operands can be folded to logical ops.
1923     if (SI->getType() == Type::Int1Ty) return 0;
1924
1925     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1926     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1927
1928     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1929                               SelectFalseVal);
1930   }
1931   return 0;
1932 }
1933
1934
1935 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1936 /// node as operand #0, see if we can fold the instruction into the PHI (which
1937 /// is only possible if all operands to the PHI are constants).
1938 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1939   PHINode *PN = cast<PHINode>(I.getOperand(0));
1940   unsigned NumPHIValues = PN->getNumIncomingValues();
1941   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1942
1943   // Check to see if all of the operands of the PHI are constants.  If there is
1944   // one non-constant value, remember the BB it is.  If there is more than one
1945   // or if *it* is a PHI, bail out.
1946   BasicBlock *NonConstBB = 0;
1947   for (unsigned i = 0; i != NumPHIValues; ++i)
1948     if (!isa<Constant>(PN->getIncomingValue(i))) {
1949       if (NonConstBB) return 0;  // More than one non-const value.
1950       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1951       NonConstBB = PN->getIncomingBlock(i);
1952       
1953       // If the incoming non-constant value is in I's block, we have an infinite
1954       // loop.
1955       if (NonConstBB == I.getParent())
1956         return 0;
1957     }
1958   
1959   // If there is exactly one non-constant value, we can insert a copy of the
1960   // operation in that block.  However, if this is a critical edge, we would be
1961   // inserting the computation one some other paths (e.g. inside a loop).  Only
1962   // do this if the pred block is unconditionally branching into the phi block.
1963   if (NonConstBB) {
1964     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1965     if (!BI || !BI->isUnconditional()) return 0;
1966   }
1967
1968   // Okay, we can do the transformation: create the new PHI node.
1969   PHINode *NewPN = PHINode::Create(I.getType(), "");
1970   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1971   InsertNewInstBefore(NewPN, *PN);
1972   NewPN->takeName(PN);
1973
1974   // Next, add all of the operands to the PHI.
1975   if (I.getNumOperands() == 2) {
1976     Constant *C = cast<Constant>(I.getOperand(1));
1977     for (unsigned i = 0; i != NumPHIValues; ++i) {
1978       Value *InV = 0;
1979       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1980         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1981           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1982         else
1983           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1984       } else {
1985         assert(PN->getIncomingBlock(i) == NonConstBB);
1986         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1987           InV = BinaryOperator::Create(BO->getOpcode(),
1988                                        PN->getIncomingValue(i), C, "phitmp",
1989                                        NonConstBB->getTerminator());
1990         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1991           InV = CmpInst::Create(CI->getOpcode(), 
1992                                 CI->getPredicate(),
1993                                 PN->getIncomingValue(i), C, "phitmp",
1994                                 NonConstBB->getTerminator());
1995         else
1996           assert(0 && "Unknown binop!");
1997         
1998         AddToWorkList(cast<Instruction>(InV));
1999       }
2000       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2001     }
2002   } else { 
2003     CastInst *CI = cast<CastInst>(&I);
2004     const Type *RetTy = CI->getType();
2005     for (unsigned i = 0; i != NumPHIValues; ++i) {
2006       Value *InV;
2007       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2008         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2009       } else {
2010         assert(PN->getIncomingBlock(i) == NonConstBB);
2011         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2012                                I.getType(), "phitmp", 
2013                                NonConstBB->getTerminator());
2014         AddToWorkList(cast<Instruction>(InV));
2015       }
2016       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2017     }
2018   }
2019   return ReplaceInstUsesWith(I, NewPN);
2020 }
2021
2022
2023 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2024 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2025 /// This basically requires proving that the add in the original type would not
2026 /// overflow to change the sign bit or have a carry out.
2027 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2028   // There are different heuristics we can use for this.  Here are some simple
2029   // ones.
2030   
2031   // Add has the property that adding any two 2's complement numbers can only 
2032   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2033   // have at least two sign bits, we know that the addition of the two values will
2034   // sign extend fine.
2035   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2036     return true;
2037   
2038   
2039   // If one of the operands only has one non-zero bit, and if the other operand
2040   // has a known-zero bit in a more significant place than it (not including the
2041   // sign bit) the ripple may go up to and fill the zero, but won't change the
2042   // sign.  For example, (X & ~4) + 1.
2043   
2044   // TODO: Implement.
2045   
2046   return false;
2047 }
2048
2049
2050 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2051   bool Changed = SimplifyCommutative(I);
2052   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2053
2054   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2055     // X + undef -> undef
2056     if (isa<UndefValue>(RHS))
2057       return ReplaceInstUsesWith(I, RHS);
2058
2059     // X + 0 --> X
2060     if (RHSC->isNullValue())
2061       return ReplaceInstUsesWith(I, LHS);
2062
2063     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2064       // X + (signbit) --> X ^ signbit
2065       const APInt& Val = CI->getValue();
2066       uint32_t BitWidth = Val.getBitWidth();
2067       if (Val == APInt::getSignBit(BitWidth))
2068         return BinaryOperator::CreateXor(LHS, RHS);
2069       
2070       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2071       // (X & 254)+1 -> (X&254)|1
2072       if (SimplifyDemandedInstructionBits(I))
2073         return &I;
2074
2075       // zext(i1) - 1  ->  select i1, 0, -1
2076       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2077         if (CI->isAllOnesValue() &&
2078             ZI->getOperand(0)->getType() == Type::Int1Ty)
2079           return SelectInst::Create(ZI->getOperand(0),
2080                                     Constant::getNullValue(I.getType()),
2081                                     ConstantInt::getAllOnesValue(I.getType()));
2082     }
2083
2084     if (isa<PHINode>(LHS))
2085       if (Instruction *NV = FoldOpIntoPhi(I))
2086         return NV;
2087     
2088     ConstantInt *XorRHS = 0;
2089     Value *XorLHS = 0;
2090     if (isa<ConstantInt>(RHSC) &&
2091         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2092       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2093       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2094       
2095       uint32_t Size = TySizeBits / 2;
2096       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2097       APInt CFF80Val(-C0080Val);
2098       do {
2099         if (TySizeBits > Size) {
2100           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2101           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2102           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2103               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2104             // This is a sign extend if the top bits are known zero.
2105             if (!MaskedValueIsZero(XorLHS, 
2106                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2107               Size = 0;  // Not a sign ext, but can't be any others either.
2108             break;
2109           }
2110         }
2111         Size >>= 1;
2112         C0080Val = APIntOps::lshr(C0080Val, Size);
2113         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2114       } while (Size >= 1);
2115       
2116       // FIXME: This shouldn't be necessary. When the backends can handle types
2117       // with funny bit widths then this switch statement should be removed. It
2118       // is just here to get the size of the "middle" type back up to something
2119       // that the back ends can handle.
2120       const Type *MiddleType = 0;
2121       switch (Size) {
2122         default: break;
2123         case 32: MiddleType = Type::Int32Ty; break;
2124         case 16: MiddleType = Type::Int16Ty; break;
2125         case  8: MiddleType = Type::Int8Ty; break;
2126       }
2127       if (MiddleType) {
2128         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2129         InsertNewInstBefore(NewTrunc, I);
2130         return new SExtInst(NewTrunc, I.getType(), I.getName());
2131       }
2132     }
2133   }
2134
2135   if (I.getType() == Type::Int1Ty)
2136     return BinaryOperator::CreateXor(LHS, RHS);
2137
2138   // X + X --> X << 1
2139   if (I.getType()->isInteger()) {
2140     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2141
2142     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2143       if (RHSI->getOpcode() == Instruction::Sub)
2144         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2145           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2146     }
2147     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2148       if (LHSI->getOpcode() == Instruction::Sub)
2149         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2150           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2151     }
2152   }
2153
2154   // -A + B  -->  B - A
2155   // -A + -B  -->  -(A + B)
2156   if (Value *LHSV = dyn_castNegVal(LHS)) {
2157     if (LHS->getType()->isIntOrIntVector()) {
2158       if (Value *RHSV = dyn_castNegVal(RHS)) {
2159         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2160         InsertNewInstBefore(NewAdd, I);
2161         return BinaryOperator::CreateNeg(NewAdd);
2162       }
2163     }
2164     
2165     return BinaryOperator::CreateSub(RHS, LHSV);
2166   }
2167
2168   // A + -B  -->  A - B
2169   if (!isa<Constant>(RHS))
2170     if (Value *V = dyn_castNegVal(RHS))
2171       return BinaryOperator::CreateSub(LHS, V);
2172
2173
2174   ConstantInt *C2;
2175   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2176     if (X == RHS)   // X*C + X --> X * (C+1)
2177       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2178
2179     // X*C1 + X*C2 --> X * (C1+C2)
2180     ConstantInt *C1;
2181     if (X == dyn_castFoldableMul(RHS, C1))
2182       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2183   }
2184
2185   // X + X*C --> X * (C+1)
2186   if (dyn_castFoldableMul(RHS, C2) == LHS)
2187     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2188
2189   // X + ~X --> -1   since   ~X = -X-1
2190   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2191     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2192   
2193
2194   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2195   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2196     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2197       return R;
2198   
2199   // A+B --> A|B iff A and B have no bits set in common.
2200   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2201     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2202     APInt LHSKnownOne(IT->getBitWidth(), 0);
2203     APInt LHSKnownZero(IT->getBitWidth(), 0);
2204     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2205     if (LHSKnownZero != 0) {
2206       APInt RHSKnownOne(IT->getBitWidth(), 0);
2207       APInt RHSKnownZero(IT->getBitWidth(), 0);
2208       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2209       
2210       // No bits in common -> bitwise or.
2211       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2212         return BinaryOperator::CreateOr(LHS, RHS);
2213     }
2214   }
2215
2216   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2217   if (I.getType()->isIntOrIntVector()) {
2218     Value *W, *X, *Y, *Z;
2219     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2220         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2221       if (W != Y) {
2222         if (W == Z) {
2223           std::swap(Y, Z);
2224         } else if (Y == X) {
2225           std::swap(W, X);
2226         } else if (X == Z) {
2227           std::swap(Y, Z);
2228           std::swap(W, X);
2229         }
2230       }
2231
2232       if (W == Y) {
2233         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2234                                                             LHS->getName()), I);
2235         return BinaryOperator::CreateMul(W, NewAdd);
2236       }
2237     }
2238   }
2239
2240   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2241     Value *X = 0;
2242     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2243       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2244
2245     // (X & FF00) + xx00  -> (X+xx00) & FF00
2246     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2247       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2248       if (Anded == CRHS) {
2249         // See if all bits from the first bit set in the Add RHS up are included
2250         // in the mask.  First, get the rightmost bit.
2251         const APInt& AddRHSV = CRHS->getValue();
2252
2253         // Form a mask of all bits from the lowest bit added through the top.
2254         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2255
2256         // See if the and mask includes all of these bits.
2257         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2258
2259         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2260           // Okay, the xform is safe.  Insert the new add pronto.
2261           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2262                                                             LHS->getName()), I);
2263           return BinaryOperator::CreateAnd(NewAdd, C2);
2264         }
2265       }
2266     }
2267
2268     // Try to fold constant add into select arguments.
2269     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2270       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2271         return R;
2272   }
2273
2274   // add (cast *A to intptrtype) B -> 
2275   //   cast (GEP (cast *A to i8*) B)  -->  intptrtype
2276   {
2277     CastInst *CI = dyn_cast<CastInst>(LHS);
2278     Value *Other = RHS;
2279     if (!CI) {
2280       CI = dyn_cast<CastInst>(RHS);
2281       Other = LHS;
2282     }
2283     if (CI && CI->getType()->isSized() && 
2284         (CI->getType()->getScalarSizeInBits() ==
2285          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2286         && isa<PointerType>(CI->getOperand(0)->getType())) {
2287       unsigned AS =
2288         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2289       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2290                                       PointerType::get(Type::Int8Ty, AS), I);
2291       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2292       return new PtrToIntInst(I2, CI->getType());
2293     }
2294   }
2295   
2296   // add (select X 0 (sub n A)) A  -->  select X A n
2297   {
2298     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2299     Value *A = RHS;
2300     if (!SI) {
2301       SI = dyn_cast<SelectInst>(RHS);
2302       A = LHS;
2303     }
2304     if (SI && SI->hasOneUse()) {
2305       Value *TV = SI->getTrueValue();
2306       Value *FV = SI->getFalseValue();
2307       Value *N;
2308
2309       // Can we fold the add into the argument of the select?
2310       // We check both true and false select arguments for a matching subtract.
2311       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2312         // Fold the add into the true select value.
2313         return SelectInst::Create(SI->getCondition(), N, A);
2314       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2315         // Fold the add into the false select value.
2316         return SelectInst::Create(SI->getCondition(), A, N);
2317     }
2318   }
2319
2320   // Check for (add (sext x), y), see if we can merge this into an
2321   // integer add followed by a sext.
2322   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2323     // (add (sext x), cst) --> (sext (add x, cst'))
2324     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2325       Constant *CI = 
2326         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2327       if (LHSConv->hasOneUse() &&
2328           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2329           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2330         // Insert the new, smaller add.
2331         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2332                                                         CI, "addconv");
2333         InsertNewInstBefore(NewAdd, I);
2334         return new SExtInst(NewAdd, I.getType());
2335       }
2336     }
2337     
2338     // (add (sext x), (sext y)) --> (sext (add int x, y))
2339     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2340       // Only do this if x/y have the same type, if at last one of them has a
2341       // single use (so we don't increase the number of sexts), and if the
2342       // integer add will not overflow.
2343       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2344           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2345           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2346                                    RHSConv->getOperand(0))) {
2347         // Insert the new integer add.
2348         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2349                                                         RHSConv->getOperand(0),
2350                                                         "addconv");
2351         InsertNewInstBefore(NewAdd, I);
2352         return new SExtInst(NewAdd, I.getType());
2353       }
2354     }
2355   }
2356
2357   return Changed ? &I : 0;
2358 }
2359
2360 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2361   bool Changed = SimplifyCommutative(I);
2362   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2363
2364   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2365     // X + 0 --> X
2366     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2367       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2368                               (I.getType())->getValueAPF()))
2369         return ReplaceInstUsesWith(I, LHS);
2370     }
2371
2372     if (isa<PHINode>(LHS))
2373       if (Instruction *NV = FoldOpIntoPhi(I))
2374         return NV;
2375   }
2376
2377   // -A + B  -->  B - A
2378   // -A + -B  -->  -(A + B)
2379   if (Value *LHSV = dyn_castFNegVal(LHS))
2380     return BinaryOperator::CreateFSub(RHS, LHSV);
2381
2382   // A + -B  -->  A - B
2383   if (!isa<Constant>(RHS))
2384     if (Value *V = dyn_castFNegVal(RHS))
2385       return BinaryOperator::CreateFSub(LHS, V);
2386
2387   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2388   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2389     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2390       return ReplaceInstUsesWith(I, LHS);
2391
2392   // Check for (add double (sitofp x), y), see if we can merge this into an
2393   // integer add followed by a promotion.
2394   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2395     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2396     // ... if the constant fits in the integer value.  This is useful for things
2397     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2398     // requires a constant pool load, and generally allows the add to be better
2399     // instcombined.
2400     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2401       Constant *CI = 
2402       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2403       if (LHSConv->hasOneUse() &&
2404           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2405           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2406         // Insert the new integer add.
2407         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2408                                                         CI, "addconv");
2409         InsertNewInstBefore(NewAdd, I);
2410         return new SIToFPInst(NewAdd, I.getType());
2411       }
2412     }
2413     
2414     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2415     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2416       // Only do this if x/y have the same type, if at last one of them has a
2417       // single use (so we don't increase the number of int->fp conversions),
2418       // and if the integer add will not overflow.
2419       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2420           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2421           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2422                                    RHSConv->getOperand(0))) {
2423         // Insert the new integer add.
2424         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2425                                                         RHSConv->getOperand(0),
2426                                                         "addconv");
2427         InsertNewInstBefore(NewAdd, I);
2428         return new SIToFPInst(NewAdd, I.getType());
2429       }
2430     }
2431   }
2432   
2433   return Changed ? &I : 0;
2434 }
2435
2436 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2437   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2438
2439   if (Op0 == Op1)                        // sub X, X  -> 0
2440     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2441
2442   // If this is a 'B = x-(-A)', change to B = x+A...
2443   if (Value *V = dyn_castNegVal(Op1))
2444     return BinaryOperator::CreateAdd(Op0, V);
2445
2446   if (isa<UndefValue>(Op0))
2447     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2448   if (isa<UndefValue>(Op1))
2449     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2450
2451   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2452     // Replace (-1 - A) with (~A)...
2453     if (C->isAllOnesValue())
2454       return BinaryOperator::CreateNot(Op1);
2455
2456     // C - ~X == X + (1+C)
2457     Value *X = 0;
2458     if (match(Op1, m_Not(m_Value(X))))
2459       return BinaryOperator::CreateAdd(X, AddOne(C));
2460
2461     // -(X >>u 31) -> (X >>s 31)
2462     // -(X >>s 31) -> (X >>u 31)
2463     if (C->isZero()) {
2464       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2465         if (SI->getOpcode() == Instruction::LShr) {
2466           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2467             // Check to see if we are shifting out everything but the sign bit.
2468             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2469                 SI->getType()->getPrimitiveSizeInBits()-1) {
2470               // Ok, the transformation is safe.  Insert AShr.
2471               return BinaryOperator::Create(Instruction::AShr, 
2472                                           SI->getOperand(0), CU, SI->getName());
2473             }
2474           }
2475         }
2476         else if (SI->getOpcode() == Instruction::AShr) {
2477           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2478             // Check to see if we are shifting out everything but the sign bit.
2479             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2480                 SI->getType()->getPrimitiveSizeInBits()-1) {
2481               // Ok, the transformation is safe.  Insert LShr. 
2482               return BinaryOperator::CreateLShr(
2483                                           SI->getOperand(0), CU, SI->getName());
2484             }
2485           }
2486         }
2487       }
2488     }
2489
2490     // Try to fold constant sub into select arguments.
2491     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2492       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2493         return R;
2494   }
2495
2496   if (I.getType() == Type::Int1Ty)
2497     return BinaryOperator::CreateXor(Op0, Op1);
2498
2499   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2500     if (Op1I->getOpcode() == Instruction::Add) {
2501       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2502         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2503       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2504         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2505       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2506         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2507           // C1-(X+C2) --> (C1-C2)-X
2508           return BinaryOperator::CreateSub(ConstantExpr::getSub(CI1, CI2),
2509                                            Op1I->getOperand(0));
2510       }
2511     }
2512
2513     if (Op1I->hasOneUse()) {
2514       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2515       // is not used by anyone else...
2516       //
2517       if (Op1I->getOpcode() == Instruction::Sub) {
2518         // Swap the two operands of the subexpr...
2519         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2520         Op1I->setOperand(0, IIOp1);
2521         Op1I->setOperand(1, IIOp0);
2522
2523         // Create the new top level add instruction...
2524         return BinaryOperator::CreateAdd(Op0, Op1);
2525       }
2526
2527       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2528       //
2529       if (Op1I->getOpcode() == Instruction::And &&
2530           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2531         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2532
2533         Value *NewNot =
2534           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2535         return BinaryOperator::CreateAnd(Op0, NewNot);
2536       }
2537
2538       // 0 - (X sdiv C)  -> (X sdiv -C)
2539       if (Op1I->getOpcode() == Instruction::SDiv)
2540         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2541           if (CSI->isZero())
2542             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2543               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2544                                                ConstantExpr::getNeg(DivRHS));
2545
2546       // X - X*C --> X * (1-C)
2547       ConstantInt *C2 = 0;
2548       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2549         Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2550                                              C2);
2551         return BinaryOperator::CreateMul(Op0, CP1);
2552       }
2553     }
2554   }
2555
2556   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2557     if (Op0I->getOpcode() == Instruction::Add) {
2558       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2559         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2560       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2561         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2562     } else if (Op0I->getOpcode() == Instruction::Sub) {
2563       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2564         return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2565     }
2566   }
2567
2568   ConstantInt *C1;
2569   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2570     if (X == Op1)  // X*C - X --> X * (C-1)
2571       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2572
2573     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2574     if (X == dyn_castFoldableMul(Op1, C2))
2575       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2576   }
2577   return 0;
2578 }
2579
2580 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2581   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2582
2583   // If this is a 'B = x-(-A)', change to B = x+A...
2584   if (Value *V = dyn_castFNegVal(Op1))
2585     return BinaryOperator::CreateFAdd(Op0, V);
2586
2587   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2588     if (Op1I->getOpcode() == Instruction::FAdd) {
2589       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2590         return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2591       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2592         return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2593     }
2594   }
2595
2596   return 0;
2597 }
2598
2599 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2600 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2601 /// TrueIfSigned if the result of the comparison is true when the input value is
2602 /// signed.
2603 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2604                            bool &TrueIfSigned) {
2605   switch (pred) {
2606   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2607     TrueIfSigned = true;
2608     return RHS->isZero();
2609   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2610     TrueIfSigned = true;
2611     return RHS->isAllOnesValue();
2612   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2613     TrueIfSigned = false;
2614     return RHS->isAllOnesValue();
2615   case ICmpInst::ICMP_UGT:
2616     // True if LHS u> RHS and RHS == high-bit-mask - 1
2617     TrueIfSigned = true;
2618     return RHS->getValue() ==
2619       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2620   case ICmpInst::ICMP_UGE: 
2621     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2622     TrueIfSigned = true;
2623     return RHS->getValue().isSignBit();
2624   default:
2625     return false;
2626   }
2627 }
2628
2629 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2630   bool Changed = SimplifyCommutative(I);
2631   Value *Op0 = I.getOperand(0);
2632
2633   // TODO: If Op1 is undef and Op0 is finite, return zero.
2634   if (!I.getType()->isFPOrFPVector() &&
2635       isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2636     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2637
2638   // Simplify mul instructions with a constant RHS...
2639   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2640     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2641
2642       // ((X << C1)*C2) == (X * (C2 << C1))
2643       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2644         if (SI->getOpcode() == Instruction::Shl)
2645           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2646             return BinaryOperator::CreateMul(SI->getOperand(0),
2647                                              ConstantExpr::getShl(CI, ShOp));
2648
2649       if (CI->isZero())
2650         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2651       if (CI->equalsInt(1))                  // X * 1  == X
2652         return ReplaceInstUsesWith(I, Op0);
2653       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2654         return BinaryOperator::CreateNeg(Op0, I.getName());
2655
2656       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2657       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2658         return BinaryOperator::CreateShl(Op0,
2659                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2660       }
2661     } else if (isa<VectorType>(Op1->getType())) {
2662       // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
2663
2664       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2665         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2666           return BinaryOperator::CreateNeg(Op0, I.getName());
2667
2668         // As above, vector X*splat(1.0) -> X in all defined cases.
2669         if (Constant *Splat = Op1V->getSplatValue()) {
2670           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2671             if (CI->equalsInt(1))
2672               return ReplaceInstUsesWith(I, Op0);
2673         }
2674       }
2675     }
2676     
2677     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2678       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2679           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2680         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2681         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2682                                                      Op1, "tmp");
2683         InsertNewInstBefore(Add, I);
2684         Value *C1C2 = ConstantExpr::getMul(Op1, 
2685                                            cast<Constant>(Op0I->getOperand(1)));
2686         return BinaryOperator::CreateAdd(Add, C1C2);
2687         
2688       }
2689
2690     // Try to fold constant mul into select arguments.
2691     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2692       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2693         return R;
2694
2695     if (isa<PHINode>(Op0))
2696       if (Instruction *NV = FoldOpIntoPhi(I))
2697         return NV;
2698   }
2699
2700   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2701     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2702       return BinaryOperator::CreateMul(Op0v, Op1v);
2703
2704   // (X / Y) *  Y = X - (X % Y)
2705   // (X / Y) * -Y = (X % Y) - X
2706   {
2707     Value *Op1 = I.getOperand(1);
2708     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2709     if (!BO ||
2710         (BO->getOpcode() != Instruction::UDiv && 
2711          BO->getOpcode() != Instruction::SDiv)) {
2712       Op1 = Op0;
2713       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2714     }
2715     Value *Neg = dyn_castNegVal(Op1);
2716     if (BO && BO->hasOneUse() &&
2717         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2718         (BO->getOpcode() == Instruction::UDiv ||
2719          BO->getOpcode() == Instruction::SDiv)) {
2720       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2721
2722       Instruction *Rem;
2723       if (BO->getOpcode() == Instruction::UDiv)
2724         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2725       else
2726         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2727
2728       InsertNewInstBefore(Rem, I);
2729       Rem->takeName(BO);
2730
2731       if (Op1BO == Op1)
2732         return BinaryOperator::CreateSub(Op0BO, Rem);
2733       else
2734         return BinaryOperator::CreateSub(Rem, Op0BO);
2735     }
2736   }
2737
2738   if (I.getType() == Type::Int1Ty)
2739     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2740
2741   // If one of the operands of the multiply is a cast from a boolean value, then
2742   // we know the bool is either zero or one, so this is a 'masking' multiply.
2743   // See if we can simplify things based on how the boolean was originally
2744   // formed.
2745   CastInst *BoolCast = 0;
2746   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2747     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2748       BoolCast = CI;
2749   if (!BoolCast)
2750     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2751       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2752         BoolCast = CI;
2753   if (BoolCast) {
2754     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2755       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2756       const Type *SCOpTy = SCIOp0->getType();
2757       bool TIS = false;
2758       
2759       // If the icmp is true iff the sign bit of X is set, then convert this
2760       // multiply into a shift/and combination.
2761       if (isa<ConstantInt>(SCIOp1) &&
2762           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2763           TIS) {
2764         // Shift the X value right to turn it into "all signbits".
2765         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2766                                           SCOpTy->getPrimitiveSizeInBits()-1);
2767         Value *V =
2768           InsertNewInstBefore(
2769             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2770                                             BoolCast->getOperand(0)->getName()+
2771                                             ".mask"), I);
2772
2773         // If the multiply type is not the same as the source type, sign extend
2774         // or truncate to the multiply type.
2775         if (I.getType() != V->getType()) {
2776           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2777           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2778           Instruction::CastOps opcode = 
2779             (SrcBits == DstBits ? Instruction::BitCast : 
2780              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2781           V = InsertCastBefore(opcode, V, I.getType(), I);
2782         }
2783
2784         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2785         return BinaryOperator::CreateAnd(V, OtherOp);
2786       }
2787     }
2788   }
2789
2790   return Changed ? &I : 0;
2791 }
2792
2793 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2794   bool Changed = SimplifyCommutative(I);
2795   Value *Op0 = I.getOperand(0);
2796
2797   // Simplify mul instructions with a constant RHS...
2798   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2799     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2800       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2801       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2802       if (Op1F->isExactlyValue(1.0))
2803         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2804     } else if (isa<VectorType>(Op1->getType())) {
2805       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2806         // As above, vector X*splat(1.0) -> X in all defined cases.
2807         if (Constant *Splat = Op1V->getSplatValue()) {
2808           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2809             if (F->isExactlyValue(1.0))
2810               return ReplaceInstUsesWith(I, Op0);
2811         }
2812       }
2813     }
2814
2815     // Try to fold constant mul into select arguments.
2816     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2817       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2818         return R;
2819
2820     if (isa<PHINode>(Op0))
2821       if (Instruction *NV = FoldOpIntoPhi(I))
2822         return NV;
2823   }
2824
2825   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2826     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2827       return BinaryOperator::CreateFMul(Op0v, Op1v);
2828
2829   return Changed ? &I : 0;
2830 }
2831
2832 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2833 /// instruction.
2834 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2835   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2836   
2837   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2838   int NonNullOperand = -1;
2839   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2840     if (ST->isNullValue())
2841       NonNullOperand = 2;
2842   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2843   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2844     if (ST->isNullValue())
2845       NonNullOperand = 1;
2846   
2847   if (NonNullOperand == -1)
2848     return false;
2849   
2850   Value *SelectCond = SI->getOperand(0);
2851   
2852   // Change the div/rem to use 'Y' instead of the select.
2853   I.setOperand(1, SI->getOperand(NonNullOperand));
2854   
2855   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2856   // problem.  However, the select, or the condition of the select may have
2857   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2858   // propagate the known value for the select into other uses of it, and
2859   // propagate a known value of the condition into its other users.
2860   
2861   // If the select and condition only have a single use, don't bother with this,
2862   // early exit.
2863   if (SI->use_empty() && SelectCond->hasOneUse())
2864     return true;
2865   
2866   // Scan the current block backward, looking for other uses of SI.
2867   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2868   
2869   while (BBI != BBFront) {
2870     --BBI;
2871     // If we found a call to a function, we can't assume it will return, so
2872     // information from below it cannot be propagated above it.
2873     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2874       break;
2875     
2876     // Replace uses of the select or its condition with the known values.
2877     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2878          I != E; ++I) {
2879       if (*I == SI) {
2880         *I = SI->getOperand(NonNullOperand);
2881         AddToWorkList(BBI);
2882       } else if (*I == SelectCond) {
2883         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2884                                    ConstantInt::getFalse();
2885         AddToWorkList(BBI);
2886       }
2887     }
2888     
2889     // If we past the instruction, quit looking for it.
2890     if (&*BBI == SI)
2891       SI = 0;
2892     if (&*BBI == SelectCond)
2893       SelectCond = 0;
2894     
2895     // If we ran out of things to eliminate, break out of the loop.
2896     if (SelectCond == 0 && SI == 0)
2897       break;
2898     
2899   }
2900   return true;
2901 }
2902
2903
2904 /// This function implements the transforms on div instructions that work
2905 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2906 /// used by the visitors to those instructions.
2907 /// @brief Transforms common to all three div instructions
2908 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2909   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2910
2911   // undef / X -> 0        for integer.
2912   // undef / X -> undef    for FP (the undef could be a snan).
2913   if (isa<UndefValue>(Op0)) {
2914     if (Op0->getType()->isFPOrFPVector())
2915       return ReplaceInstUsesWith(I, Op0);
2916     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2917   }
2918
2919   // X / undef -> undef
2920   if (isa<UndefValue>(Op1))
2921     return ReplaceInstUsesWith(I, Op1);
2922
2923   return 0;
2924 }
2925
2926 /// This function implements the transforms common to both integer division
2927 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2928 /// division instructions.
2929 /// @brief Common integer divide transforms
2930 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2931   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2932
2933   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2934   if (Op0 == Op1) {
2935     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2936       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2937       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2938       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2939     }
2940
2941     Constant *CI = ConstantInt::get(I.getType(), 1);
2942     return ReplaceInstUsesWith(I, CI);
2943   }
2944   
2945   if (Instruction *Common = commonDivTransforms(I))
2946     return Common;
2947   
2948   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2949   // This does not apply for fdiv.
2950   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2951     return &I;
2952
2953   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2954     // div X, 1 == X
2955     if (RHS->equalsInt(1))
2956       return ReplaceInstUsesWith(I, Op0);
2957
2958     // (X / C1) / C2  -> X / (C1*C2)
2959     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2960       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2961         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2962           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2963             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2964           else 
2965             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2966                                           ConstantExpr::getMul(RHS, LHSRHS));
2967         }
2968
2969     if (!RHS->isZero()) { // avoid X udiv 0
2970       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2971         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2972           return R;
2973       if (isa<PHINode>(Op0))
2974         if (Instruction *NV = FoldOpIntoPhi(I))
2975           return NV;
2976     }
2977   }
2978
2979   // 0 / X == 0, we don't need to preserve faults!
2980   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2981     if (LHS->equalsInt(0))
2982       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2983
2984   // It can't be division by zero, hence it must be division by one.
2985   if (I.getType() == Type::Int1Ty)
2986     return ReplaceInstUsesWith(I, Op0);
2987
2988   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2989     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2990       // div X, 1 == X
2991       if (X->isOne())
2992         return ReplaceInstUsesWith(I, Op0);
2993   }
2994
2995   return 0;
2996 }
2997
2998 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2999   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3000
3001   // Handle the integer div common cases
3002   if (Instruction *Common = commonIDivTransforms(I))
3003     return Common;
3004
3005   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3006     // X udiv C^2 -> X >> C
3007     // Check to see if this is an unsigned division with an exact power of 2,
3008     // if so, convert to a right shift.
3009     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3010       return BinaryOperator::CreateLShr(Op0, 
3011                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3012
3013     // X udiv C, where C >= signbit
3014     if (C->getValue().isNegative()) {
3015       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
3016                                       I);
3017       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3018                                 ConstantInt::get(I.getType(), 1));
3019     }
3020   }
3021
3022   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3023   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3024     if (RHSI->getOpcode() == Instruction::Shl &&
3025         isa<ConstantInt>(RHSI->getOperand(0))) {
3026       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3027       if (C1.isPowerOf2()) {
3028         Value *N = RHSI->getOperand(1);
3029         const Type *NTy = N->getType();
3030         if (uint32_t C2 = C1.logBase2()) {
3031           Constant *C2V = ConstantInt::get(NTy, C2);
3032           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3033         }
3034         return BinaryOperator::CreateLShr(Op0, N);
3035       }
3036     }
3037   }
3038   
3039   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3040   // where C1&C2 are powers of two.
3041   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3042     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3043       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3044         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3045         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3046           // Compute the shift amounts
3047           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3048           // Construct the "on true" case of the select
3049           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3050           Instruction *TSI = BinaryOperator::CreateLShr(
3051                                                  Op0, TC, SI->getName()+".t");
3052           TSI = InsertNewInstBefore(TSI, I);
3053   
3054           // Construct the "on false" case of the select
3055           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3056           Instruction *FSI = BinaryOperator::CreateLShr(
3057                                                  Op0, FC, SI->getName()+".f");
3058           FSI = InsertNewInstBefore(FSI, I);
3059
3060           // construct the select instruction and return it.
3061           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3062         }
3063       }
3064   return 0;
3065 }
3066
3067 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3068   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3069
3070   // Handle the integer div common cases
3071   if (Instruction *Common = commonIDivTransforms(I))
3072     return Common;
3073
3074   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3075     // sdiv X, -1 == -X
3076     if (RHS->isAllOnesValue())
3077       return BinaryOperator::CreateNeg(Op0);
3078   }
3079
3080   // If the sign bits of both operands are zero (i.e. we can prove they are
3081   // unsigned inputs), turn this into a udiv.
3082   if (I.getType()->isInteger()) {
3083     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3084     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3085       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3086       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3087     }
3088   }      
3089   
3090   return 0;
3091 }
3092
3093 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3094   return commonDivTransforms(I);
3095 }
3096
3097 /// This function implements the transforms on rem instructions that work
3098 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3099 /// is used by the visitors to those instructions.
3100 /// @brief Transforms common to all three rem instructions
3101 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3102   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3103
3104   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3105     if (I.getType()->isFPOrFPVector())
3106       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3107     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3108   }
3109   if (isa<UndefValue>(Op1))
3110     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3111
3112   // Handle cases involving: rem X, (select Cond, Y, Z)
3113   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3114     return &I;
3115
3116   return 0;
3117 }
3118
3119 /// This function implements the transforms common to both integer remainder
3120 /// instructions (urem and srem). It is called by the visitors to those integer
3121 /// remainder instructions.
3122 /// @brief Common integer remainder transforms
3123 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3124   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3125
3126   if (Instruction *common = commonRemTransforms(I))
3127     return common;
3128
3129   // 0 % X == 0 for integer, we don't need to preserve faults!
3130   if (Constant *LHS = dyn_cast<Constant>(Op0))
3131     if (LHS->isNullValue())
3132       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3133
3134   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3135     // X % 0 == undef, we don't need to preserve faults!
3136     if (RHS->equalsInt(0))
3137       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3138     
3139     if (RHS->equalsInt(1))  // X % 1 == 0
3140       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3141
3142     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3143       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3144         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3145           return R;
3146       } else if (isa<PHINode>(Op0I)) {
3147         if (Instruction *NV = FoldOpIntoPhi(I))
3148           return NV;
3149       }
3150
3151       // See if we can fold away this rem instruction.
3152       if (SimplifyDemandedInstructionBits(I))
3153         return &I;
3154     }
3155   }
3156
3157   return 0;
3158 }
3159
3160 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3161   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3162
3163   if (Instruction *common = commonIRemTransforms(I))
3164     return common;
3165   
3166   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3167     // X urem C^2 -> X and C
3168     // Check to see if this is an unsigned remainder with an exact power of 2,
3169     // if so, convert to a bitwise and.
3170     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3171       if (C->getValue().isPowerOf2())
3172         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3173   }
3174
3175   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3176     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3177     if (RHSI->getOpcode() == Instruction::Shl &&
3178         isa<ConstantInt>(RHSI->getOperand(0))) {
3179       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3180         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3181         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3182                                                                    "tmp"), I);
3183         return BinaryOperator::CreateAnd(Op0, Add);
3184       }
3185     }
3186   }
3187
3188   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3189   // where C1&C2 are powers of two.
3190   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3191     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3192       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3193         // STO == 0 and SFO == 0 handled above.
3194         if ((STO->getValue().isPowerOf2()) && 
3195             (SFO->getValue().isPowerOf2())) {
3196           Value *TrueAnd = InsertNewInstBefore(
3197             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3198           Value *FalseAnd = InsertNewInstBefore(
3199             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3200           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3201         }
3202       }
3203   }
3204   
3205   return 0;
3206 }
3207
3208 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3209   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3210
3211   // Handle the integer rem common cases
3212   if (Instruction *common = commonIRemTransforms(I))
3213     return common;
3214   
3215   if (Value *RHSNeg = dyn_castNegVal(Op1))
3216     if (!isa<Constant>(RHSNeg) ||
3217         (isa<ConstantInt>(RHSNeg) &&
3218          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3219       // X % -Y -> X % Y
3220       AddUsesToWorkList(I);
3221       I.setOperand(1, RHSNeg);
3222       return &I;
3223     }
3224
3225   // If the sign bits of both operands are zero (i.e. we can prove they are
3226   // unsigned inputs), turn this into a urem.
3227   if (I.getType()->isInteger()) {
3228     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3229     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3230       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3231       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3232     }
3233   }
3234
3235   // If it's a constant vector, flip any negative values positive.
3236   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3237     unsigned VWidth = RHSV->getNumOperands();
3238
3239     bool hasNegative = false;
3240     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3241       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3242         if (RHS->getValue().isNegative())
3243           hasNegative = true;
3244
3245     if (hasNegative) {
3246       std::vector<Constant *> Elts(VWidth);
3247       for (unsigned i = 0; i != VWidth; ++i) {
3248         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3249           if (RHS->getValue().isNegative())
3250             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3251           else
3252             Elts[i] = RHS;
3253         }
3254       }
3255
3256       Constant *NewRHSV = ConstantVector::get(Elts);
3257       if (NewRHSV != RHSV) {
3258         AddUsesToWorkList(I);
3259         I.setOperand(1, NewRHSV);
3260         return &I;
3261       }
3262     }
3263   }
3264
3265   return 0;
3266 }
3267
3268 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3269   return commonRemTransforms(I);
3270 }
3271
3272 // isOneBitSet - Return true if there is exactly one bit set in the specified
3273 // constant.
3274 static bool isOneBitSet(const ConstantInt *CI) {
3275   return CI->getValue().isPowerOf2();
3276 }
3277
3278 // isHighOnes - Return true if the constant is of the form 1+0+.
3279 // This is the same as lowones(~X).
3280 static bool isHighOnes(const ConstantInt *CI) {
3281   return (~CI->getValue() + 1).isPowerOf2();
3282 }
3283
3284 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3285 /// are carefully arranged to allow folding of expressions such as:
3286 ///
3287 ///      (A < B) | (A > B) --> (A != B)
3288 ///
3289 /// Note that this is only valid if the first and second predicates have the
3290 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3291 ///
3292 /// Three bits are used to represent the condition, as follows:
3293 ///   0  A > B
3294 ///   1  A == B
3295 ///   2  A < B
3296 ///
3297 /// <=>  Value  Definition
3298 /// 000     0   Always false
3299 /// 001     1   A >  B
3300 /// 010     2   A == B
3301 /// 011     3   A >= B
3302 /// 100     4   A <  B
3303 /// 101     5   A != B
3304 /// 110     6   A <= B
3305 /// 111     7   Always true
3306 ///  
3307 static unsigned getICmpCode(const ICmpInst *ICI) {
3308   switch (ICI->getPredicate()) {
3309     // False -> 0
3310   case ICmpInst::ICMP_UGT: return 1;  // 001
3311   case ICmpInst::ICMP_SGT: return 1;  // 001
3312   case ICmpInst::ICMP_EQ:  return 2;  // 010
3313   case ICmpInst::ICMP_UGE: return 3;  // 011
3314   case ICmpInst::ICMP_SGE: return 3;  // 011
3315   case ICmpInst::ICMP_ULT: return 4;  // 100
3316   case ICmpInst::ICMP_SLT: return 4;  // 100
3317   case ICmpInst::ICMP_NE:  return 5;  // 101
3318   case ICmpInst::ICMP_ULE: return 6;  // 110
3319   case ICmpInst::ICMP_SLE: return 6;  // 110
3320     // True -> 7
3321   default:
3322     assert(0 && "Invalid ICmp predicate!");
3323     return 0;
3324   }
3325 }
3326
3327 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3328 /// predicate into a three bit mask. It also returns whether it is an ordered
3329 /// predicate by reference.
3330 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3331   isOrdered = false;
3332   switch (CC) {
3333   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3334   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3335   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3336   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3337   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3338   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3339   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3340   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3341   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3342   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3343   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3344   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3345   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3346   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3347     // True -> 7
3348   default:
3349     // Not expecting FCMP_FALSE and FCMP_TRUE;
3350     assert(0 && "Unexpected FCmp predicate!");
3351     return 0;
3352   }
3353 }
3354
3355 /// getICmpValue - This is the complement of getICmpCode, which turns an
3356 /// opcode and two operands into either a constant true or false, or a brand 
3357 /// new ICmp instruction. The sign is passed in to determine which kind
3358 /// of predicate to use in the new icmp instruction.
3359 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3360   switch (code) {
3361   default: assert(0 && "Illegal ICmp code!");
3362   case  0: return ConstantInt::getFalse();
3363   case  1: 
3364     if (sign)
3365       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3366     else
3367       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3368   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3369   case  3: 
3370     if (sign)
3371       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3372     else
3373       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3374   case  4: 
3375     if (sign)
3376       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3377     else
3378       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3379   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3380   case  6: 
3381     if (sign)
3382       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3383     else
3384       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3385   case  7: return ConstantInt::getTrue();
3386   }
3387 }
3388
3389 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3390 /// opcode and two operands into either a FCmp instruction. isordered is passed
3391 /// in to determine which kind of predicate to use in the new fcmp instruction.
3392 static Value *getFCmpValue(bool isordered, unsigned code,
3393                            Value *LHS, Value *RHS) {
3394   switch (code) {
3395   default: assert(0 && "Illegal FCmp code!");
3396   case  0:
3397     if (isordered)
3398       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3399     else
3400       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3401   case  1: 
3402     if (isordered)
3403       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3404     else
3405       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3406   case  2: 
3407     if (isordered)
3408       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3409     else
3410       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3411   case  3: 
3412     if (isordered)
3413       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3414     else
3415       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3416   case  4: 
3417     if (isordered)
3418       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3419     else
3420       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3421   case  5: 
3422     if (isordered)
3423       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3424     else
3425       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3426   case  6: 
3427     if (isordered)
3428       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3429     else
3430       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3431   case  7: return ConstantInt::getTrue();
3432   }
3433 }
3434
3435 /// PredicatesFoldable - Return true if both predicates match sign or if at
3436 /// least one of them is an equality comparison (which is signless).
3437 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3438   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3439          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3440          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3441 }
3442
3443 namespace { 
3444 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3445 struct FoldICmpLogical {
3446   InstCombiner &IC;
3447   Value *LHS, *RHS;
3448   ICmpInst::Predicate pred;
3449   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3450     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3451       pred(ICI->getPredicate()) {}
3452   bool shouldApply(Value *V) const {
3453     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3454       if (PredicatesFoldable(pred, ICI->getPredicate()))
3455         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3456                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3457     return false;
3458   }
3459   Instruction *apply(Instruction &Log) const {
3460     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3461     if (ICI->getOperand(0) != LHS) {
3462       assert(ICI->getOperand(1) == LHS);
3463       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3464     }
3465
3466     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3467     unsigned LHSCode = getICmpCode(ICI);
3468     unsigned RHSCode = getICmpCode(RHSICI);
3469     unsigned Code;
3470     switch (Log.getOpcode()) {
3471     case Instruction::And: Code = LHSCode & RHSCode; break;
3472     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3473     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3474     default: assert(0 && "Illegal logical opcode!"); return 0;
3475     }
3476
3477     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3478                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3479       
3480     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3481     if (Instruction *I = dyn_cast<Instruction>(RV))
3482       return I;
3483     // Otherwise, it's a constant boolean value...
3484     return IC.ReplaceInstUsesWith(Log, RV);
3485   }
3486 };
3487 } // end anonymous namespace
3488
3489 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3490 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3491 // guaranteed to be a binary operator.
3492 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3493                                     ConstantInt *OpRHS,
3494                                     ConstantInt *AndRHS,
3495                                     BinaryOperator &TheAnd) {
3496   Value *X = Op->getOperand(0);
3497   Constant *Together = 0;
3498   if (!Op->isShift())
3499     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3500
3501   switch (Op->getOpcode()) {
3502   case Instruction::Xor:
3503     if (Op->hasOneUse()) {
3504       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3505       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3506       InsertNewInstBefore(And, TheAnd);
3507       And->takeName(Op);
3508       return BinaryOperator::CreateXor(And, Together);
3509     }
3510     break;
3511   case Instruction::Or:
3512     if (Together == AndRHS) // (X | C) & C --> C
3513       return ReplaceInstUsesWith(TheAnd, AndRHS);
3514
3515     if (Op->hasOneUse() && Together != OpRHS) {
3516       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3517       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3518       InsertNewInstBefore(Or, TheAnd);
3519       Or->takeName(Op);
3520       return BinaryOperator::CreateAnd(Or, AndRHS);
3521     }
3522     break;
3523   case Instruction::Add:
3524     if (Op->hasOneUse()) {
3525       // Adding a one to a single bit bit-field should be turned into an XOR
3526       // of the bit.  First thing to check is to see if this AND is with a
3527       // single bit constant.
3528       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3529
3530       // If there is only one bit set...
3531       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3532         // Ok, at this point, we know that we are masking the result of the
3533         // ADD down to exactly one bit.  If the constant we are adding has
3534         // no bits set below this bit, then we can eliminate the ADD.
3535         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3536
3537         // Check to see if any bits below the one bit set in AndRHSV are set.
3538         if ((AddRHS & (AndRHSV-1)) == 0) {
3539           // If not, the only thing that can effect the output of the AND is
3540           // the bit specified by AndRHSV.  If that bit is set, the effect of
3541           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3542           // no effect.
3543           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3544             TheAnd.setOperand(0, X);
3545             return &TheAnd;
3546           } else {
3547             // Pull the XOR out of the AND.
3548             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3549             InsertNewInstBefore(NewAnd, TheAnd);
3550             NewAnd->takeName(Op);
3551             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3552           }
3553         }
3554       }
3555     }
3556     break;
3557
3558   case Instruction::Shl: {
3559     // We know that the AND will not produce any of the bits shifted in, so if
3560     // the anded constant includes them, clear them now!
3561     //
3562     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3563     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3564     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3565     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3566
3567     if (CI->getValue() == ShlMask) { 
3568     // Masking out bits that the shift already masks
3569       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3570     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3571       TheAnd.setOperand(1, CI);
3572       return &TheAnd;
3573     }
3574     break;
3575   }
3576   case Instruction::LShr:
3577   {
3578     // We know that the AND will not produce any of the bits shifted in, so if
3579     // the anded constant includes them, clear them now!  This only applies to
3580     // unsigned shifts, because a signed shr may bring in set bits!
3581     //
3582     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3583     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3584     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3585     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3586
3587     if (CI->getValue() == ShrMask) {   
3588     // Masking out bits that the shift already masks.
3589       return ReplaceInstUsesWith(TheAnd, Op);
3590     } else if (CI != AndRHS) {
3591       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3592       return &TheAnd;
3593     }
3594     break;
3595   }
3596   case Instruction::AShr:
3597     // Signed shr.
3598     // See if this is shifting in some sign extension, then masking it out
3599     // with an and.
3600     if (Op->hasOneUse()) {
3601       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3602       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3603       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3604       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3605       if (C == AndRHS) {          // Masking out bits shifted in.
3606         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3607         // Make the argument unsigned.
3608         Value *ShVal = Op->getOperand(0);
3609         ShVal = InsertNewInstBefore(
3610             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3611                                    Op->getName()), TheAnd);
3612         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3613       }
3614     }
3615     break;
3616   }
3617   return 0;
3618 }
3619
3620
3621 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3622 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3623 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3624 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3625 /// insert new instructions.
3626 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3627                                            bool isSigned, bool Inside, 
3628                                            Instruction &IB) {
3629   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3630             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3631          "Lo is not <= Hi in range emission code!");
3632     
3633   if (Inside) {
3634     if (Lo == Hi)  // Trivially false.
3635       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3636
3637     // V >= Min && V < Hi --> V < Hi
3638     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3639       ICmpInst::Predicate pred = (isSigned ? 
3640         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3641       return new ICmpInst(pred, V, Hi);
3642     }
3643
3644     // Emit V-Lo <u Hi-Lo
3645     Constant *NegLo = ConstantExpr::getNeg(Lo);
3646     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3647     InsertNewInstBefore(Add, IB);
3648     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3649     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3650   }
3651
3652   if (Lo == Hi)  // Trivially true.
3653     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3654
3655   // V < Min || V >= Hi -> V > Hi-1
3656   Hi = SubOne(cast<ConstantInt>(Hi));
3657   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3658     ICmpInst::Predicate pred = (isSigned ? 
3659         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3660     return new ICmpInst(pred, V, Hi);
3661   }
3662
3663   // Emit V-Lo >u Hi-1-Lo
3664   // Note that Hi has already had one subtracted from it, above.
3665   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3666   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3667   InsertNewInstBefore(Add, IB);
3668   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3669   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3670 }
3671
3672 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3673 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3674 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3675 // not, since all 1s are not contiguous.
3676 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3677   const APInt& V = Val->getValue();
3678   uint32_t BitWidth = Val->getType()->getBitWidth();
3679   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3680
3681   // look for the first zero bit after the run of ones
3682   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3683   // look for the first non-zero bit
3684   ME = V.getActiveBits(); 
3685   return true;
3686 }
3687
3688 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3689 /// where isSub determines whether the operator is a sub.  If we can fold one of
3690 /// the following xforms:
3691 /// 
3692 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3693 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3694 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3695 ///
3696 /// return (A +/- B).
3697 ///
3698 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3699                                         ConstantInt *Mask, bool isSub,
3700                                         Instruction &I) {
3701   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3702   if (!LHSI || LHSI->getNumOperands() != 2 ||
3703       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3704
3705   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3706
3707   switch (LHSI->getOpcode()) {
3708   default: return 0;
3709   case Instruction::And:
3710     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3711       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3712       if ((Mask->getValue().countLeadingZeros() + 
3713            Mask->getValue().countPopulation()) == 
3714           Mask->getValue().getBitWidth())
3715         break;
3716
3717       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3718       // part, we don't need any explicit masks to take them out of A.  If that
3719       // is all N is, ignore it.
3720       uint32_t MB = 0, ME = 0;
3721       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3722         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3723         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3724         if (MaskedValueIsZero(RHS, Mask))
3725           break;
3726       }
3727     }
3728     return 0;
3729   case Instruction::Or:
3730   case Instruction::Xor:
3731     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3732     if ((Mask->getValue().countLeadingZeros() + 
3733          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3734         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3735       break;
3736     return 0;
3737   }
3738   
3739   Instruction *New;
3740   if (isSub)
3741     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3742   else
3743     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3744   return InsertNewInstBefore(New, I);
3745 }
3746
3747 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3748 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3749                                           ICmpInst *LHS, ICmpInst *RHS) {
3750   Value *Val, *Val2;
3751   ConstantInt *LHSCst, *RHSCst;
3752   ICmpInst::Predicate LHSCC, RHSCC;
3753   
3754   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3755   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3756       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3757     return 0;
3758   
3759   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3760   // where C is a power of 2
3761   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3762       LHSCst->getValue().isPowerOf2()) {
3763     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3764     InsertNewInstBefore(NewOr, I);
3765     return new ICmpInst(LHSCC, NewOr, LHSCst);
3766   }
3767   
3768   // From here on, we only handle:
3769   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3770   if (Val != Val2) return 0;
3771   
3772   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3773   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3774       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3775       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3776       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3777     return 0;
3778   
3779   // We can't fold (ugt x, C) & (sgt x, C2).
3780   if (!PredicatesFoldable(LHSCC, RHSCC))
3781     return 0;
3782     
3783   // Ensure that the larger constant is on the RHS.
3784   bool ShouldSwap;
3785   if (ICmpInst::isSignedPredicate(LHSCC) ||
3786       (ICmpInst::isEquality(LHSCC) && 
3787        ICmpInst::isSignedPredicate(RHSCC)))
3788     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3789   else
3790     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3791     
3792   if (ShouldSwap) {
3793     std::swap(LHS, RHS);
3794     std::swap(LHSCst, RHSCst);
3795     std::swap(LHSCC, RHSCC);
3796   }
3797
3798   // At this point, we know we have have two icmp instructions
3799   // comparing a value against two constants and and'ing the result
3800   // together.  Because of the above check, we know that we only have
3801   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3802   // (from the FoldICmpLogical check above), that the two constants 
3803   // are not equal and that the larger constant is on the RHS
3804   assert(LHSCst != RHSCst && "Compares not folded above?");
3805
3806   switch (LHSCC) {
3807   default: assert(0 && "Unknown integer condition code!");
3808   case ICmpInst::ICMP_EQ:
3809     switch (RHSCC) {
3810     default: assert(0 && "Unknown integer condition code!");
3811     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3812     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3813     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3814       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3815     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3816     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3817     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3818       return ReplaceInstUsesWith(I, LHS);
3819     }
3820   case ICmpInst::ICMP_NE:
3821     switch (RHSCC) {
3822     default: assert(0 && "Unknown integer condition code!");
3823     case ICmpInst::ICMP_ULT:
3824       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3825         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3826       break;                        // (X != 13 & X u< 15) -> no change
3827     case ICmpInst::ICMP_SLT:
3828       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3829         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3830       break;                        // (X != 13 & X s< 15) -> no change
3831     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3832     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3833     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3834       return ReplaceInstUsesWith(I, RHS);
3835     case ICmpInst::ICMP_NE:
3836       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3837         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3838         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3839                                                      Val->getName()+".off");
3840         InsertNewInstBefore(Add, I);
3841         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3842                             ConstantInt::get(Add->getType(), 1));
3843       }
3844       break;                        // (X != 13 & X != 15) -> no change
3845     }
3846     break;
3847   case ICmpInst::ICMP_ULT:
3848     switch (RHSCC) {
3849     default: assert(0 && "Unknown integer condition code!");
3850     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3851     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3852       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3853     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3854       break;
3855     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3856     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3857       return ReplaceInstUsesWith(I, LHS);
3858     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3859       break;
3860     }
3861     break;
3862   case ICmpInst::ICMP_SLT:
3863     switch (RHSCC) {
3864     default: assert(0 && "Unknown integer condition code!");
3865     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3866     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3867       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3868     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3869       break;
3870     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3871     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3872       return ReplaceInstUsesWith(I, LHS);
3873     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3874       break;
3875     }
3876     break;
3877   case ICmpInst::ICMP_UGT:
3878     switch (RHSCC) {
3879     default: assert(0 && "Unknown integer condition code!");
3880     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3881     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3882       return ReplaceInstUsesWith(I, RHS);
3883     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3884       break;
3885     case ICmpInst::ICMP_NE:
3886       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3887         return new ICmpInst(LHSCC, Val, RHSCst);
3888       break;                        // (X u> 13 & X != 15) -> no change
3889     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3890       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3891     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3892       break;
3893     }
3894     break;
3895   case ICmpInst::ICMP_SGT:
3896     switch (RHSCC) {
3897     default: assert(0 && "Unknown integer condition code!");
3898     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3899     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3900       return ReplaceInstUsesWith(I, RHS);
3901     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3902       break;
3903     case ICmpInst::ICMP_NE:
3904       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3905         return new ICmpInst(LHSCC, Val, RHSCst);
3906       break;                        // (X s> 13 & X != 15) -> no change
3907     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3908       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3909     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3910       break;
3911     }
3912     break;
3913   }
3914  
3915   return 0;
3916 }
3917
3918
3919 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3920   bool Changed = SimplifyCommutative(I);
3921   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3922
3923   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3924     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3925
3926   // and X, X = X
3927   if (Op0 == Op1)
3928     return ReplaceInstUsesWith(I, Op1);
3929
3930   // See if we can simplify any instructions used by the instruction whose sole 
3931   // purpose is to compute bits we don't care about.
3932   if (SimplifyDemandedInstructionBits(I))
3933     return &I;
3934   if (isa<VectorType>(I.getType())) {
3935     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3936       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3937         return ReplaceInstUsesWith(I, I.getOperand(0));
3938     } else if (isa<ConstantAggregateZero>(Op1)) {
3939       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3940     }
3941   }
3942
3943   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3944     const APInt& AndRHSMask = AndRHS->getValue();
3945     APInt NotAndRHS(~AndRHSMask);
3946
3947     // Optimize a variety of ((val OP C1) & C2) combinations...
3948     if (isa<BinaryOperator>(Op0)) {
3949       Instruction *Op0I = cast<Instruction>(Op0);
3950       Value *Op0LHS = Op0I->getOperand(0);
3951       Value *Op0RHS = Op0I->getOperand(1);
3952       switch (Op0I->getOpcode()) {
3953       case Instruction::Xor:
3954       case Instruction::Or:
3955         // If the mask is only needed on one incoming arm, push it up.
3956         if (Op0I->hasOneUse()) {
3957           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3958             // Not masking anything out for the LHS, move to RHS.
3959             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3960                                                    Op0RHS->getName()+".masked");
3961             InsertNewInstBefore(NewRHS, I);
3962             return BinaryOperator::Create(
3963                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3964           }
3965           if (!isa<Constant>(Op0RHS) &&
3966               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3967             // Not masking anything out for the RHS, move to LHS.
3968             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3969                                                    Op0LHS->getName()+".masked");
3970             InsertNewInstBefore(NewLHS, I);
3971             return BinaryOperator::Create(
3972                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3973           }
3974         }
3975
3976         break;
3977       case Instruction::Add:
3978         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3979         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3980         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3981         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3982           return BinaryOperator::CreateAnd(V, AndRHS);
3983         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3984           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3985         break;
3986
3987       case Instruction::Sub:
3988         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3989         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3990         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3991         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3992           return BinaryOperator::CreateAnd(V, AndRHS);
3993
3994         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3995         // has 1's for all bits that the subtraction with A might affect.
3996         if (Op0I->hasOneUse()) {
3997           uint32_t BitWidth = AndRHSMask.getBitWidth();
3998           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3999           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4000
4001           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4002           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4003               MaskedValueIsZero(Op0LHS, Mask)) {
4004             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4005             InsertNewInstBefore(NewNeg, I);
4006             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4007           }
4008         }
4009         break;
4010
4011       case Instruction::Shl:
4012       case Instruction::LShr:
4013         // (1 << x) & 1 --> zext(x == 0)
4014         // (1 >> x) & 1 --> zext(x == 0)
4015         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4016           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
4017                                            Constant::getNullValue(I.getType()));
4018           InsertNewInstBefore(NewICmp, I);
4019           return new ZExtInst(NewICmp, I.getType());
4020         }
4021         break;
4022       }
4023
4024       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4025         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4026           return Res;
4027     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4028       // If this is an integer truncation or change from signed-to-unsigned, and
4029       // if the source is an and/or with immediate, transform it.  This
4030       // frequently occurs for bitfield accesses.
4031       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4032         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4033             CastOp->getNumOperands() == 2)
4034           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4035             if (CastOp->getOpcode() == Instruction::And) {
4036               // Change: and (cast (and X, C1) to T), C2
4037               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4038               // This will fold the two constants together, which may allow 
4039               // other simplifications.
4040               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4041                 CastOp->getOperand(0), I.getType(), 
4042                 CastOp->getName()+".shrunk");
4043               NewCast = InsertNewInstBefore(NewCast, I);
4044               // trunc_or_bitcast(C1)&C2
4045               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4046               C3 = ConstantExpr::getAnd(C3, AndRHS);
4047               return BinaryOperator::CreateAnd(NewCast, C3);
4048             } else if (CastOp->getOpcode() == Instruction::Or) {
4049               // Change: and (cast (or X, C1) to T), C2
4050               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4051               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4052               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
4053                 return ReplaceInstUsesWith(I, AndRHS);
4054             }
4055           }
4056       }
4057     }
4058
4059     // Try to fold constant and into select arguments.
4060     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4061       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4062         return R;
4063     if (isa<PHINode>(Op0))
4064       if (Instruction *NV = FoldOpIntoPhi(I))
4065         return NV;
4066   }
4067
4068   Value *Op0NotVal = dyn_castNotVal(Op0);
4069   Value *Op1NotVal = dyn_castNotVal(Op1);
4070
4071   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4072     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4073
4074   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4075   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4076     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4077                                                I.getName()+".demorgan");
4078     InsertNewInstBefore(Or, I);
4079     return BinaryOperator::CreateNot(Or);
4080   }
4081   
4082   {
4083     Value *A = 0, *B = 0, *C = 0, *D = 0;
4084     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4085       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4086         return ReplaceInstUsesWith(I, Op1);
4087     
4088       // (A|B) & ~(A&B) -> A^B
4089       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4090         if ((A == C && B == D) || (A == D && B == C))
4091           return BinaryOperator::CreateXor(A, B);
4092       }
4093     }
4094     
4095     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4096       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4097         return ReplaceInstUsesWith(I, Op0);
4098
4099       // ~(A&B) & (A|B) -> A^B
4100       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4101         if ((A == C && B == D) || (A == D && B == C))
4102           return BinaryOperator::CreateXor(A, B);
4103       }
4104     }
4105     
4106     if (Op0->hasOneUse() &&
4107         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4108       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4109         I.swapOperands();     // Simplify below
4110         std::swap(Op0, Op1);
4111       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4112         cast<BinaryOperator>(Op0)->swapOperands();
4113         I.swapOperands();     // Simplify below
4114         std::swap(Op0, Op1);
4115       }
4116     }
4117
4118     if (Op1->hasOneUse() &&
4119         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4120       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4121         cast<BinaryOperator>(Op1)->swapOperands();
4122         std::swap(A, B);
4123       }
4124       if (A == Op0) {                                // A&(A^B) -> A & ~B
4125         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4126         InsertNewInstBefore(NotB, I);
4127         return BinaryOperator::CreateAnd(A, NotB);
4128       }
4129     }
4130
4131     // (A&((~A)|B)) -> A&B
4132     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4133         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4134       return BinaryOperator::CreateAnd(A, Op1);
4135     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4136         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4137       return BinaryOperator::CreateAnd(A, Op0);
4138   }
4139   
4140   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4141     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4142     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4143       return R;
4144
4145     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4146       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4147         return Res;
4148   }
4149
4150   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4151   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4152     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4153       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4154         const Type *SrcTy = Op0C->getOperand(0)->getType();
4155         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4156             // Only do this if the casts both really cause code to be generated.
4157             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4158                               I.getType(), TD) &&
4159             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4160                               I.getType(), TD)) {
4161           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4162                                                          Op1C->getOperand(0),
4163                                                          I.getName());
4164           InsertNewInstBefore(NewOp, I);
4165           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4166         }
4167       }
4168     
4169   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4170   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4171     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4172       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4173           SI0->getOperand(1) == SI1->getOperand(1) &&
4174           (SI0->hasOneUse() || SI1->hasOneUse())) {
4175         Instruction *NewOp =
4176           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4177                                                         SI1->getOperand(0),
4178                                                         SI0->getName()), I);
4179         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4180                                       SI1->getOperand(1));
4181       }
4182   }
4183
4184   // If and'ing two fcmp, try combine them into one.
4185   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4186     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4187       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4188           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4189         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4190         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4191           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4192             // If either of the constants are nans, then the whole thing returns
4193             // false.
4194             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4195               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4196             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4197                                 RHS->getOperand(0));
4198           }
4199       } else {
4200         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4201         FCmpInst::Predicate Op0CC, Op1CC;
4202         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4203             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4204           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4205             // Swap RHS operands to match LHS.
4206             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4207             std::swap(Op1LHS, Op1RHS);
4208           }
4209           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4210             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4211             if (Op0CC == Op1CC)
4212               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4213             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4214                      Op1CC == FCmpInst::FCMP_FALSE)
4215               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4216             else if (Op0CC == FCmpInst::FCMP_TRUE)
4217               return ReplaceInstUsesWith(I, Op1);
4218             else if (Op1CC == FCmpInst::FCMP_TRUE)
4219               return ReplaceInstUsesWith(I, Op0);
4220             bool Op0Ordered;
4221             bool Op1Ordered;
4222             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4223             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4224             if (Op1Pred == 0) {
4225               std::swap(Op0, Op1);
4226               std::swap(Op0Pred, Op1Pred);
4227               std::swap(Op0Ordered, Op1Ordered);
4228             }
4229             if (Op0Pred == 0) {
4230               // uno && ueq -> uno && (uno || eq) -> ueq
4231               // ord && olt -> ord && (ord && lt) -> olt
4232               if (Op0Ordered == Op1Ordered)
4233                 return ReplaceInstUsesWith(I, Op1);
4234               // uno && oeq -> uno && (ord && eq) -> false
4235               // uno && ord -> false
4236               if (!Op0Ordered)
4237                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4238               // ord && ueq -> ord && (uno || eq) -> oeq
4239               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4240                                                     Op0LHS, Op0RHS));
4241             }
4242           }
4243         }
4244       }
4245     }
4246   }
4247
4248   return Changed ? &I : 0;
4249 }
4250
4251 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4252 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4253 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4254 /// the expression came from the corresponding "byte swapped" byte in some other
4255 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4256 /// we know that the expression deposits the low byte of %X into the high byte
4257 /// of the bswap result and that all other bytes are zero.  This expression is
4258 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4259 /// match.
4260 ///
4261 /// This function returns true if the match was unsuccessful and false if so.
4262 /// On entry to the function the "OverallLeftShift" is a signed integer value
4263 /// indicating the number of bytes that the subexpression is later shifted.  For
4264 /// example, if the expression is later right shifted by 16 bits, the
4265 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4266 /// byte of ByteValues is actually being set.
4267 ///
4268 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4269 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4270 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4271 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4272 /// always in the local (OverallLeftShift) coordinate space.
4273 ///
4274 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4275                               SmallVector<Value*, 8> &ByteValues) {
4276   if (Instruction *I = dyn_cast<Instruction>(V)) {
4277     // If this is an or instruction, it may be an inner node of the bswap.
4278     if (I->getOpcode() == Instruction::Or) {
4279       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4280                                ByteValues) ||
4281              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4282                                ByteValues);
4283     }
4284   
4285     // If this is a logical shift by a constant multiple of 8, recurse with
4286     // OverallLeftShift and ByteMask adjusted.
4287     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4288       unsigned ShAmt = 
4289         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4290       // Ensure the shift amount is defined and of a byte value.
4291       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4292         return true;
4293
4294       unsigned ByteShift = ShAmt >> 3;
4295       if (I->getOpcode() == Instruction::Shl) {
4296         // X << 2 -> collect(X, +2)
4297         OverallLeftShift += ByteShift;
4298         ByteMask >>= ByteShift;
4299       } else {
4300         // X >>u 2 -> collect(X, -2)
4301         OverallLeftShift -= ByteShift;
4302         ByteMask <<= ByteShift;
4303         ByteMask &= (~0U >> (32-ByteValues.size()));
4304       }
4305
4306       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4307       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4308
4309       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4310                                ByteValues);
4311     }
4312
4313     // If this is a logical 'and' with a mask that clears bytes, clear the
4314     // corresponding bytes in ByteMask.
4315     if (I->getOpcode() == Instruction::And &&
4316         isa<ConstantInt>(I->getOperand(1))) {
4317       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4318       unsigned NumBytes = ByteValues.size();
4319       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4320       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4321       
4322       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4323         // If this byte is masked out by a later operation, we don't care what
4324         // the and mask is.
4325         if ((ByteMask & (1 << i)) == 0)
4326           continue;
4327         
4328         // If the AndMask is all zeros for this byte, clear the bit.
4329         APInt MaskB = AndMask & Byte;
4330         if (MaskB == 0) {
4331           ByteMask &= ~(1U << i);
4332           continue;
4333         }
4334         
4335         // If the AndMask is not all ones for this byte, it's not a bytezap.
4336         if (MaskB != Byte)
4337           return true;
4338
4339         // Otherwise, this byte is kept.
4340       }
4341
4342       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4343                                ByteValues);
4344     }
4345   }
4346   
4347   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4348   // the input value to the bswap.  Some observations: 1) if more than one byte
4349   // is demanded from this input, then it could not be successfully assembled
4350   // into a byteswap.  At least one of the two bytes would not be aligned with
4351   // their ultimate destination.
4352   if (!isPowerOf2_32(ByteMask)) return true;
4353   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4354   
4355   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4356   // is demanded, it needs to go into byte 0 of the result.  This means that the
4357   // byte needs to be shifted until it lands in the right byte bucket.  The
4358   // shift amount depends on the position: if the byte is coming from the high
4359   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4360   // low part, it must be shifted left.
4361   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4362   if (InputByteNo < ByteValues.size()/2) {
4363     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4364       return true;
4365   } else {
4366     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4367       return true;
4368   }
4369   
4370   // If the destination byte value is already defined, the values are or'd
4371   // together, which isn't a bswap (unless it's an or of the same bits).
4372   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4373     return true;
4374   ByteValues[DestByteNo] = V;
4375   return false;
4376 }
4377
4378 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4379 /// If so, insert the new bswap intrinsic and return it.
4380 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4381   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4382   if (!ITy || ITy->getBitWidth() % 16 || 
4383       // ByteMask only allows up to 32-byte values.
4384       ITy->getBitWidth() > 32*8) 
4385     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4386   
4387   /// ByteValues - For each byte of the result, we keep track of which value
4388   /// defines each byte.
4389   SmallVector<Value*, 8> ByteValues;
4390   ByteValues.resize(ITy->getBitWidth()/8);
4391     
4392   // Try to find all the pieces corresponding to the bswap.
4393   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4394   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4395     return 0;
4396   
4397   // Check to see if all of the bytes come from the same value.
4398   Value *V = ByteValues[0];
4399   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4400   
4401   // Check to make sure that all of the bytes come from the same value.
4402   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4403     if (ByteValues[i] != V)
4404       return 0;
4405   const Type *Tys[] = { ITy };
4406   Module *M = I.getParent()->getParent()->getParent();
4407   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4408   return CallInst::Create(F, V);
4409 }
4410
4411 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4412 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4413 /// we can simplify this expression to "cond ? C : D or B".
4414 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4415                                          Value *C, Value *D) {
4416   // If A is not a select of -1/0, this cannot match.
4417   Value *Cond = 0;
4418   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4419     return 0;
4420
4421   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4422   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4423     return SelectInst::Create(Cond, C, B);
4424   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4425     return SelectInst::Create(Cond, C, B);
4426   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4427   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4428     return SelectInst::Create(Cond, C, D);
4429   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4430     return SelectInst::Create(Cond, C, D);
4431   return 0;
4432 }
4433
4434 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4435 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4436                                          ICmpInst *LHS, ICmpInst *RHS) {
4437   Value *Val, *Val2;
4438   ConstantInt *LHSCst, *RHSCst;
4439   ICmpInst::Predicate LHSCC, RHSCC;
4440   
4441   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4442   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4443       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4444     return 0;
4445   
4446   // From here on, we only handle:
4447   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4448   if (Val != Val2) return 0;
4449   
4450   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4451   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4452       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4453       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4454       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4455     return 0;
4456   
4457   // We can't fold (ugt x, C) | (sgt x, C2).
4458   if (!PredicatesFoldable(LHSCC, RHSCC))
4459     return 0;
4460   
4461   // Ensure that the larger constant is on the RHS.
4462   bool ShouldSwap;
4463   if (ICmpInst::isSignedPredicate(LHSCC) ||
4464       (ICmpInst::isEquality(LHSCC) && 
4465        ICmpInst::isSignedPredicate(RHSCC)))
4466     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4467   else
4468     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4469   
4470   if (ShouldSwap) {
4471     std::swap(LHS, RHS);
4472     std::swap(LHSCst, RHSCst);
4473     std::swap(LHSCC, RHSCC);
4474   }
4475   
4476   // At this point, we know we have have two icmp instructions
4477   // comparing a value against two constants and or'ing the result
4478   // together.  Because of the above check, we know that we only have
4479   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4480   // FoldICmpLogical check above), that the two constants are not
4481   // equal.
4482   assert(LHSCst != RHSCst && "Compares not folded above?");
4483
4484   switch (LHSCC) {
4485   default: assert(0 && "Unknown integer condition code!");
4486   case ICmpInst::ICMP_EQ:
4487     switch (RHSCC) {
4488     default: assert(0 && "Unknown integer condition code!");
4489     case ICmpInst::ICMP_EQ:
4490       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4491         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4492         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4493                                                      Val->getName()+".off");
4494         InsertNewInstBefore(Add, I);
4495         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4496         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4497       }
4498       break;                         // (X == 13 | X == 15) -> no change
4499     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4500     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4501       break;
4502     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4503     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4504     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4505       return ReplaceInstUsesWith(I, RHS);
4506     }
4507     break;
4508   case ICmpInst::ICMP_NE:
4509     switch (RHSCC) {
4510     default: assert(0 && "Unknown integer condition code!");
4511     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4512     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4513     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4514       return ReplaceInstUsesWith(I, LHS);
4515     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4516     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4517     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4518       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4519     }
4520     break;
4521   case ICmpInst::ICMP_ULT:
4522     switch (RHSCC) {
4523     default: assert(0 && "Unknown integer condition code!");
4524     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4525       break;
4526     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4527       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4528       // this can cause overflow.
4529       if (RHSCst->isMaxValue(false))
4530         return ReplaceInstUsesWith(I, LHS);
4531       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4532     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4533       break;
4534     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4535     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4536       return ReplaceInstUsesWith(I, RHS);
4537     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4538       break;
4539     }
4540     break;
4541   case ICmpInst::ICMP_SLT:
4542     switch (RHSCC) {
4543     default: assert(0 && "Unknown integer condition code!");
4544     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4545       break;
4546     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4547       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4548       // this can cause overflow.
4549       if (RHSCst->isMaxValue(true))
4550         return ReplaceInstUsesWith(I, LHS);
4551       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4552     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4553       break;
4554     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4555     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4556       return ReplaceInstUsesWith(I, RHS);
4557     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4558       break;
4559     }
4560     break;
4561   case ICmpInst::ICMP_UGT:
4562     switch (RHSCC) {
4563     default: assert(0 && "Unknown integer condition code!");
4564     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4565     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4566       return ReplaceInstUsesWith(I, LHS);
4567     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4568       break;
4569     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4570     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4571       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4572     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4573       break;
4574     }
4575     break;
4576   case ICmpInst::ICMP_SGT:
4577     switch (RHSCC) {
4578     default: assert(0 && "Unknown integer condition code!");
4579     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4580     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4581       return ReplaceInstUsesWith(I, LHS);
4582     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4583       break;
4584     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4585     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4586       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4587     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4588       break;
4589     }
4590     break;
4591   }
4592   return 0;
4593 }
4594
4595 /// FoldOrWithConstants - This helper function folds:
4596 ///
4597 ///     ((A | B) & C1) | (B & C2)
4598 ///
4599 /// into:
4600 /// 
4601 ///     (A & C1) | B
4602 ///
4603 /// when the XOR of the two constants is "all ones" (-1).
4604 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4605                                                Value *A, Value *B, Value *C) {
4606   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4607   if (!CI1) return 0;
4608
4609   Value *V1 = 0;
4610   ConstantInt *CI2 = 0;
4611   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4612
4613   APInt Xor = CI1->getValue() ^ CI2->getValue();
4614   if (!Xor.isAllOnesValue()) return 0;
4615
4616   if (V1 == A || V1 == B) {
4617     Instruction *NewOp =
4618       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4619     return BinaryOperator::CreateOr(NewOp, V1);
4620   }
4621
4622   return 0;
4623 }
4624
4625 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4626   bool Changed = SimplifyCommutative(I);
4627   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4628
4629   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4630     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4631
4632   // or X, X = X
4633   if (Op0 == Op1)
4634     return ReplaceInstUsesWith(I, Op0);
4635
4636   // See if we can simplify any instructions used by the instruction whose sole 
4637   // purpose is to compute bits we don't care about.
4638   if (SimplifyDemandedInstructionBits(I))
4639     return &I;
4640   if (isa<VectorType>(I.getType())) {
4641     if (isa<ConstantAggregateZero>(Op1)) {
4642       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4643     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4644       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4645         return ReplaceInstUsesWith(I, I.getOperand(1));
4646     }
4647   }
4648
4649   // or X, -1 == -1
4650   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4651     ConstantInt *C1 = 0; Value *X = 0;
4652     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4653     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4654       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4655       InsertNewInstBefore(Or, I);
4656       Or->takeName(Op0);
4657       return BinaryOperator::CreateAnd(Or, 
4658                ConstantInt::get(RHS->getValue() | C1->getValue()));
4659     }
4660
4661     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4662     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4663       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4664       InsertNewInstBefore(Or, I);
4665       Or->takeName(Op0);
4666       return BinaryOperator::CreateXor(Or,
4667                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4668     }
4669
4670     // Try to fold constant and into select arguments.
4671     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4672       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4673         return R;
4674     if (isa<PHINode>(Op0))
4675       if (Instruction *NV = FoldOpIntoPhi(I))
4676         return NV;
4677   }
4678
4679   Value *A = 0, *B = 0;
4680   ConstantInt *C1 = 0, *C2 = 0;
4681
4682   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4683     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4684       return ReplaceInstUsesWith(I, Op1);
4685   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4686     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4687       return ReplaceInstUsesWith(I, Op0);
4688
4689   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4690   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4691   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4692       match(Op1, m_Or(m_Value(), m_Value())) ||
4693       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4694        match(Op1, m_Shift(m_Value(), m_Value())))) {
4695     if (Instruction *BSwap = MatchBSwap(I))
4696       return BSwap;
4697   }
4698   
4699   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4700   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4701       MaskedValueIsZero(Op1, C1->getValue())) {
4702     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4703     InsertNewInstBefore(NOr, I);
4704     NOr->takeName(Op0);
4705     return BinaryOperator::CreateXor(NOr, C1);
4706   }
4707
4708   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4709   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4710       MaskedValueIsZero(Op0, C1->getValue())) {
4711     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4712     InsertNewInstBefore(NOr, I);
4713     NOr->takeName(Op0);
4714     return BinaryOperator::CreateXor(NOr, C1);
4715   }
4716
4717   // (A & C)|(B & D)
4718   Value *C = 0, *D = 0;
4719   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4720       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4721     Value *V1 = 0, *V2 = 0, *V3 = 0;
4722     C1 = dyn_cast<ConstantInt>(C);
4723     C2 = dyn_cast<ConstantInt>(D);
4724     if (C1 && C2) {  // (A & C1)|(B & C2)
4725       // If we have: ((V + N) & C1) | (V & C2)
4726       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4727       // replace with V+N.
4728       if (C1->getValue() == ~C2->getValue()) {
4729         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4730             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4731           // Add commutes, try both ways.
4732           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4733             return ReplaceInstUsesWith(I, A);
4734           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4735             return ReplaceInstUsesWith(I, A);
4736         }
4737         // Or commutes, try both ways.
4738         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4739             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4740           // Add commutes, try both ways.
4741           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4742             return ReplaceInstUsesWith(I, B);
4743           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4744             return ReplaceInstUsesWith(I, B);
4745         }
4746       }
4747       V1 = 0; V2 = 0; V3 = 0;
4748     }
4749     
4750     // Check to see if we have any common things being and'ed.  If so, find the
4751     // terms for V1 & (V2|V3).
4752     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4753       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4754         V1 = A, V2 = C, V3 = D;
4755       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4756         V1 = A, V2 = B, V3 = C;
4757       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4758         V1 = C, V2 = A, V3 = D;
4759       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4760         V1 = C, V2 = A, V3 = B;
4761       
4762       if (V1) {
4763         Value *Or =
4764           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4765         return BinaryOperator::CreateAnd(V1, Or);
4766       }
4767     }
4768
4769     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4770     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4771       return Match;
4772     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4773       return Match;
4774     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4775       return Match;
4776     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4777       return Match;
4778
4779     // ((A&~B)|(~A&B)) -> A^B
4780     if ((match(C, m_Not(m_Specific(D))) &&
4781          match(B, m_Not(m_Specific(A)))))
4782       return BinaryOperator::CreateXor(A, D);
4783     // ((~B&A)|(~A&B)) -> A^B
4784     if ((match(A, m_Not(m_Specific(D))) &&
4785          match(B, m_Not(m_Specific(C)))))
4786       return BinaryOperator::CreateXor(C, D);
4787     // ((A&~B)|(B&~A)) -> A^B
4788     if ((match(C, m_Not(m_Specific(B))) &&
4789          match(D, m_Not(m_Specific(A)))))
4790       return BinaryOperator::CreateXor(A, B);
4791     // ((~B&A)|(B&~A)) -> A^B
4792     if ((match(A, m_Not(m_Specific(B))) &&
4793          match(D, m_Not(m_Specific(C)))))
4794       return BinaryOperator::CreateXor(C, B);
4795   }
4796   
4797   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4798   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4799     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4800       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4801           SI0->getOperand(1) == SI1->getOperand(1) &&
4802           (SI0->hasOneUse() || SI1->hasOneUse())) {
4803         Instruction *NewOp =
4804         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4805                                                      SI1->getOperand(0),
4806                                                      SI0->getName()), I);
4807         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4808                                       SI1->getOperand(1));
4809       }
4810   }
4811
4812   // ((A|B)&1)|(B&-2) -> (A&1) | B
4813   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4814       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4815     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4816     if (Ret) return Ret;
4817   }
4818   // (B&-2)|((A|B)&1) -> (A&1) | B
4819   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4820       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4821     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4822     if (Ret) return Ret;
4823   }
4824
4825   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4826     if (A == Op1)   // ~A | A == -1
4827       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4828   } else {
4829     A = 0;
4830   }
4831   // Note, A is still live here!
4832   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4833     if (Op0 == B)
4834       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4835
4836     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4837     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4838       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4839                                               I.getName()+".demorgan"), I);
4840       return BinaryOperator::CreateNot(And);
4841     }
4842   }
4843
4844   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4845   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4846     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4847       return R;
4848
4849     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4850       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4851         return Res;
4852   }
4853     
4854   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4855   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4856     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4857       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4858         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4859             !isa<ICmpInst>(Op1C->getOperand(0))) {
4860           const Type *SrcTy = Op0C->getOperand(0)->getType();
4861           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4862               // Only do this if the casts both really cause code to be
4863               // generated.
4864               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4865                                 I.getType(), TD) &&
4866               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4867                                 I.getType(), TD)) {
4868             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4869                                                           Op1C->getOperand(0),
4870                                                           I.getName());
4871             InsertNewInstBefore(NewOp, I);
4872             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4873           }
4874         }
4875       }
4876   }
4877   
4878     
4879   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4880   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4881     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4882       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4883           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4884           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4885         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4886           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4887             // If either of the constants are nans, then the whole thing returns
4888             // true.
4889             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4890               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4891             
4892             // Otherwise, no need to compare the two constants, compare the
4893             // rest.
4894             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4895                                 RHS->getOperand(0));
4896           }
4897       } else {
4898         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4899         FCmpInst::Predicate Op0CC, Op1CC;
4900         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4901             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4902           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4903             // Swap RHS operands to match LHS.
4904             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4905             std::swap(Op1LHS, Op1RHS);
4906           }
4907           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4908             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4909             if (Op0CC == Op1CC)
4910               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4911             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4912                      Op1CC == FCmpInst::FCMP_TRUE)
4913               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4914             else if (Op0CC == FCmpInst::FCMP_FALSE)
4915               return ReplaceInstUsesWith(I, Op1);
4916             else if (Op1CC == FCmpInst::FCMP_FALSE)
4917               return ReplaceInstUsesWith(I, Op0);
4918             bool Op0Ordered;
4919             bool Op1Ordered;
4920             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4921             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4922             if (Op0Ordered == Op1Ordered) {
4923               // If both are ordered or unordered, return a new fcmp with
4924               // or'ed predicates.
4925               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4926                                        Op0LHS, Op0RHS);
4927               if (Instruction *I = dyn_cast<Instruction>(RV))
4928                 return I;
4929               // Otherwise, it's a constant boolean value...
4930               return ReplaceInstUsesWith(I, RV);
4931             }
4932           }
4933         }
4934       }
4935     }
4936   }
4937
4938   return Changed ? &I : 0;
4939 }
4940
4941 namespace {
4942
4943 // XorSelf - Implements: X ^ X --> 0
4944 struct XorSelf {
4945   Value *RHS;
4946   XorSelf(Value *rhs) : RHS(rhs) {}
4947   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4948   Instruction *apply(BinaryOperator &Xor) const {
4949     return &Xor;
4950   }
4951 };
4952
4953 }
4954
4955 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4956   bool Changed = SimplifyCommutative(I);
4957   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4958
4959   if (isa<UndefValue>(Op1)) {
4960     if (isa<UndefValue>(Op0))
4961       // Handle undef ^ undef -> 0 special case. This is a common
4962       // idiom (misuse).
4963       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4964     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4965   }
4966
4967   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4968   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4969     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4970     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4971   }
4972   
4973   // See if we can simplify any instructions used by the instruction whose sole 
4974   // purpose is to compute bits we don't care about.
4975   if (SimplifyDemandedInstructionBits(I))
4976     return &I;
4977   if (isa<VectorType>(I.getType()))
4978     if (isa<ConstantAggregateZero>(Op1))
4979       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4980
4981   // Is this a ~ operation?
4982   if (Value *NotOp = dyn_castNotVal(&I)) {
4983     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4984     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4985     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4986       if (Op0I->getOpcode() == Instruction::And || 
4987           Op0I->getOpcode() == Instruction::Or) {
4988         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4989         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4990           Instruction *NotY =
4991             BinaryOperator::CreateNot(Op0I->getOperand(1),
4992                                       Op0I->getOperand(1)->getName()+".not");
4993           InsertNewInstBefore(NotY, I);
4994           if (Op0I->getOpcode() == Instruction::And)
4995             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4996           else
4997             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4998         }
4999       }
5000     }
5001   }
5002   
5003   
5004   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5005     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
5006       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5007       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5008         return new ICmpInst(ICI->getInversePredicate(),
5009                             ICI->getOperand(0), ICI->getOperand(1));
5010
5011       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5012         return new FCmpInst(FCI->getInversePredicate(),
5013                             FCI->getOperand(0), FCI->getOperand(1));
5014     }
5015
5016     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5017     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5018       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5019         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5020           Instruction::CastOps Opcode = Op0C->getOpcode();
5021           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5022             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
5023                                              Op0C->getDestTy())) {
5024               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5025                                      CI->getOpcode(), CI->getInversePredicate(),
5026                                      CI->getOperand(0), CI->getOperand(1)), I);
5027               NewCI->takeName(CI);
5028               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5029             }
5030           }
5031         }
5032       }
5033     }
5034
5035     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5036       // ~(c-X) == X-c-1 == X+(-c-1)
5037       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5038         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5039           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5040           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5041                                               ConstantInt::get(I.getType(), 1));
5042           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5043         }
5044           
5045       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5046         if (Op0I->getOpcode() == Instruction::Add) {
5047           // ~(X-c) --> (-c-1)-X
5048           if (RHS->isAllOnesValue()) {
5049             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5050             return BinaryOperator::CreateSub(
5051                            ConstantExpr::getSub(NegOp0CI,
5052                                              ConstantInt::get(I.getType(), 1)),
5053                                           Op0I->getOperand(0));
5054           } else if (RHS->getValue().isSignBit()) {
5055             // (X + C) ^ signbit -> (X + C + signbit)
5056             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
5057             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5058
5059           }
5060         } else if (Op0I->getOpcode() == Instruction::Or) {
5061           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5062           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5063             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5064             // Anything in both C1 and C2 is known to be zero, remove it from
5065             // NewRHS.
5066             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5067             NewRHS = ConstantExpr::getAnd(NewRHS, 
5068                                           ConstantExpr::getNot(CommonBits));
5069             AddToWorkList(Op0I);
5070             I.setOperand(0, Op0I->getOperand(0));
5071             I.setOperand(1, NewRHS);
5072             return &I;
5073           }
5074         }
5075       }
5076     }
5077
5078     // Try to fold constant and into select arguments.
5079     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5080       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5081         return R;
5082     if (isa<PHINode>(Op0))
5083       if (Instruction *NV = FoldOpIntoPhi(I))
5084         return NV;
5085   }
5086
5087   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5088     if (X == Op1)
5089       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5090
5091   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5092     if (X == Op0)
5093       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5094
5095   
5096   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5097   if (Op1I) {
5098     Value *A, *B;
5099     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5100       if (A == Op0) {              // B^(B|A) == (A|B)^B
5101         Op1I->swapOperands();
5102         I.swapOperands();
5103         std::swap(Op0, Op1);
5104       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5105         I.swapOperands();     // Simplified below.
5106         std::swap(Op0, Op1);
5107       }
5108     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5109       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5110     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5111       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5112     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5113       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5114         Op1I->swapOperands();
5115         std::swap(A, B);
5116       }
5117       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5118         I.swapOperands();     // Simplified below.
5119         std::swap(Op0, Op1);
5120       }
5121     }
5122   }
5123   
5124   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5125   if (Op0I) {
5126     Value *A, *B;
5127     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5128       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5129         std::swap(A, B);
5130       if (B == Op1) {                                // (A|B)^B == A & ~B
5131         Instruction *NotB =
5132           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5133         return BinaryOperator::CreateAnd(A, NotB);
5134       }
5135     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5136       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5137     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5138       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5139     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5140       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5141         std::swap(A, B);
5142       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5143           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5144         Instruction *N =
5145           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5146         return BinaryOperator::CreateAnd(N, Op1);
5147       }
5148     }
5149   }
5150   
5151   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5152   if (Op0I && Op1I && Op0I->isShift() && 
5153       Op0I->getOpcode() == Op1I->getOpcode() && 
5154       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5155       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5156     Instruction *NewOp =
5157       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5158                                                     Op1I->getOperand(0),
5159                                                     Op0I->getName()), I);
5160     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5161                                   Op1I->getOperand(1));
5162   }
5163     
5164   if (Op0I && Op1I) {
5165     Value *A, *B, *C, *D;
5166     // (A & B)^(A | B) -> A ^ B
5167     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5168         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5169       if ((A == C && B == D) || (A == D && B == C)) 
5170         return BinaryOperator::CreateXor(A, B);
5171     }
5172     // (A | B)^(A & B) -> A ^ B
5173     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5174         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5175       if ((A == C && B == D) || (A == D && B == C)) 
5176         return BinaryOperator::CreateXor(A, B);
5177     }
5178     
5179     // (A & B)^(C & D)
5180     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5181         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5182         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5183       // (X & Y)^(X & Y) -> (Y^Z) & X
5184       Value *X = 0, *Y = 0, *Z = 0;
5185       if (A == C)
5186         X = A, Y = B, Z = D;
5187       else if (A == D)
5188         X = A, Y = B, Z = C;
5189       else if (B == C)
5190         X = B, Y = A, Z = D;
5191       else if (B == D)
5192         X = B, Y = A, Z = C;
5193       
5194       if (X) {
5195         Instruction *NewOp =
5196         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5197         return BinaryOperator::CreateAnd(NewOp, X);
5198       }
5199     }
5200   }
5201     
5202   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5203   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5204     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5205       return R;
5206
5207   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5208   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5209     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5210       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5211         const Type *SrcTy = Op0C->getOperand(0)->getType();
5212         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5213             // Only do this if the casts both really cause code to be generated.
5214             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5215                               I.getType(), TD) &&
5216             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5217                               I.getType(), TD)) {
5218           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5219                                                          Op1C->getOperand(0),
5220                                                          I.getName());
5221           InsertNewInstBefore(NewOp, I);
5222           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5223         }
5224       }
5225   }
5226
5227   return Changed ? &I : 0;
5228 }
5229
5230 static ConstantInt *ExtractElement(Constant *V, Constant *Idx) {
5231   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5232 }
5233
5234 static bool HasAddOverflow(ConstantInt *Result,
5235                            ConstantInt *In1, ConstantInt *In2,
5236                            bool IsSigned) {
5237   if (IsSigned)
5238     if (In2->getValue().isNegative())
5239       return Result->getValue().sgt(In1->getValue());
5240     else
5241       return Result->getValue().slt(In1->getValue());
5242   else
5243     return Result->getValue().ult(In1->getValue());
5244 }
5245
5246 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5247 /// overflowed for this type.
5248 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5249                             Constant *In2, bool IsSigned = false) {
5250   Result = ConstantExpr::getAdd(In1, In2);
5251
5252   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5253     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5254       Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5255       if (HasAddOverflow(ExtractElement(Result, Idx),
5256                          ExtractElement(In1, Idx),
5257                          ExtractElement(In2, Idx),
5258                          IsSigned))
5259         return true;
5260     }
5261     return false;
5262   }
5263
5264   return HasAddOverflow(cast<ConstantInt>(Result),
5265                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5266                         IsSigned);
5267 }
5268
5269 static bool HasSubOverflow(ConstantInt *Result,
5270                            ConstantInt *In1, ConstantInt *In2,
5271                            bool IsSigned) {
5272   if (IsSigned)
5273     if (In2->getValue().isNegative())
5274       return Result->getValue().slt(In1->getValue());
5275     else
5276       return Result->getValue().sgt(In1->getValue());
5277   else
5278     return Result->getValue().ugt(In1->getValue());
5279 }
5280
5281 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5282 /// overflowed for this type.
5283 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5284                             Constant *In2, bool IsSigned = false) {
5285   Result = ConstantExpr::getSub(In1, In2);
5286
5287   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5288     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5289       Constant *Idx = ConstantInt::get(Type::Int32Ty, i);
5290       if (HasSubOverflow(ExtractElement(Result, Idx),
5291                          ExtractElement(In1, Idx),
5292                          ExtractElement(In2, Idx),
5293                          IsSigned))
5294         return true;
5295     }
5296     return false;
5297   }
5298
5299   return HasSubOverflow(cast<ConstantInt>(Result),
5300                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5301                         IsSigned);
5302 }
5303
5304 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5305 /// code necessary to compute the offset from the base pointer (without adding
5306 /// in the base pointer).  Return the result as a signed integer of intptr size.
5307 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5308   TargetData &TD = IC.getTargetData();
5309   gep_type_iterator GTI = gep_type_begin(GEP);
5310   const Type *IntPtrTy = TD.getIntPtrType();
5311   Value *Result = Constant::getNullValue(IntPtrTy);
5312
5313   // Build a mask for high order bits.
5314   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5315   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5316
5317   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5318        ++i, ++GTI) {
5319     Value *Op = *i;
5320     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5321     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5322       if (OpC->isZero()) continue;
5323       
5324       // Handle a struct index, which adds its field offset to the pointer.
5325       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5326         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5327         
5328         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5329           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5330         else
5331           Result = IC.InsertNewInstBefore(
5332                    BinaryOperator::CreateAdd(Result,
5333                                              ConstantInt::get(IntPtrTy, Size),
5334                                              GEP->getName()+".offs"), I);
5335         continue;
5336       }
5337       
5338       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5339       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5340       Scale = ConstantExpr::getMul(OC, Scale);
5341       if (Constant *RC = dyn_cast<Constant>(Result))
5342         Result = ConstantExpr::getAdd(RC, Scale);
5343       else {
5344         // Emit an add instruction.
5345         Result = IC.InsertNewInstBefore(
5346            BinaryOperator::CreateAdd(Result, Scale,
5347                                      GEP->getName()+".offs"), I);
5348       }
5349       continue;
5350     }
5351     // Convert to correct type.
5352     if (Op->getType() != IntPtrTy) {
5353       if (Constant *OpC = dyn_cast<Constant>(Op))
5354         Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
5355       else
5356         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5357                                                                 true,
5358                                                       Op->getName()+".c"), I);
5359     }
5360     if (Size != 1) {
5361       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5362       if (Constant *OpC = dyn_cast<Constant>(Op))
5363         Op = ConstantExpr::getMul(OpC, Scale);
5364       else    // We'll let instcombine(mul) convert this to a shl if possible.
5365         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5366                                                   GEP->getName()+".idx"), I);
5367     }
5368
5369     // Emit an add instruction.
5370     if (isa<Constant>(Op) && isa<Constant>(Result))
5371       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5372                                     cast<Constant>(Result));
5373     else
5374       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5375                                                   GEP->getName()+".offs"), I);
5376   }
5377   return Result;
5378 }
5379
5380
5381 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5382 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5383 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5384 /// complex, and scales are involved.  The above expression would also be legal
5385 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5386 /// later form is less amenable to optimization though, and we are allowed to
5387 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5388 ///
5389 /// If we can't emit an optimized form for this expression, this returns null.
5390 /// 
5391 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5392                                           InstCombiner &IC) {
5393   TargetData &TD = IC.getTargetData();
5394   gep_type_iterator GTI = gep_type_begin(GEP);
5395
5396   // Check to see if this gep only has a single variable index.  If so, and if
5397   // any constant indices are a multiple of its scale, then we can compute this
5398   // in terms of the scale of the variable index.  For example, if the GEP
5399   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5400   // because the expression will cross zero at the same point.
5401   unsigned i, e = GEP->getNumOperands();
5402   int64_t Offset = 0;
5403   for (i = 1; i != e; ++i, ++GTI) {
5404     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5405       // Compute the aggregate offset of constant indices.
5406       if (CI->isZero()) continue;
5407
5408       // Handle a struct index, which adds its field offset to the pointer.
5409       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5410         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5411       } else {
5412         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5413         Offset += Size*CI->getSExtValue();
5414       }
5415     } else {
5416       // Found our variable index.
5417       break;
5418     }
5419   }
5420   
5421   // If there are no variable indices, we must have a constant offset, just
5422   // evaluate it the general way.
5423   if (i == e) return 0;
5424   
5425   Value *VariableIdx = GEP->getOperand(i);
5426   // Determine the scale factor of the variable element.  For example, this is
5427   // 4 if the variable index is into an array of i32.
5428   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5429   
5430   // Verify that there are no other variable indices.  If so, emit the hard way.
5431   for (++i, ++GTI; i != e; ++i, ++GTI) {
5432     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5433     if (!CI) return 0;
5434    
5435     // Compute the aggregate offset of constant indices.
5436     if (CI->isZero()) continue;
5437     
5438     // Handle a struct index, which adds its field offset to the pointer.
5439     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5440       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5441     } else {
5442       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5443       Offset += Size*CI->getSExtValue();
5444     }
5445   }
5446   
5447   // Okay, we know we have a single variable index, which must be a
5448   // pointer/array/vector index.  If there is no offset, life is simple, return
5449   // the index.
5450   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5451   if (Offset == 0) {
5452     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5453     // we don't need to bother extending: the extension won't affect where the
5454     // computation crosses zero.
5455     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5456       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5457                                   VariableIdx->getNameStart(), &I);
5458     return VariableIdx;
5459   }
5460   
5461   // Otherwise, there is an index.  The computation we will do will be modulo
5462   // the pointer size, so get it.
5463   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5464   
5465   Offset &= PtrSizeMask;
5466   VariableScale &= PtrSizeMask;
5467
5468   // To do this transformation, any constant index must be a multiple of the
5469   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5470   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5471   // multiple of the variable scale.
5472   int64_t NewOffs = Offset / (int64_t)VariableScale;
5473   if (Offset != NewOffs*(int64_t)VariableScale)
5474     return 0;
5475
5476   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5477   const Type *IntPtrTy = TD.getIntPtrType();
5478   if (VariableIdx->getType() != IntPtrTy)
5479     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5480                                               true /*SExt*/, 
5481                                               VariableIdx->getNameStart(), &I);
5482   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5483   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5484 }
5485
5486
5487 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5488 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5489 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5490                                        ICmpInst::Predicate Cond,
5491                                        Instruction &I) {
5492   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5493
5494   // Look through bitcasts.
5495   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5496     RHS = BCI->getOperand(0);
5497
5498   Value *PtrBase = GEPLHS->getOperand(0);
5499   if (PtrBase == RHS) {
5500     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5501     // This transformation (ignoring the base and scales) is valid because we
5502     // know pointers can't overflow.  See if we can output an optimized form.
5503     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5504     
5505     // If not, synthesize the offset the hard way.
5506     if (Offset == 0)
5507       Offset = EmitGEPOffset(GEPLHS, I, *this);
5508     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5509                         Constant::getNullValue(Offset->getType()));
5510   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5511     // If the base pointers are different, but the indices are the same, just
5512     // compare the base pointer.
5513     if (PtrBase != GEPRHS->getOperand(0)) {
5514       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5515       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5516                         GEPRHS->getOperand(0)->getType();
5517       if (IndicesTheSame)
5518         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5519           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5520             IndicesTheSame = false;
5521             break;
5522           }
5523
5524       // If all indices are the same, just compare the base pointers.
5525       if (IndicesTheSame)
5526         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5527                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5528
5529       // Otherwise, the base pointers are different and the indices are
5530       // different, bail out.
5531       return 0;
5532     }
5533
5534     // If one of the GEPs has all zero indices, recurse.
5535     bool AllZeros = true;
5536     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5537       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5538           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5539         AllZeros = false;
5540         break;
5541       }
5542     if (AllZeros)
5543       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5544                           ICmpInst::getSwappedPredicate(Cond), I);
5545
5546     // If the other GEP has all zero indices, recurse.
5547     AllZeros = true;
5548     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5549       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5550           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5551         AllZeros = false;
5552         break;
5553       }
5554     if (AllZeros)
5555       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5556
5557     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5558       // If the GEPs only differ by one index, compare it.
5559       unsigned NumDifferences = 0;  // Keep track of # differences.
5560       unsigned DiffOperand = 0;     // The operand that differs.
5561       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5562         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5563           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5564                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5565             // Irreconcilable differences.
5566             NumDifferences = 2;
5567             break;
5568           } else {
5569             if (NumDifferences++) break;
5570             DiffOperand = i;
5571           }
5572         }
5573
5574       if (NumDifferences == 0)   // SAME GEP?
5575         return ReplaceInstUsesWith(I, // No comparison is needed here.
5576                                    ConstantInt::get(Type::Int1Ty,
5577                                              ICmpInst::isTrueWhenEqual(Cond)));
5578
5579       else if (NumDifferences == 1) {
5580         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5581         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5582         // Make sure we do a signed comparison here.
5583         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5584       }
5585     }
5586
5587     // Only lower this if the icmp is the only user of the GEP or if we expect
5588     // the result to fold to a constant!
5589     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5590         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5591       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5592       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5593       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5594       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5595     }
5596   }
5597   return 0;
5598 }
5599
5600 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5601 ///
5602 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5603                                                 Instruction *LHSI,
5604                                                 Constant *RHSC) {
5605   if (!isa<ConstantFP>(RHSC)) return 0;
5606   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5607   
5608   // Get the width of the mantissa.  We don't want to hack on conversions that
5609   // might lose information from the integer, e.g. "i64 -> float"
5610   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5611   if (MantissaWidth == -1) return 0;  // Unknown.
5612   
5613   // Check to see that the input is converted from an integer type that is small
5614   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5615   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5616   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5617   
5618   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5619   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5620   if (LHSUnsigned)
5621     ++InputSize;
5622   
5623   // If the conversion would lose info, don't hack on this.
5624   if ((int)InputSize > MantissaWidth)
5625     return 0;
5626   
5627   // Otherwise, we can potentially simplify the comparison.  We know that it
5628   // will always come through as an integer value and we know the constant is
5629   // not a NAN (it would have been previously simplified).
5630   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5631   
5632   ICmpInst::Predicate Pred;
5633   switch (I.getPredicate()) {
5634   default: assert(0 && "Unexpected predicate!");
5635   case FCmpInst::FCMP_UEQ:
5636   case FCmpInst::FCMP_OEQ:
5637     Pred = ICmpInst::ICMP_EQ;
5638     break;
5639   case FCmpInst::FCMP_UGT:
5640   case FCmpInst::FCMP_OGT:
5641     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5642     break;
5643   case FCmpInst::FCMP_UGE:
5644   case FCmpInst::FCMP_OGE:
5645     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5646     break;
5647   case FCmpInst::FCMP_ULT:
5648   case FCmpInst::FCMP_OLT:
5649     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5650     break;
5651   case FCmpInst::FCMP_ULE:
5652   case FCmpInst::FCMP_OLE:
5653     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5654     break;
5655   case FCmpInst::FCMP_UNE:
5656   case FCmpInst::FCMP_ONE:
5657     Pred = ICmpInst::ICMP_NE;
5658     break;
5659   case FCmpInst::FCMP_ORD:
5660     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5661   case FCmpInst::FCMP_UNO:
5662     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5663   }
5664   
5665   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5666   
5667   // Now we know that the APFloat is a normal number, zero or inf.
5668   
5669   // See if the FP constant is too large for the integer.  For example,
5670   // comparing an i8 to 300.0.
5671   unsigned IntWidth = IntTy->getScalarSizeInBits();
5672   
5673   if (!LHSUnsigned) {
5674     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5675     // and large values.
5676     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5677     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5678                           APFloat::rmNearestTiesToEven);
5679     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5680       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5681           Pred == ICmpInst::ICMP_SLE)
5682         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5683       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5684     }
5685   } else {
5686     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5687     // +INF and large values.
5688     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5689     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5690                           APFloat::rmNearestTiesToEven);
5691     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5692       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5693           Pred == ICmpInst::ICMP_ULE)
5694         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5695       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5696     }
5697   }
5698   
5699   if (!LHSUnsigned) {
5700     // See if the RHS value is < SignedMin.
5701     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5702     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5703                           APFloat::rmNearestTiesToEven);
5704     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5705       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5706           Pred == ICmpInst::ICMP_SGE)
5707         return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5708       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5709     }
5710   }
5711
5712   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5713   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5714   // casting the FP value to the integer value and back, checking for equality.
5715   // Don't do this for zero, because -0.0 is not fractional.
5716   Constant *RHSInt = LHSUnsigned
5717     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5718     : ConstantExpr::getFPToSI(RHSC, IntTy);
5719   if (!RHS.isZero()) {
5720     bool Equal = LHSUnsigned
5721       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5722       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5723     if (!Equal) {
5724       // If we had a comparison against a fractional value, we have to adjust
5725       // the compare predicate and sometimes the value.  RHSC is rounded towards
5726       // zero at this point.
5727       switch (Pred) {
5728       default: assert(0 && "Unexpected integer comparison!");
5729       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5730         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5731       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5732         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5733       case ICmpInst::ICMP_ULE:
5734         // (float)int <= 4.4   --> int <= 4
5735         // (float)int <= -4.4  --> false
5736         if (RHS.isNegative())
5737           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5738         break;
5739       case ICmpInst::ICMP_SLE:
5740         // (float)int <= 4.4   --> int <= 4
5741         // (float)int <= -4.4  --> int < -4
5742         if (RHS.isNegative())
5743           Pred = ICmpInst::ICMP_SLT;
5744         break;
5745       case ICmpInst::ICMP_ULT:
5746         // (float)int < -4.4   --> false
5747         // (float)int < 4.4    --> int <= 4
5748         if (RHS.isNegative())
5749           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5750         Pred = ICmpInst::ICMP_ULE;
5751         break;
5752       case ICmpInst::ICMP_SLT:
5753         // (float)int < -4.4   --> int < -4
5754         // (float)int < 4.4    --> int <= 4
5755         if (!RHS.isNegative())
5756           Pred = ICmpInst::ICMP_SLE;
5757         break;
5758       case ICmpInst::ICMP_UGT:
5759         // (float)int > 4.4    --> int > 4
5760         // (float)int > -4.4   --> true
5761         if (RHS.isNegative())
5762           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5763         break;
5764       case ICmpInst::ICMP_SGT:
5765         // (float)int > 4.4    --> int > 4
5766         // (float)int > -4.4   --> int >= -4
5767         if (RHS.isNegative())
5768           Pred = ICmpInst::ICMP_SGE;
5769         break;
5770       case ICmpInst::ICMP_UGE:
5771         // (float)int >= -4.4   --> true
5772         // (float)int >= 4.4    --> int > 4
5773         if (!RHS.isNegative())
5774           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5775         Pred = ICmpInst::ICMP_UGT;
5776         break;
5777       case ICmpInst::ICMP_SGE:
5778         // (float)int >= -4.4   --> int >= -4
5779         // (float)int >= 4.4    --> int > 4
5780         if (!RHS.isNegative())
5781           Pred = ICmpInst::ICMP_SGT;
5782         break;
5783       }
5784     }
5785   }
5786
5787   // Lower this FP comparison into an appropriate integer version of the
5788   // comparison.
5789   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5790 }
5791
5792 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5793   bool Changed = SimplifyCompare(I);
5794   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5795
5796   // Fold trivial predicates.
5797   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5798     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5799   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5800     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5801   
5802   // Simplify 'fcmp pred X, X'
5803   if (Op0 == Op1) {
5804     switch (I.getPredicate()) {
5805     default: assert(0 && "Unknown predicate!");
5806     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5807     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5808     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5809       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5810     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5811     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5812     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5813       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5814       
5815     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5816     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5817     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5818     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5819       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5820       I.setPredicate(FCmpInst::FCMP_UNO);
5821       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5822       return &I;
5823       
5824     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5825     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5826     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5827     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5828       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5829       I.setPredicate(FCmpInst::FCMP_ORD);
5830       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5831       return &I;
5832     }
5833   }
5834     
5835   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5836     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5837
5838   // Handle fcmp with constant RHS
5839   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5840     // If the constant is a nan, see if we can fold the comparison based on it.
5841     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5842       if (CFP->getValueAPF().isNaN()) {
5843         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5844           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5845         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5846                "Comparison must be either ordered or unordered!");
5847         // True if unordered.
5848         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5849       }
5850     }
5851     
5852     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5853       switch (LHSI->getOpcode()) {
5854       case Instruction::PHI:
5855         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5856         // block.  If in the same block, we're encouraging jump threading.  If
5857         // not, we are just pessimizing the code by making an i1 phi.
5858         if (LHSI->getParent() == I.getParent())
5859           if (Instruction *NV = FoldOpIntoPhi(I))
5860             return NV;
5861         break;
5862       case Instruction::SIToFP:
5863       case Instruction::UIToFP:
5864         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5865           return NV;
5866         break;
5867       case Instruction::Select:
5868         // If either operand of the select is a constant, we can fold the
5869         // comparison into the select arms, which will cause one to be
5870         // constant folded and the select turned into a bitwise or.
5871         Value *Op1 = 0, *Op2 = 0;
5872         if (LHSI->hasOneUse()) {
5873           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5874             // Fold the known value into the constant operand.
5875             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5876             // Insert a new FCmp of the other select operand.
5877             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5878                                                       LHSI->getOperand(2), RHSC,
5879                                                       I.getName()), I);
5880           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5881             // Fold the known value into the constant operand.
5882             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5883             // Insert a new FCmp of the other select operand.
5884             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5885                                                       LHSI->getOperand(1), RHSC,
5886                                                       I.getName()), I);
5887           }
5888         }
5889
5890         if (Op1)
5891           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5892         break;
5893       }
5894   }
5895
5896   return Changed ? &I : 0;
5897 }
5898
5899 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5900   bool Changed = SimplifyCompare(I);
5901   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5902   const Type *Ty = Op0->getType();
5903
5904   // icmp X, X
5905   if (Op0 == Op1)
5906     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5907                                                    I.isTrueWhenEqual()));
5908
5909   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5910     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5911   
5912   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5913   // addresses never equal each other!  We already know that Op0 != Op1.
5914   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5915        isa<ConstantPointerNull>(Op0)) &&
5916       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5917        isa<ConstantPointerNull>(Op1)))
5918     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5919                                                    !I.isTrueWhenEqual()));
5920
5921   // icmp's with boolean values can always be turned into bitwise operations
5922   if (Ty == Type::Int1Ty) {
5923     switch (I.getPredicate()) {
5924     default: assert(0 && "Invalid icmp instruction!");
5925     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5926       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5927       InsertNewInstBefore(Xor, I);
5928       return BinaryOperator::CreateNot(Xor);
5929     }
5930     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5931       return BinaryOperator::CreateXor(Op0, Op1);
5932
5933     case ICmpInst::ICMP_UGT:
5934       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5935       // FALL THROUGH
5936     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5937       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5938       InsertNewInstBefore(Not, I);
5939       return BinaryOperator::CreateAnd(Not, Op1);
5940     }
5941     case ICmpInst::ICMP_SGT:
5942       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5943       // FALL THROUGH
5944     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5945       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5946       InsertNewInstBefore(Not, I);
5947       return BinaryOperator::CreateAnd(Not, Op0);
5948     }
5949     case ICmpInst::ICMP_UGE:
5950       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5951       // FALL THROUGH
5952     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5953       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5954       InsertNewInstBefore(Not, I);
5955       return BinaryOperator::CreateOr(Not, Op1);
5956     }
5957     case ICmpInst::ICMP_SGE:
5958       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5959       // FALL THROUGH
5960     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5961       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5962       InsertNewInstBefore(Not, I);
5963       return BinaryOperator::CreateOr(Not, Op0);
5964     }
5965     }
5966   }
5967
5968   unsigned BitWidth = 0;
5969   if (TD)
5970     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5971   else if (Ty->isIntOrIntVector())
5972     BitWidth = Ty->getScalarSizeInBits();
5973
5974   bool isSignBit = false;
5975
5976   // See if we are doing a comparison with a constant.
5977   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5978     Value *A = 0, *B = 0;
5979     
5980     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5981     if (I.isEquality() && CI->isNullValue() &&
5982         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5983       // (icmp cond A B) if cond is equality
5984       return new ICmpInst(I.getPredicate(), A, B);
5985     }
5986     
5987     // If we have an icmp le or icmp ge instruction, turn it into the
5988     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5989     // them being folded in the code below.
5990     switch (I.getPredicate()) {
5991     default: break;
5992     case ICmpInst::ICMP_ULE:
5993       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5994         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5995       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5996     case ICmpInst::ICMP_SLE:
5997       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5998         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5999       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
6000     case ICmpInst::ICMP_UGE:
6001       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6002         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6003       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
6004     case ICmpInst::ICMP_SGE:
6005       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6006         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6007       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
6008     }
6009     
6010     // If this comparison is a normal comparison, it demands all
6011     // bits, if it is a sign bit comparison, it only demands the sign bit.
6012     bool UnusedBit;
6013     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6014   }
6015
6016   // See if we can fold the comparison based on range information we can get
6017   // by checking whether bits are known to be zero or one in the input.
6018   if (BitWidth != 0) {
6019     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6020     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6021
6022     if (SimplifyDemandedBits(I.getOperandUse(0),
6023                              isSignBit ? APInt::getSignBit(BitWidth)
6024                                        : APInt::getAllOnesValue(BitWidth),
6025                              Op0KnownZero, Op0KnownOne, 0))
6026       return &I;
6027     if (SimplifyDemandedBits(I.getOperandUse(1),
6028                              APInt::getAllOnesValue(BitWidth),
6029                              Op1KnownZero, Op1KnownOne, 0))
6030       return &I;
6031
6032     // Given the known and unknown bits, compute a range that the LHS could be
6033     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6034     // EQ and NE we use unsigned values.
6035     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6036     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6037     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6038       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6039                                              Op0Min, Op0Max);
6040       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6041                                              Op1Min, Op1Max);
6042     } else {
6043       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6044                                                Op0Min, Op0Max);
6045       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6046                                                Op1Min, Op1Max);
6047     }
6048
6049     // If Min and Max are known to be the same, then SimplifyDemandedBits
6050     // figured out that the LHS is a constant.  Just constant fold this now so
6051     // that code below can assume that Min != Max.
6052     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6053       return new ICmpInst(I.getPredicate(), ConstantInt::get(Op0Min), Op1);
6054     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6055       return new ICmpInst(I.getPredicate(), Op0, ConstantInt::get(Op1Min));
6056
6057     // Based on the range information we know about the LHS, see if we can
6058     // simplify this comparison.  For example, (x&4) < 8  is always true.
6059     switch (I.getPredicate()) {
6060     default: assert(0 && "Unknown icmp opcode!");
6061     case ICmpInst::ICMP_EQ:
6062       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6063         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6064       break;
6065     case ICmpInst::ICMP_NE:
6066       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6067         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6068       break;
6069     case ICmpInst::ICMP_ULT:
6070       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6071         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6072       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6073         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6074       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6075         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6076       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6077         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6078           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6079
6080         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6081         if (CI->isMinValue(true))
6082           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6083                             ConstantInt::getAllOnesValue(Op0->getType()));
6084       }
6085       break;
6086     case ICmpInst::ICMP_UGT:
6087       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6088         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6089       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6090         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6091
6092       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6093         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6094       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6095         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6096           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6097
6098         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6099         if (CI->isMaxValue(true))
6100           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6101                               ConstantInt::getNullValue(Op0->getType()));
6102       }
6103       break;
6104     case ICmpInst::ICMP_SLT:
6105       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6106         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6107       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6108         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6109       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6110         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6111       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6112         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6113           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6114       }
6115       break;
6116     case ICmpInst::ICMP_SGT:
6117       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6118         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6119       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6120         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6121
6122       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6123         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6124       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6125         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6126           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6127       }
6128       break;
6129     case ICmpInst::ICMP_SGE:
6130       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6131       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6132         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6133       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6134         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6135       break;
6136     case ICmpInst::ICMP_SLE:
6137       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6138       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6139         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6140       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6141         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6142       break;
6143     case ICmpInst::ICMP_UGE:
6144       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6145       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6146         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6147       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6148         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6149       break;
6150     case ICmpInst::ICMP_ULE:
6151       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6152       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6153         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6154       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6155         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6156       break;
6157     }
6158
6159     // Turn a signed comparison into an unsigned one if both operands
6160     // are known to have the same sign.
6161     if (I.isSignedPredicate() &&
6162         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6163          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6164       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6165   }
6166
6167   // Test if the ICmpInst instruction is used exclusively by a select as
6168   // part of a minimum or maximum operation. If so, refrain from doing
6169   // any other folding. This helps out other analyses which understand
6170   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6171   // and CodeGen. And in this case, at least one of the comparison
6172   // operands has at least one user besides the compare (the select),
6173   // which would often largely negate the benefit of folding anyway.
6174   if (I.hasOneUse())
6175     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6176       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6177           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6178         return 0;
6179
6180   // See if we are doing a comparison between a constant and an instruction that
6181   // can be folded into the comparison.
6182   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6183     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6184     // instruction, see if that instruction also has constants so that the 
6185     // instruction can be folded into the icmp 
6186     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6187       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6188         return Res;
6189   }
6190
6191   // Handle icmp with constant (but not simple integer constant) RHS
6192   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6193     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6194       switch (LHSI->getOpcode()) {
6195       case Instruction::GetElementPtr:
6196         if (RHSC->isNullValue()) {
6197           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6198           bool isAllZeros = true;
6199           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6200             if (!isa<Constant>(LHSI->getOperand(i)) ||
6201                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6202               isAllZeros = false;
6203               break;
6204             }
6205           if (isAllZeros)
6206             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6207                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6208         }
6209         break;
6210
6211       case Instruction::PHI:
6212         // Only fold icmp into the PHI if the phi and fcmp are in the same
6213         // block.  If in the same block, we're encouraging jump threading.  If
6214         // not, we are just pessimizing the code by making an i1 phi.
6215         if (LHSI->getParent() == I.getParent())
6216           if (Instruction *NV = FoldOpIntoPhi(I))
6217             return NV;
6218         break;
6219       case Instruction::Select: {
6220         // If either operand of the select is a constant, we can fold the
6221         // comparison into the select arms, which will cause one to be
6222         // constant folded and the select turned into a bitwise or.
6223         Value *Op1 = 0, *Op2 = 0;
6224         if (LHSI->hasOneUse()) {
6225           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6226             // Fold the known value into the constant operand.
6227             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6228             // Insert a new ICmp of the other select operand.
6229             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6230                                                    LHSI->getOperand(2), RHSC,
6231                                                    I.getName()), I);
6232           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6233             // Fold the known value into the constant operand.
6234             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6235             // Insert a new ICmp of the other select operand.
6236             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6237                                                    LHSI->getOperand(1), RHSC,
6238                                                    I.getName()), I);
6239           }
6240         }
6241
6242         if (Op1)
6243           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6244         break;
6245       }
6246       case Instruction::Malloc:
6247         // If we have (malloc != null), and if the malloc has a single use, we
6248         // can assume it is successful and remove the malloc.
6249         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6250           AddToWorkList(LHSI);
6251           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6252                                                          !I.isTrueWhenEqual()));
6253         }
6254         break;
6255       }
6256   }
6257
6258   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6259   if (User *GEP = dyn_castGetElementPtr(Op0))
6260     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6261       return NI;
6262   if (User *GEP = dyn_castGetElementPtr(Op1))
6263     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6264                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6265       return NI;
6266
6267   // Test to see if the operands of the icmp are casted versions of other
6268   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6269   // now.
6270   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6271     if (isa<PointerType>(Op0->getType()) && 
6272         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6273       // We keep moving the cast from the left operand over to the right
6274       // operand, where it can often be eliminated completely.
6275       Op0 = CI->getOperand(0);
6276
6277       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6278       // so eliminate it as well.
6279       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6280         Op1 = CI2->getOperand(0);
6281
6282       // If Op1 is a constant, we can fold the cast into the constant.
6283       if (Op0->getType() != Op1->getType()) {
6284         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6285           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6286         } else {
6287           // Otherwise, cast the RHS right before the icmp
6288           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6289         }
6290       }
6291       return new ICmpInst(I.getPredicate(), Op0, Op1);
6292     }
6293   }
6294   
6295   if (isa<CastInst>(Op0)) {
6296     // Handle the special case of: icmp (cast bool to X), <cst>
6297     // This comes up when you have code like
6298     //   int X = A < B;
6299     //   if (X) ...
6300     // For generality, we handle any zero-extension of any operand comparison
6301     // with a constant or another cast from the same type.
6302     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6303       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6304         return R;
6305   }
6306   
6307   // See if it's the same type of instruction on the left and right.
6308   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6309     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6310       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6311           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6312         switch (Op0I->getOpcode()) {
6313         default: break;
6314         case Instruction::Add:
6315         case Instruction::Sub:
6316         case Instruction::Xor:
6317           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6318             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6319                                 Op1I->getOperand(0));
6320           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6321           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6322             if (CI->getValue().isSignBit()) {
6323               ICmpInst::Predicate Pred = I.isSignedPredicate()
6324                                              ? I.getUnsignedPredicate()
6325                                              : I.getSignedPredicate();
6326               return new ICmpInst(Pred, Op0I->getOperand(0),
6327                                   Op1I->getOperand(0));
6328             }
6329             
6330             if (CI->getValue().isMaxSignedValue()) {
6331               ICmpInst::Predicate Pred = I.isSignedPredicate()
6332                                              ? I.getUnsignedPredicate()
6333                                              : I.getSignedPredicate();
6334               Pred = I.getSwappedPredicate(Pred);
6335               return new ICmpInst(Pred, Op0I->getOperand(0),
6336                                   Op1I->getOperand(0));
6337             }
6338           }
6339           break;
6340         case Instruction::Mul:
6341           if (!I.isEquality())
6342             break;
6343
6344           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6345             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6346             // Mask = -1 >> count-trailing-zeros(Cst).
6347             if (!CI->isZero() && !CI->isOne()) {
6348               const APInt &AP = CI->getValue();
6349               ConstantInt *Mask = ConstantInt::get(
6350                                       APInt::getLowBitsSet(AP.getBitWidth(),
6351                                                            AP.getBitWidth() -
6352                                                       AP.countTrailingZeros()));
6353               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6354                                                             Mask);
6355               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6356                                                             Mask);
6357               InsertNewInstBefore(And1, I);
6358               InsertNewInstBefore(And2, I);
6359               return new ICmpInst(I.getPredicate(), And1, And2);
6360             }
6361           }
6362           break;
6363         }
6364       }
6365     }
6366   }
6367   
6368   // ~x < ~y --> y < x
6369   { Value *A, *B;
6370     if (match(Op0, m_Not(m_Value(A))) &&
6371         match(Op1, m_Not(m_Value(B))))
6372       return new ICmpInst(I.getPredicate(), B, A);
6373   }
6374   
6375   if (I.isEquality()) {
6376     Value *A, *B, *C, *D;
6377     
6378     // -x == -y --> x == y
6379     if (match(Op0, m_Neg(m_Value(A))) &&
6380         match(Op1, m_Neg(m_Value(B))))
6381       return new ICmpInst(I.getPredicate(), A, B);
6382     
6383     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6384       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6385         Value *OtherVal = A == Op1 ? B : A;
6386         return new ICmpInst(I.getPredicate(), OtherVal,
6387                             Constant::getNullValue(A->getType()));
6388       }
6389
6390       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6391         // A^c1 == C^c2 --> A == C^(c1^c2)
6392         ConstantInt *C1, *C2;
6393         if (match(B, m_ConstantInt(C1)) &&
6394             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6395           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6396           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6397           return new ICmpInst(I.getPredicate(), A,
6398                               InsertNewInstBefore(Xor, I));
6399         }
6400         
6401         // A^B == A^D -> B == D
6402         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6403         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6404         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6405         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6406       }
6407     }
6408     
6409     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6410         (A == Op0 || B == Op0)) {
6411       // A == (A^B)  ->  B == 0
6412       Value *OtherVal = A == Op0 ? B : A;
6413       return new ICmpInst(I.getPredicate(), OtherVal,
6414                           Constant::getNullValue(A->getType()));
6415     }
6416
6417     // (A-B) == A  ->  B == 0
6418     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6419       return new ICmpInst(I.getPredicate(), B, 
6420                           Constant::getNullValue(B->getType()));
6421
6422     // A == (A-B)  ->  B == 0
6423     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6424       return new ICmpInst(I.getPredicate(), B,
6425                           Constant::getNullValue(B->getType()));
6426     
6427     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6428     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6429         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6430         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6431       Value *X = 0, *Y = 0, *Z = 0;
6432       
6433       if (A == C) {
6434         X = B; Y = D; Z = A;
6435       } else if (A == D) {
6436         X = B; Y = C; Z = A;
6437       } else if (B == C) {
6438         X = A; Y = D; Z = B;
6439       } else if (B == D) {
6440         X = A; Y = C; Z = B;
6441       }
6442       
6443       if (X) {   // Build (X^Y) & Z
6444         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6445         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6446         I.setOperand(0, Op1);
6447         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6448         return &I;
6449       }
6450     }
6451   }
6452   return Changed ? &I : 0;
6453 }
6454
6455
6456 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6457 /// and CmpRHS are both known to be integer constants.
6458 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6459                                           ConstantInt *DivRHS) {
6460   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6461   const APInt &CmpRHSV = CmpRHS->getValue();
6462   
6463   // FIXME: If the operand types don't match the type of the divide 
6464   // then don't attempt this transform. The code below doesn't have the
6465   // logic to deal with a signed divide and an unsigned compare (and
6466   // vice versa). This is because (x /s C1) <s C2  produces different 
6467   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6468   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6469   // work. :(  The if statement below tests that condition and bails 
6470   // if it finds it. 
6471   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6472   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6473     return 0;
6474   if (DivRHS->isZero())
6475     return 0; // The ProdOV computation fails on divide by zero.
6476   if (DivIsSigned && DivRHS->isAllOnesValue())
6477     return 0; // The overflow computation also screws up here
6478   if (DivRHS->isOne())
6479     return 0; // Not worth bothering, and eliminates some funny cases
6480               // with INT_MIN.
6481
6482   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6483   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6484   // C2 (CI). By solving for X we can turn this into a range check 
6485   // instead of computing a divide. 
6486   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6487
6488   // Determine if the product overflows by seeing if the product is
6489   // not equal to the divide. Make sure we do the same kind of divide
6490   // as in the LHS instruction that we're folding. 
6491   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6492                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6493
6494   // Get the ICmp opcode
6495   ICmpInst::Predicate Pred = ICI.getPredicate();
6496
6497   // Figure out the interval that is being checked.  For example, a comparison
6498   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6499   // Compute this interval based on the constants involved and the signedness of
6500   // the compare/divide.  This computes a half-open interval, keeping track of
6501   // whether either value in the interval overflows.  After analysis each
6502   // overflow variable is set to 0 if it's corresponding bound variable is valid
6503   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6504   int LoOverflow = 0, HiOverflow = 0;
6505   Constant *LoBound = 0, *HiBound = 0;
6506   
6507   if (!DivIsSigned) {  // udiv
6508     // e.g. X/5 op 3  --> [15, 20)
6509     LoBound = Prod;
6510     HiOverflow = LoOverflow = ProdOV;
6511     if (!HiOverflow)
6512       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6513   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6514     if (CmpRHSV == 0) {       // (X / pos) op 0
6515       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6516       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6517       HiBound = DivRHS;
6518     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6519       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6520       HiOverflow = LoOverflow = ProdOV;
6521       if (!HiOverflow)
6522         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6523     } else {                       // (X / pos) op neg
6524       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6525       HiBound = AddOne(Prod);
6526       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6527       if (!LoOverflow) {
6528         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6529         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6530                                      true) ? -1 : 0;
6531        }
6532     }
6533   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6534     if (CmpRHSV == 0) {       // (X / neg) op 0
6535       // e.g. X/-5 op 0  --> [-4, 5)
6536       LoBound = AddOne(DivRHS);
6537       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6538       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6539         HiOverflow = 1;            // [INTMIN+1, overflow)
6540         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6541       }
6542     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6543       // e.g. X/-5 op 3  --> [-19, -14)
6544       HiBound = AddOne(Prod);
6545       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6546       if (!LoOverflow)
6547         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6548     } else {                       // (X / neg) op neg
6549       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6550       LoOverflow = HiOverflow = ProdOV;
6551       if (!HiOverflow)
6552         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6553     }
6554     
6555     // Dividing by a negative swaps the condition.  LT <-> GT
6556     Pred = ICmpInst::getSwappedPredicate(Pred);
6557   }
6558
6559   Value *X = DivI->getOperand(0);
6560   switch (Pred) {
6561   default: assert(0 && "Unhandled icmp opcode!");
6562   case ICmpInst::ICMP_EQ:
6563     if (LoOverflow && HiOverflow)
6564       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6565     else if (HiOverflow)
6566       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6567                           ICmpInst::ICMP_UGE, X, LoBound);
6568     else if (LoOverflow)
6569       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6570                           ICmpInst::ICMP_ULT, X, HiBound);
6571     else
6572       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6573   case ICmpInst::ICMP_NE:
6574     if (LoOverflow && HiOverflow)
6575       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6576     else if (HiOverflow)
6577       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6578                           ICmpInst::ICMP_ULT, X, LoBound);
6579     else if (LoOverflow)
6580       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6581                           ICmpInst::ICMP_UGE, X, HiBound);
6582     else
6583       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6584   case ICmpInst::ICMP_ULT:
6585   case ICmpInst::ICMP_SLT:
6586     if (LoOverflow == +1)   // Low bound is greater than input range.
6587       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6588     if (LoOverflow == -1)   // Low bound is less than input range.
6589       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6590     return new ICmpInst(Pred, X, LoBound);
6591   case ICmpInst::ICMP_UGT:
6592   case ICmpInst::ICMP_SGT:
6593     if (HiOverflow == +1)       // High bound greater than input range.
6594       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6595     else if (HiOverflow == -1)  // High bound less than input range.
6596       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6597     if (Pred == ICmpInst::ICMP_UGT)
6598       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6599     else
6600       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6601   }
6602 }
6603
6604
6605 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6606 ///
6607 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6608                                                           Instruction *LHSI,
6609                                                           ConstantInt *RHS) {
6610   const APInt &RHSV = RHS->getValue();
6611   
6612   switch (LHSI->getOpcode()) {
6613   case Instruction::Trunc:
6614     if (ICI.isEquality() && LHSI->hasOneUse()) {
6615       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6616       // of the high bits truncated out of x are known.
6617       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6618              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6619       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6620       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6621       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6622       
6623       // If all the high bits are known, we can do this xform.
6624       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6625         // Pull in the high bits from known-ones set.
6626         APInt NewRHS(RHS->getValue());
6627         NewRHS.zext(SrcBits);
6628         NewRHS |= KnownOne;
6629         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6630                             ConstantInt::get(NewRHS));
6631       }
6632     }
6633     break;
6634       
6635   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6636     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6637       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6638       // fold the xor.
6639       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6640           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6641         Value *CompareVal = LHSI->getOperand(0);
6642         
6643         // If the sign bit of the XorCST is not set, there is no change to
6644         // the operation, just stop using the Xor.
6645         if (!XorCST->getValue().isNegative()) {
6646           ICI.setOperand(0, CompareVal);
6647           AddToWorkList(LHSI);
6648           return &ICI;
6649         }
6650         
6651         // Was the old condition true if the operand is positive?
6652         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6653         
6654         // If so, the new one isn't.
6655         isTrueIfPositive ^= true;
6656         
6657         if (isTrueIfPositive)
6658           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6659         else
6660           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6661       }
6662
6663       if (LHSI->hasOneUse()) {
6664         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6665         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6666           const APInt &SignBit = XorCST->getValue();
6667           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6668                                          ? ICI.getUnsignedPredicate()
6669                                          : ICI.getSignedPredicate();
6670           return new ICmpInst(Pred, LHSI->getOperand(0),
6671                               ConstantInt::get(RHSV ^ SignBit));
6672         }
6673
6674         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6675         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6676           const APInt &NotSignBit = XorCST->getValue();
6677           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6678                                          ? ICI.getUnsignedPredicate()
6679                                          : ICI.getSignedPredicate();
6680           Pred = ICI.getSwappedPredicate(Pred);
6681           return new ICmpInst(Pred, LHSI->getOperand(0),
6682                               ConstantInt::get(RHSV ^ NotSignBit));
6683         }
6684       }
6685     }
6686     break;
6687   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6688     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6689         LHSI->getOperand(0)->hasOneUse()) {
6690       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6691       
6692       // If the LHS is an AND of a truncating cast, we can widen the
6693       // and/compare to be the input width without changing the value
6694       // produced, eliminating a cast.
6695       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6696         // We can do this transformation if either the AND constant does not
6697         // have its sign bit set or if it is an equality comparison. 
6698         // Extending a relational comparison when we're checking the sign
6699         // bit would not work.
6700         if (Cast->hasOneUse() &&
6701             (ICI.isEquality() ||
6702              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6703           uint32_t BitWidth = 
6704             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6705           APInt NewCST = AndCST->getValue();
6706           NewCST.zext(BitWidth);
6707           APInt NewCI = RHSV;
6708           NewCI.zext(BitWidth);
6709           Instruction *NewAnd = 
6710             BinaryOperator::CreateAnd(Cast->getOperand(0),
6711                                       ConstantInt::get(NewCST),LHSI->getName());
6712           InsertNewInstBefore(NewAnd, ICI);
6713           return new ICmpInst(ICI.getPredicate(), NewAnd,
6714                               ConstantInt::get(NewCI));
6715         }
6716       }
6717       
6718       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6719       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6720       // happens a LOT in code produced by the C front-end, for bitfield
6721       // access.
6722       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6723       if (Shift && !Shift->isShift())
6724         Shift = 0;
6725       
6726       ConstantInt *ShAmt;
6727       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6728       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6729       const Type *AndTy = AndCST->getType();          // Type of the and.
6730       
6731       // We can fold this as long as we can't shift unknown bits
6732       // into the mask.  This can only happen with signed shift
6733       // rights, as they sign-extend.
6734       if (ShAmt) {
6735         bool CanFold = Shift->isLogicalShift();
6736         if (!CanFold) {
6737           // To test for the bad case of the signed shr, see if any
6738           // of the bits shifted in could be tested after the mask.
6739           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6740           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6741           
6742           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6743           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6744                AndCST->getValue()) == 0)
6745             CanFold = true;
6746         }
6747         
6748         if (CanFold) {
6749           Constant *NewCst;
6750           if (Shift->getOpcode() == Instruction::Shl)
6751             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6752           else
6753             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6754           
6755           // Check to see if we are shifting out any of the bits being
6756           // compared.
6757           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6758             // If we shifted bits out, the fold is not going to work out.
6759             // As a special case, check to see if this means that the
6760             // result is always true or false now.
6761             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6762               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6763             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6764               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6765           } else {
6766             ICI.setOperand(1, NewCst);
6767             Constant *NewAndCST;
6768             if (Shift->getOpcode() == Instruction::Shl)
6769               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6770             else
6771               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6772             LHSI->setOperand(1, NewAndCST);
6773             LHSI->setOperand(0, Shift->getOperand(0));
6774             AddToWorkList(Shift); // Shift is dead.
6775             AddUsesToWorkList(ICI);
6776             return &ICI;
6777           }
6778         }
6779       }
6780       
6781       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6782       // preferable because it allows the C<<Y expression to be hoisted out
6783       // of a loop if Y is invariant and X is not.
6784       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6785           ICI.isEquality() && !Shift->isArithmeticShift() &&
6786           !isa<Constant>(Shift->getOperand(0))) {
6787         // Compute C << Y.
6788         Value *NS;
6789         if (Shift->getOpcode() == Instruction::LShr) {
6790           NS = BinaryOperator::CreateShl(AndCST, 
6791                                          Shift->getOperand(1), "tmp");
6792         } else {
6793           // Insert a logical shift.
6794           NS = BinaryOperator::CreateLShr(AndCST,
6795                                           Shift->getOperand(1), "tmp");
6796         }
6797         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6798         
6799         // Compute X & (C << Y).
6800         Instruction *NewAnd = 
6801           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6802         InsertNewInstBefore(NewAnd, ICI);
6803         
6804         ICI.setOperand(0, NewAnd);
6805         return &ICI;
6806       }
6807     }
6808     break;
6809     
6810   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6811     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6812     if (!ShAmt) break;
6813     
6814     uint32_t TypeBits = RHSV.getBitWidth();
6815     
6816     // Check that the shift amount is in range.  If not, don't perform
6817     // undefined shifts.  When the shift is visited it will be
6818     // simplified.
6819     if (ShAmt->uge(TypeBits))
6820       break;
6821     
6822     if (ICI.isEquality()) {
6823       // If we are comparing against bits always shifted out, the
6824       // comparison cannot succeed.
6825       Constant *Comp =
6826         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6827       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6828         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6829         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6830         return ReplaceInstUsesWith(ICI, Cst);
6831       }
6832       
6833       if (LHSI->hasOneUse()) {
6834         // Otherwise strength reduce the shift into an and.
6835         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6836         Constant *Mask =
6837           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6838         
6839         Instruction *AndI =
6840           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6841                                     Mask, LHSI->getName()+".mask");
6842         Value *And = InsertNewInstBefore(AndI, ICI);
6843         return new ICmpInst(ICI.getPredicate(), And,
6844                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6845       }
6846     }
6847     
6848     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6849     bool TrueIfSigned = false;
6850     if (LHSI->hasOneUse() &&
6851         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6852       // (X << 31) <s 0  --> (X&1) != 0
6853       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6854                                            (TypeBits-ShAmt->getZExtValue()-1));
6855       Instruction *AndI =
6856         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6857                                   Mask, LHSI->getName()+".mask");
6858       Value *And = InsertNewInstBefore(AndI, ICI);
6859       
6860       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6861                           And, Constant::getNullValue(And->getType()));
6862     }
6863     break;
6864   }
6865     
6866   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6867   case Instruction::AShr: {
6868     // Only handle equality comparisons of shift-by-constant.
6869     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6870     if (!ShAmt || !ICI.isEquality()) break;
6871
6872     // Check that the shift amount is in range.  If not, don't perform
6873     // undefined shifts.  When the shift is visited it will be
6874     // simplified.
6875     uint32_t TypeBits = RHSV.getBitWidth();
6876     if (ShAmt->uge(TypeBits))
6877       break;
6878     
6879     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6880       
6881     // If we are comparing against bits always shifted out, the
6882     // comparison cannot succeed.
6883     APInt Comp = RHSV << ShAmtVal;
6884     if (LHSI->getOpcode() == Instruction::LShr)
6885       Comp = Comp.lshr(ShAmtVal);
6886     else
6887       Comp = Comp.ashr(ShAmtVal);
6888     
6889     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6890       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6891       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6892       return ReplaceInstUsesWith(ICI, Cst);
6893     }
6894     
6895     // Otherwise, check to see if the bits shifted out are known to be zero.
6896     // If so, we can compare against the unshifted value:
6897     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6898     if (LHSI->hasOneUse() &&
6899         MaskedValueIsZero(LHSI->getOperand(0), 
6900                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6901       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6902                           ConstantExpr::getShl(RHS, ShAmt));
6903     }
6904       
6905     if (LHSI->hasOneUse()) {
6906       // Otherwise strength reduce the shift into an and.
6907       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6908       Constant *Mask = ConstantInt::get(Val);
6909       
6910       Instruction *AndI =
6911         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6912                                   Mask, LHSI->getName()+".mask");
6913       Value *And = InsertNewInstBefore(AndI, ICI);
6914       return new ICmpInst(ICI.getPredicate(), And,
6915                           ConstantExpr::getShl(RHS, ShAmt));
6916     }
6917     break;
6918   }
6919     
6920   case Instruction::SDiv:
6921   case Instruction::UDiv:
6922     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6923     // Fold this div into the comparison, producing a range check. 
6924     // Determine, based on the divide type, what the range is being 
6925     // checked.  If there is an overflow on the low or high side, remember 
6926     // it, otherwise compute the range [low, hi) bounding the new value.
6927     // See: InsertRangeTest above for the kinds of replacements possible.
6928     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6929       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6930                                           DivRHS))
6931         return R;
6932     break;
6933
6934   case Instruction::Add:
6935     // Fold: icmp pred (add, X, C1), C2
6936
6937     if (!ICI.isEquality()) {
6938       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6939       if (!LHSC) break;
6940       const APInt &LHSV = LHSC->getValue();
6941
6942       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6943                             .subtract(LHSV);
6944
6945       if (ICI.isSignedPredicate()) {
6946         if (CR.getLower().isSignBit()) {
6947           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6948                               ConstantInt::get(CR.getUpper()));
6949         } else if (CR.getUpper().isSignBit()) {
6950           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6951                               ConstantInt::get(CR.getLower()));
6952         }
6953       } else {
6954         if (CR.getLower().isMinValue()) {
6955           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6956                               ConstantInt::get(CR.getUpper()));
6957         } else if (CR.getUpper().isMinValue()) {
6958           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6959                               ConstantInt::get(CR.getLower()));
6960         }
6961       }
6962     }
6963     break;
6964   }
6965   
6966   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6967   if (ICI.isEquality()) {
6968     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6969     
6970     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6971     // the second operand is a constant, simplify a bit.
6972     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6973       switch (BO->getOpcode()) {
6974       case Instruction::SRem:
6975         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6976         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6977           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6978           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6979             Instruction *NewRem =
6980               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6981                                          BO->getName());
6982             InsertNewInstBefore(NewRem, ICI);
6983             return new ICmpInst(ICI.getPredicate(), NewRem, 
6984                                 Constant::getNullValue(BO->getType()));
6985           }
6986         }
6987         break;
6988       case Instruction::Add:
6989         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6990         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6991           if (BO->hasOneUse())
6992             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6993                                 ConstantExpr::getSub(RHS, BOp1C));
6994         } else if (RHSV == 0) {
6995           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6996           // efficiently invertible, or if the add has just this one use.
6997           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6998           
6999           if (Value *NegVal = dyn_castNegVal(BOp1))
7000             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7001           else if (Value *NegVal = dyn_castNegVal(BOp0))
7002             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7003           else if (BO->hasOneUse()) {
7004             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
7005             InsertNewInstBefore(Neg, ICI);
7006             Neg->takeName(BO);
7007             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7008           }
7009         }
7010         break;
7011       case Instruction::Xor:
7012         // For the xor case, we can xor two constants together, eliminating
7013         // the explicit xor.
7014         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7015           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7016                               ConstantExpr::getXor(RHS, BOC));
7017         
7018         // FALLTHROUGH
7019       case Instruction::Sub:
7020         // Replace (([sub|xor] A, B) != 0) with (A != B)
7021         if (RHSV == 0)
7022           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7023                               BO->getOperand(1));
7024         break;
7025         
7026       case Instruction::Or:
7027         // If bits are being or'd in that are not present in the constant we
7028         // are comparing against, then the comparison could never succeed!
7029         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7030           Constant *NotCI = ConstantExpr::getNot(RHS);
7031           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7032             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
7033                                                              isICMP_NE));
7034         }
7035         break;
7036         
7037       case Instruction::And:
7038         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7039           // If bits are being compared against that are and'd out, then the
7040           // comparison can never succeed!
7041           if ((RHSV & ~BOC->getValue()) != 0)
7042             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
7043                                                              isICMP_NE));
7044           
7045           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7046           if (RHS == BOC && RHSV.isPowerOf2())
7047             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7048                                 ICmpInst::ICMP_NE, LHSI,
7049                                 Constant::getNullValue(RHS->getType()));
7050           
7051           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7052           if (BOC->getValue().isSignBit()) {
7053             Value *X = BO->getOperand(0);
7054             Constant *Zero = Constant::getNullValue(X->getType());
7055             ICmpInst::Predicate pred = isICMP_NE ? 
7056               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7057             return new ICmpInst(pred, X, Zero);
7058           }
7059           
7060           // ((X & ~7) == 0) --> X < 8
7061           if (RHSV == 0 && isHighOnes(BOC)) {
7062             Value *X = BO->getOperand(0);
7063             Constant *NegX = ConstantExpr::getNeg(BOC);
7064             ICmpInst::Predicate pred = isICMP_NE ? 
7065               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7066             return new ICmpInst(pred, X, NegX);
7067           }
7068         }
7069       default: break;
7070       }
7071     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7072       // Handle icmp {eq|ne} <intrinsic>, intcst.
7073       if (II->getIntrinsicID() == Intrinsic::bswap) {
7074         AddToWorkList(II);
7075         ICI.setOperand(0, II->getOperand(1));
7076         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
7077         return &ICI;
7078       }
7079     }
7080   }
7081   return 0;
7082 }
7083
7084 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7085 /// We only handle extending casts so far.
7086 ///
7087 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7088   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7089   Value *LHSCIOp        = LHSCI->getOperand(0);
7090   const Type *SrcTy     = LHSCIOp->getType();
7091   const Type *DestTy    = LHSCI->getType();
7092   Value *RHSCIOp;
7093
7094   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7095   // integer type is the same size as the pointer type.
7096   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7097       getTargetData().getPointerSizeInBits() == 
7098          cast<IntegerType>(DestTy)->getBitWidth()) {
7099     Value *RHSOp = 0;
7100     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7101       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7102     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7103       RHSOp = RHSC->getOperand(0);
7104       // If the pointer types don't match, insert a bitcast.
7105       if (LHSCIOp->getType() != RHSOp->getType())
7106         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7107     }
7108
7109     if (RHSOp)
7110       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7111   }
7112   
7113   // The code below only handles extension cast instructions, so far.
7114   // Enforce this.
7115   if (LHSCI->getOpcode() != Instruction::ZExt &&
7116       LHSCI->getOpcode() != Instruction::SExt)
7117     return 0;
7118
7119   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7120   bool isSignedCmp = ICI.isSignedPredicate();
7121
7122   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7123     // Not an extension from the same type?
7124     RHSCIOp = CI->getOperand(0);
7125     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7126       return 0;
7127     
7128     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7129     // and the other is a zext), then we can't handle this.
7130     if (CI->getOpcode() != LHSCI->getOpcode())
7131       return 0;
7132
7133     // Deal with equality cases early.
7134     if (ICI.isEquality())
7135       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7136
7137     // A signed comparison of sign extended values simplifies into a
7138     // signed comparison.
7139     if (isSignedCmp && isSignedExt)
7140       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7141
7142     // The other three cases all fold into an unsigned comparison.
7143     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7144   }
7145
7146   // If we aren't dealing with a constant on the RHS, exit early
7147   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7148   if (!CI)
7149     return 0;
7150
7151   // Compute the constant that would happen if we truncated to SrcTy then
7152   // reextended to DestTy.
7153   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7154   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
7155
7156   // If the re-extended constant didn't change...
7157   if (Res2 == CI) {
7158     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7159     // For example, we might have:
7160     //    %A = sext i16 %X to i32
7161     //    %B = icmp ugt i32 %A, 1330
7162     // It is incorrect to transform this into 
7163     //    %B = icmp ugt i16 %X, 1330
7164     // because %A may have negative value. 
7165     //
7166     // However, we allow this when the compare is EQ/NE, because they are
7167     // signless.
7168     if (isSignedExt == isSignedCmp || ICI.isEquality())
7169       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7170     return 0;
7171   }
7172
7173   // The re-extended constant changed so the constant cannot be represented 
7174   // in the shorter type. Consequently, we cannot emit a simple comparison.
7175
7176   // First, handle some easy cases. We know the result cannot be equal at this
7177   // point so handle the ICI.isEquality() cases
7178   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7179     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
7180   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7181     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
7182
7183   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7184   // should have been folded away previously and not enter in here.
7185   Value *Result;
7186   if (isSignedCmp) {
7187     // We're performing a signed comparison.
7188     if (cast<ConstantInt>(CI)->getValue().isNegative())
7189       Result = ConstantInt::getFalse();          // X < (small) --> false
7190     else
7191       Result = ConstantInt::getTrue();           // X < (large) --> true
7192   } else {
7193     // We're performing an unsigned comparison.
7194     if (isSignedExt) {
7195       // We're performing an unsigned comp with a sign extended value.
7196       // This is true if the input is >= 0. [aka >s -1]
7197       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
7198       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
7199                                    NegOne, ICI.getName()), ICI);
7200     } else {
7201       // Unsigned extend & unsigned compare -> always true.
7202       Result = ConstantInt::getTrue();
7203     }
7204   }
7205
7206   // Finally, return the value computed.
7207   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7208       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7209     return ReplaceInstUsesWith(ICI, Result);
7210
7211   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7212           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7213          "ICmp should be folded!");
7214   if (Constant *CI = dyn_cast<Constant>(Result))
7215     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7216   return BinaryOperator::CreateNot(Result);
7217 }
7218
7219 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7220   return commonShiftTransforms(I);
7221 }
7222
7223 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7224   return commonShiftTransforms(I);
7225 }
7226
7227 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7228   if (Instruction *R = commonShiftTransforms(I))
7229     return R;
7230   
7231   Value *Op0 = I.getOperand(0);
7232   
7233   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7234   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7235     if (CSI->isAllOnesValue())
7236       return ReplaceInstUsesWith(I, CSI);
7237
7238   // See if we can turn a signed shr into an unsigned shr.
7239   if (MaskedValueIsZero(Op0,
7240                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7241     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7242
7243   // Arithmetic shifting an all-sign-bit value is a no-op.
7244   unsigned NumSignBits = ComputeNumSignBits(Op0);
7245   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7246     return ReplaceInstUsesWith(I, Op0);
7247
7248   return 0;
7249 }
7250
7251 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7252   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7253   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7254
7255   // shl X, 0 == X and shr X, 0 == X
7256   // shl 0, X == 0 and shr 0, X == 0
7257   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7258       Op0 == Constant::getNullValue(Op0->getType()))
7259     return ReplaceInstUsesWith(I, Op0);
7260   
7261   if (isa<UndefValue>(Op0)) {            
7262     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7263       return ReplaceInstUsesWith(I, Op0);
7264     else                                    // undef << X -> 0, undef >>u X -> 0
7265       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7266   }
7267   if (isa<UndefValue>(Op1)) {
7268     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7269       return ReplaceInstUsesWith(I, Op0);          
7270     else                                     // X << undef, X >>u undef -> 0
7271       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7272   }
7273
7274   // See if we can fold away this shift.
7275   if (SimplifyDemandedInstructionBits(I))
7276     return &I;
7277
7278   // Try to fold constant and into select arguments.
7279   if (isa<Constant>(Op0))
7280     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7281       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7282         return R;
7283
7284   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7285     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7286       return Res;
7287   return 0;
7288 }
7289
7290 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7291                                                BinaryOperator &I) {
7292   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7293
7294   // See if we can simplify any instructions used by the instruction whose sole 
7295   // purpose is to compute bits we don't care about.
7296   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7297   
7298   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7299   // a signed shift.
7300   //
7301   if (Op1->uge(TypeBits)) {
7302     if (I.getOpcode() != Instruction::AShr)
7303       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7304     else {
7305       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7306       return &I;
7307     }
7308   }
7309   
7310   // ((X*C1) << C2) == (X * (C1 << C2))
7311   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7312     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7313       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7314         return BinaryOperator::CreateMul(BO->getOperand(0),
7315                                          ConstantExpr::getShl(BOOp, Op1));
7316   
7317   // Try to fold constant and into select arguments.
7318   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7319     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7320       return R;
7321   if (isa<PHINode>(Op0))
7322     if (Instruction *NV = FoldOpIntoPhi(I))
7323       return NV;
7324   
7325   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7326   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7327     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7328     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7329     // place.  Don't try to do this transformation in this case.  Also, we
7330     // require that the input operand is a shift-by-constant so that we have
7331     // confidence that the shifts will get folded together.  We could do this
7332     // xform in more cases, but it is unlikely to be profitable.
7333     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7334         isa<ConstantInt>(TrOp->getOperand(1))) {
7335       // Okay, we'll do this xform.  Make the shift of shift.
7336       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7337       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7338                                                 I.getName());
7339       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7340
7341       // For logical shifts, the truncation has the effect of making the high
7342       // part of the register be zeros.  Emulate this by inserting an AND to
7343       // clear the top bits as needed.  This 'and' will usually be zapped by
7344       // other xforms later if dead.
7345       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7346       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7347       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7348       
7349       // The mask we constructed says what the trunc would do if occurring
7350       // between the shifts.  We want to know the effect *after* the second
7351       // shift.  We know that it is a logical shift by a constant, so adjust the
7352       // mask as appropriate.
7353       if (I.getOpcode() == Instruction::Shl)
7354         MaskV <<= Op1->getZExtValue();
7355       else {
7356         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7357         MaskV = MaskV.lshr(Op1->getZExtValue());
7358       }
7359
7360       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7361                                                    TI->getName());
7362       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7363
7364       // Return the value truncated to the interesting size.
7365       return new TruncInst(And, I.getType());
7366     }
7367   }
7368   
7369   if (Op0->hasOneUse()) {
7370     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7371       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7372       Value *V1, *V2;
7373       ConstantInt *CC;
7374       switch (Op0BO->getOpcode()) {
7375         default: break;
7376         case Instruction::Add:
7377         case Instruction::And:
7378         case Instruction::Or:
7379         case Instruction::Xor: {
7380           // These operators commute.
7381           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7382           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7383               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7384             Instruction *YS = BinaryOperator::CreateShl(
7385                                             Op0BO->getOperand(0), Op1,
7386                                             Op0BO->getName());
7387             InsertNewInstBefore(YS, I); // (Y << C)
7388             Instruction *X = 
7389               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7390                                      Op0BO->getOperand(1)->getName());
7391             InsertNewInstBefore(X, I);  // (X + (Y << C))
7392             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7393             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7394                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7395           }
7396           
7397           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7398           Value *Op0BOOp1 = Op0BO->getOperand(1);
7399           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7400               match(Op0BOOp1, 
7401                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7402                           m_ConstantInt(CC))) &&
7403               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7404             Instruction *YS = BinaryOperator::CreateShl(
7405                                                      Op0BO->getOperand(0), Op1,
7406                                                      Op0BO->getName());
7407             InsertNewInstBefore(YS, I); // (Y << C)
7408             Instruction *XM =
7409               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7410                                         V1->getName()+".mask");
7411             InsertNewInstBefore(XM, I); // X & (CC << C)
7412             
7413             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7414           }
7415         }
7416           
7417         // FALL THROUGH.
7418         case Instruction::Sub: {
7419           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7420           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7421               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7422             Instruction *YS = BinaryOperator::CreateShl(
7423                                                      Op0BO->getOperand(1), Op1,
7424                                                      Op0BO->getName());
7425             InsertNewInstBefore(YS, I); // (Y << C)
7426             Instruction *X =
7427               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7428                                      Op0BO->getOperand(0)->getName());
7429             InsertNewInstBefore(X, I);  // (X + (Y << C))
7430             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7431             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7432                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7433           }
7434           
7435           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7436           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7437               match(Op0BO->getOperand(0),
7438                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7439                           m_ConstantInt(CC))) && V2 == Op1 &&
7440               cast<BinaryOperator>(Op0BO->getOperand(0))
7441                   ->getOperand(0)->hasOneUse()) {
7442             Instruction *YS = BinaryOperator::CreateShl(
7443                                                      Op0BO->getOperand(1), Op1,
7444                                                      Op0BO->getName());
7445             InsertNewInstBefore(YS, I); // (Y << C)
7446             Instruction *XM =
7447               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7448                                         V1->getName()+".mask");
7449             InsertNewInstBefore(XM, I); // X & (CC << C)
7450             
7451             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7452           }
7453           
7454           break;
7455         }
7456       }
7457       
7458       
7459       // If the operand is an bitwise operator with a constant RHS, and the
7460       // shift is the only use, we can pull it out of the shift.
7461       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7462         bool isValid = true;     // Valid only for And, Or, Xor
7463         bool highBitSet = false; // Transform if high bit of constant set?
7464         
7465         switch (Op0BO->getOpcode()) {
7466           default: isValid = false; break;   // Do not perform transform!
7467           case Instruction::Add:
7468             isValid = isLeftShift;
7469             break;
7470           case Instruction::Or:
7471           case Instruction::Xor:
7472             highBitSet = false;
7473             break;
7474           case Instruction::And:
7475             highBitSet = true;
7476             break;
7477         }
7478         
7479         // If this is a signed shift right, and the high bit is modified
7480         // by the logical operation, do not perform the transformation.
7481         // The highBitSet boolean indicates the value of the high bit of
7482         // the constant which would cause it to be modified for this
7483         // operation.
7484         //
7485         if (isValid && I.getOpcode() == Instruction::AShr)
7486           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7487         
7488         if (isValid) {
7489           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7490           
7491           Instruction *NewShift =
7492             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7493           InsertNewInstBefore(NewShift, I);
7494           NewShift->takeName(Op0BO);
7495           
7496           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7497                                         NewRHS);
7498         }
7499       }
7500     }
7501   }
7502   
7503   // Find out if this is a shift of a shift by a constant.
7504   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7505   if (ShiftOp && !ShiftOp->isShift())
7506     ShiftOp = 0;
7507   
7508   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7509     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7510     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7511     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7512     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7513     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7514     Value *X = ShiftOp->getOperand(0);
7515     
7516     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7517     
7518     const IntegerType *Ty = cast<IntegerType>(I.getType());
7519     
7520     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7521     if (I.getOpcode() == ShiftOp->getOpcode()) {
7522       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7523       // saturates.
7524       if (AmtSum >= TypeBits) {
7525         if (I.getOpcode() != Instruction::AShr)
7526           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7527         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7528       }
7529       
7530       return BinaryOperator::Create(I.getOpcode(), X,
7531                                     ConstantInt::get(Ty, AmtSum));
7532     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7533                I.getOpcode() == Instruction::AShr) {
7534       if (AmtSum >= TypeBits)
7535         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7536       
7537       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7538       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7539     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7540                I.getOpcode() == Instruction::LShr) {
7541       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7542       if (AmtSum >= TypeBits)
7543         AmtSum = TypeBits-1;
7544       
7545       Instruction *Shift =
7546         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7547       InsertNewInstBefore(Shift, I);
7548
7549       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7550       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7551     }
7552     
7553     // Okay, if we get here, one shift must be left, and the other shift must be
7554     // right.  See if the amounts are equal.
7555     if (ShiftAmt1 == ShiftAmt2) {
7556       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7557       if (I.getOpcode() == Instruction::Shl) {
7558         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7559         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7560       }
7561       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7562       if (I.getOpcode() == Instruction::LShr) {
7563         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7564         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7565       }
7566       // We can simplify ((X << C) >>s C) into a trunc + sext.
7567       // NOTE: we could do this for any C, but that would make 'unusual' integer
7568       // types.  For now, just stick to ones well-supported by the code
7569       // generators.
7570       const Type *SExtType = 0;
7571       switch (Ty->getBitWidth() - ShiftAmt1) {
7572       case 1  :
7573       case 8  :
7574       case 16 :
7575       case 32 :
7576       case 64 :
7577       case 128:
7578         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7579         break;
7580       default: break;
7581       }
7582       if (SExtType) {
7583         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7584         InsertNewInstBefore(NewTrunc, I);
7585         return new SExtInst(NewTrunc, Ty);
7586       }
7587       // Otherwise, we can't handle it yet.
7588     } else if (ShiftAmt1 < ShiftAmt2) {
7589       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7590       
7591       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7592       if (I.getOpcode() == Instruction::Shl) {
7593         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7594                ShiftOp->getOpcode() == Instruction::AShr);
7595         Instruction *Shift =
7596           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7597         InsertNewInstBefore(Shift, I);
7598         
7599         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7600         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7601       }
7602       
7603       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7604       if (I.getOpcode() == Instruction::LShr) {
7605         assert(ShiftOp->getOpcode() == Instruction::Shl);
7606         Instruction *Shift =
7607           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7608         InsertNewInstBefore(Shift, I);
7609         
7610         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7611         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7612       }
7613       
7614       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7615     } else {
7616       assert(ShiftAmt2 < ShiftAmt1);
7617       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7618
7619       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7620       if (I.getOpcode() == Instruction::Shl) {
7621         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7622                ShiftOp->getOpcode() == Instruction::AShr);
7623         Instruction *Shift =
7624           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7625                                  ConstantInt::get(Ty, ShiftDiff));
7626         InsertNewInstBefore(Shift, I);
7627         
7628         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7629         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7630       }
7631       
7632       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7633       if (I.getOpcode() == Instruction::LShr) {
7634         assert(ShiftOp->getOpcode() == Instruction::Shl);
7635         Instruction *Shift =
7636           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7637         InsertNewInstBefore(Shift, I);
7638         
7639         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7640         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7641       }
7642       
7643       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7644     }
7645   }
7646   return 0;
7647 }
7648
7649
7650 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7651 /// expression.  If so, decompose it, returning some value X, such that Val is
7652 /// X*Scale+Offset.
7653 ///
7654 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7655                                         int &Offset) {
7656   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7657   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7658     Offset = CI->getZExtValue();
7659     Scale  = 0;
7660     return ConstantInt::get(Type::Int32Ty, 0);
7661   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7662     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7663       if (I->getOpcode() == Instruction::Shl) {
7664         // This is a value scaled by '1 << the shift amt'.
7665         Scale = 1U << RHS->getZExtValue();
7666         Offset = 0;
7667         return I->getOperand(0);
7668       } else if (I->getOpcode() == Instruction::Mul) {
7669         // This value is scaled by 'RHS'.
7670         Scale = RHS->getZExtValue();
7671         Offset = 0;
7672         return I->getOperand(0);
7673       } else if (I->getOpcode() == Instruction::Add) {
7674         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7675         // where C1 is divisible by C2.
7676         unsigned SubScale;
7677         Value *SubVal = 
7678           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7679         Offset += RHS->getZExtValue();
7680         Scale = SubScale;
7681         return SubVal;
7682       }
7683     }
7684   }
7685
7686   // Otherwise, we can't look past this.
7687   Scale = 1;
7688   Offset = 0;
7689   return Val;
7690 }
7691
7692
7693 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7694 /// try to eliminate the cast by moving the type information into the alloc.
7695 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7696                                                    AllocationInst &AI) {
7697   const PointerType *PTy = cast<PointerType>(CI.getType());
7698   
7699   // Remove any uses of AI that are dead.
7700   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7701   
7702   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7703     Instruction *User = cast<Instruction>(*UI++);
7704     if (isInstructionTriviallyDead(User)) {
7705       while (UI != E && *UI == User)
7706         ++UI; // If this instruction uses AI more than once, don't break UI.
7707       
7708       ++NumDeadInst;
7709       DOUT << "IC: DCE: " << *User;
7710       EraseInstFromFunction(*User);
7711     }
7712   }
7713   
7714   // Get the type really allocated and the type casted to.
7715   const Type *AllocElTy = AI.getAllocatedType();
7716   const Type *CastElTy = PTy->getElementType();
7717   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7718
7719   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7720   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7721   if (CastElTyAlign < AllocElTyAlign) return 0;
7722
7723   // If the allocation has multiple uses, only promote it if we are strictly
7724   // increasing the alignment of the resultant allocation.  If we keep it the
7725   // same, we open the door to infinite loops of various kinds.  (A reference
7726   // from a dbg.declare doesn't count as a use for this purpose.)
7727   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7728       CastElTyAlign == AllocElTyAlign) return 0;
7729
7730   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7731   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7732   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7733
7734   // See if we can satisfy the modulus by pulling a scale out of the array
7735   // size argument.
7736   unsigned ArraySizeScale;
7737   int ArrayOffset;
7738   Value *NumElements = // See if the array size is a decomposable linear expr.
7739     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7740  
7741   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7742   // do the xform.
7743   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7744       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7745
7746   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7747   Value *Amt = 0;
7748   if (Scale == 1) {
7749     Amt = NumElements;
7750   } else {
7751     // If the allocation size is constant, form a constant mul expression
7752     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7753     if (isa<ConstantInt>(NumElements))
7754       Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
7755                                  cast<ConstantInt>(Amt));
7756     // otherwise multiply the amount and the number of elements
7757     else {
7758       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7759       Amt = InsertNewInstBefore(Tmp, AI);
7760     }
7761   }
7762   
7763   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7764     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7765     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7766     Amt = InsertNewInstBefore(Tmp, AI);
7767   }
7768   
7769   AllocationInst *New;
7770   if (isa<MallocInst>(AI))
7771     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7772   else
7773     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7774   InsertNewInstBefore(New, AI);
7775   New->takeName(&AI);
7776   
7777   // If the allocation has one real use plus a dbg.declare, just remove the
7778   // declare.
7779   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7780     EraseInstFromFunction(*DI);
7781   }
7782   // If the allocation has multiple real uses, insert a cast and change all
7783   // things that used it to use the new cast.  This will also hack on CI, but it
7784   // will die soon.
7785   else if (!AI.hasOneUse()) {
7786     AddUsesToWorkList(AI);
7787     // New is the allocation instruction, pointer typed. AI is the original
7788     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7789     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7790     InsertNewInstBefore(NewCast, AI);
7791     AI.replaceAllUsesWith(NewCast);
7792   }
7793   return ReplaceInstUsesWith(CI, New);
7794 }
7795
7796 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7797 /// and return it as type Ty without inserting any new casts and without
7798 /// changing the computed value.  This is used by code that tries to decide
7799 /// whether promoting or shrinking integer operations to wider or smaller types
7800 /// will allow us to eliminate a truncate or extend.
7801 ///
7802 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7803 /// extension operation if Ty is larger.
7804 ///
7805 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7806 /// should return true if trunc(V) can be computed by computing V in the smaller
7807 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7808 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7809 /// efficiently truncated.
7810 ///
7811 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7812 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7813 /// the final result.
7814 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7815                                               unsigned CastOpc,
7816                                               int &NumCastsRemoved){
7817   // We can always evaluate constants in another type.
7818   if (isa<Constant>(V))
7819     return true;
7820   
7821   Instruction *I = dyn_cast<Instruction>(V);
7822   if (!I) return false;
7823   
7824   const Type *OrigTy = V->getType();
7825   
7826   // If this is an extension or truncate, we can often eliminate it.
7827   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7828     // If this is a cast from the destination type, we can trivially eliminate
7829     // it, and this will remove a cast overall.
7830     if (I->getOperand(0)->getType() == Ty) {
7831       // If the first operand is itself a cast, and is eliminable, do not count
7832       // this as an eliminable cast.  We would prefer to eliminate those two
7833       // casts first.
7834       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7835         ++NumCastsRemoved;
7836       return true;
7837     }
7838   }
7839
7840   // We can't extend or shrink something that has multiple uses: doing so would
7841   // require duplicating the instruction in general, which isn't profitable.
7842   if (!I->hasOneUse()) return false;
7843
7844   unsigned Opc = I->getOpcode();
7845   switch (Opc) {
7846   case Instruction::Add:
7847   case Instruction::Sub:
7848   case Instruction::Mul:
7849   case Instruction::And:
7850   case Instruction::Or:
7851   case Instruction::Xor:
7852     // These operators can all arbitrarily be extended or truncated.
7853     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7854                                       NumCastsRemoved) &&
7855            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7856                                       NumCastsRemoved);
7857
7858   case Instruction::Shl:
7859     // If we are truncating the result of this SHL, and if it's a shift of a
7860     // constant amount, we can always perform a SHL in a smaller type.
7861     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7862       uint32_t BitWidth = Ty->getScalarSizeInBits();
7863       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7864           CI->getLimitedValue(BitWidth) < BitWidth)
7865         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7866                                           NumCastsRemoved);
7867     }
7868     break;
7869   case Instruction::LShr:
7870     // If this is a truncate of a logical shr, we can truncate it to a smaller
7871     // lshr iff we know that the bits we would otherwise be shifting in are
7872     // already zeros.
7873     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7874       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7875       uint32_t BitWidth = Ty->getScalarSizeInBits();
7876       if (BitWidth < OrigBitWidth &&
7877           MaskedValueIsZero(I->getOperand(0),
7878             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7879           CI->getLimitedValue(BitWidth) < BitWidth) {
7880         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7881                                           NumCastsRemoved);
7882       }
7883     }
7884     break;
7885   case Instruction::ZExt:
7886   case Instruction::SExt:
7887   case Instruction::Trunc:
7888     // If this is the same kind of case as our original (e.g. zext+zext), we
7889     // can safely replace it.  Note that replacing it does not reduce the number
7890     // of casts in the input.
7891     if (Opc == CastOpc)
7892       return true;
7893
7894     // sext (zext ty1), ty2 -> zext ty2
7895     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7896       return true;
7897     break;
7898   case Instruction::Select: {
7899     SelectInst *SI = cast<SelectInst>(I);
7900     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7901                                       NumCastsRemoved) &&
7902            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7903                                       NumCastsRemoved);
7904   }
7905   case Instruction::PHI: {
7906     // We can change a phi if we can change all operands.
7907     PHINode *PN = cast<PHINode>(I);
7908     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7909       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7910                                       NumCastsRemoved))
7911         return false;
7912     return true;
7913   }
7914   default:
7915     // TODO: Can handle more cases here.
7916     break;
7917   }
7918   
7919   return false;
7920 }
7921
7922 /// EvaluateInDifferentType - Given an expression that 
7923 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7924 /// evaluate the expression.
7925 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7926                                              bool isSigned) {
7927   if (Constant *C = dyn_cast<Constant>(V))
7928     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7929
7930   // Otherwise, it must be an instruction.
7931   Instruction *I = cast<Instruction>(V);
7932   Instruction *Res = 0;
7933   unsigned Opc = I->getOpcode();
7934   switch (Opc) {
7935   case Instruction::Add:
7936   case Instruction::Sub:
7937   case Instruction::Mul:
7938   case Instruction::And:
7939   case Instruction::Or:
7940   case Instruction::Xor:
7941   case Instruction::AShr:
7942   case Instruction::LShr:
7943   case Instruction::Shl: {
7944     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7945     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7946     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7947     break;
7948   }    
7949   case Instruction::Trunc:
7950   case Instruction::ZExt:
7951   case Instruction::SExt:
7952     // If the source type of the cast is the type we're trying for then we can
7953     // just return the source.  There's no need to insert it because it is not
7954     // new.
7955     if (I->getOperand(0)->getType() == Ty)
7956       return I->getOperand(0);
7957     
7958     // Otherwise, must be the same type of cast, so just reinsert a new one.
7959     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7960                            Ty);
7961     break;
7962   case Instruction::Select: {
7963     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7964     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7965     Res = SelectInst::Create(I->getOperand(0), True, False);
7966     break;
7967   }
7968   case Instruction::PHI: {
7969     PHINode *OPN = cast<PHINode>(I);
7970     PHINode *NPN = PHINode::Create(Ty);
7971     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7972       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7973       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7974     }
7975     Res = NPN;
7976     break;
7977   }
7978   default: 
7979     // TODO: Can handle more cases here.
7980     assert(0 && "Unreachable!");
7981     break;
7982   }
7983   
7984   Res->takeName(I);
7985   return InsertNewInstBefore(Res, *I);
7986 }
7987
7988 /// @brief Implement the transforms common to all CastInst visitors.
7989 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7990   Value *Src = CI.getOperand(0);
7991
7992   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7993   // eliminate it now.
7994   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7995     if (Instruction::CastOps opc = 
7996         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7997       // The first cast (CSrc) is eliminable so we need to fix up or replace
7998       // the second cast (CI). CSrc will then have a good chance of being dead.
7999       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8000     }
8001   }
8002
8003   // If we are casting a select then fold the cast into the select
8004   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8005     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8006       return NV;
8007
8008   // If we are casting a PHI then fold the cast into the PHI
8009   if (isa<PHINode>(Src))
8010     if (Instruction *NV = FoldOpIntoPhi(CI))
8011       return NV;
8012   
8013   return 0;
8014 }
8015
8016 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8017 /// or not there is a sequence of GEP indices into the type that will land us at
8018 /// the specified offset.  If so, fill them into NewIndices and return the
8019 /// resultant element type, otherwise return null.
8020 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8021                                        SmallVectorImpl<Value*> &NewIndices,
8022                                        const TargetData *TD) {
8023   if (!Ty->isSized()) return 0;
8024   
8025   // Start with the index over the outer type.  Note that the type size
8026   // might be zero (even if the offset isn't zero) if the indexed type
8027   // is something like [0 x {int, int}]
8028   const Type *IntPtrTy = TD->getIntPtrType();
8029   int64_t FirstIdx = 0;
8030   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8031     FirstIdx = Offset/TySize;
8032     Offset -= FirstIdx*TySize;
8033     
8034     // Handle hosts where % returns negative instead of values [0..TySize).
8035     if (Offset < 0) {
8036       --FirstIdx;
8037       Offset += TySize;
8038       assert(Offset >= 0);
8039     }
8040     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8041   }
8042   
8043   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8044     
8045   // Index into the types.  If we fail, set OrigBase to null.
8046   while (Offset) {
8047     // Indexing into tail padding between struct/array elements.
8048     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8049       return 0;
8050     
8051     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8052       const StructLayout *SL = TD->getStructLayout(STy);
8053       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8054              "Offset must stay within the indexed type");
8055       
8056       unsigned Elt = SL->getElementContainingOffset(Offset);
8057       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
8058       
8059       Offset -= SL->getElementOffset(Elt);
8060       Ty = STy->getElementType(Elt);
8061     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8062       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8063       assert(EltSize && "Cannot index into a zero-sized array");
8064       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8065       Offset %= EltSize;
8066       Ty = AT->getElementType();
8067     } else {
8068       // Otherwise, we can't index into the middle of this atomic type, bail.
8069       return 0;
8070     }
8071   }
8072   
8073   return Ty;
8074 }
8075
8076 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8077 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8078   Value *Src = CI.getOperand(0);
8079   
8080   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8081     // If casting the result of a getelementptr instruction with no offset, turn
8082     // this into a cast of the original pointer!
8083     if (GEP->hasAllZeroIndices()) {
8084       // Changing the cast operand is usually not a good idea but it is safe
8085       // here because the pointer operand is being replaced with another 
8086       // pointer operand so the opcode doesn't need to change.
8087       AddToWorkList(GEP);
8088       CI.setOperand(0, GEP->getOperand(0));
8089       return &CI;
8090     }
8091     
8092     // If the GEP has a single use, and the base pointer is a bitcast, and the
8093     // GEP computes a constant offset, see if we can convert these three
8094     // instructions into fewer.  This typically happens with unions and other
8095     // non-type-safe code.
8096     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8097       if (GEP->hasAllConstantIndices()) {
8098         // We are guaranteed to get a constant from EmitGEPOffset.
8099         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8100         int64_t Offset = OffsetV->getSExtValue();
8101         
8102         // Get the base pointer input of the bitcast, and the type it points to.
8103         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8104         const Type *GEPIdxTy =
8105           cast<PointerType>(OrigBase->getType())->getElementType();
8106         SmallVector<Value*, 8> NewIndices;
8107         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
8108           // If we were able to index down into an element, create the GEP
8109           // and bitcast the result.  This eliminates one bitcast, potentially
8110           // two.
8111           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8112                                                         NewIndices.begin(),
8113                                                         NewIndices.end(), "");
8114           InsertNewInstBefore(NGEP, CI);
8115           NGEP->takeName(GEP);
8116           
8117           if (isa<BitCastInst>(CI))
8118             return new BitCastInst(NGEP, CI.getType());
8119           assert(isa<PtrToIntInst>(CI));
8120           return new PtrToIntInst(NGEP, CI.getType());
8121         }
8122       }      
8123     }
8124   }
8125     
8126   return commonCastTransforms(CI);
8127 }
8128
8129 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8130 /// type like i42.  We don't want to introduce operations on random non-legal
8131 /// integer types where they don't already exist in the code.  In the future,
8132 /// we should consider making this based off target-data, so that 32-bit targets
8133 /// won't get i64 operations etc.
8134 static bool isSafeIntegerType(const Type *Ty) {
8135   switch (Ty->getPrimitiveSizeInBits()) {
8136   case 8:
8137   case 16:
8138   case 32:
8139   case 64:
8140     return true;
8141   default: 
8142     return false;
8143   }
8144 }
8145
8146 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8147 /// integer types. This function implements the common transforms for all those
8148 /// cases.
8149 /// @brief Implement the transforms common to CastInst with integer operands
8150 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8151   if (Instruction *Result = commonCastTransforms(CI))
8152     return Result;
8153
8154   Value *Src = CI.getOperand(0);
8155   const Type *SrcTy = Src->getType();
8156   const Type *DestTy = CI.getType();
8157   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8158   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8159
8160   // See if we can simplify any instructions used by the LHS whose sole 
8161   // purpose is to compute bits we don't care about.
8162   if (SimplifyDemandedInstructionBits(CI))
8163     return &CI;
8164
8165   // If the source isn't an instruction or has more than one use then we
8166   // can't do anything more. 
8167   Instruction *SrcI = dyn_cast<Instruction>(Src);
8168   if (!SrcI || !Src->hasOneUse())
8169     return 0;
8170
8171   // Attempt to propagate the cast into the instruction for int->int casts.
8172   int NumCastsRemoved = 0;
8173   if (!isa<BitCastInst>(CI) &&
8174       // Only do this if the dest type is a simple type, don't convert the
8175       // expression tree to something weird like i93 unless the source is also
8176       // strange.
8177       (isSafeIntegerType(DestTy->getScalarType()) ||
8178        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8179       CanEvaluateInDifferentType(SrcI, DestTy,
8180                                  CI.getOpcode(), NumCastsRemoved)) {
8181     // If this cast is a truncate, evaluting in a different type always
8182     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8183     // we need to do an AND to maintain the clear top-part of the computation,
8184     // so we require that the input have eliminated at least one cast.  If this
8185     // is a sign extension, we insert two new casts (to do the extension) so we
8186     // require that two casts have been eliminated.
8187     bool DoXForm = false;
8188     bool JustReplace = false;
8189     switch (CI.getOpcode()) {
8190     default:
8191       // All the others use floating point so we shouldn't actually 
8192       // get here because of the check above.
8193       assert(0 && "Unknown cast type");
8194     case Instruction::Trunc:
8195       DoXForm = true;
8196       break;
8197     case Instruction::ZExt: {
8198       DoXForm = NumCastsRemoved >= 1;
8199       if (!DoXForm && 0) {
8200         // If it's unnecessary to issue an AND to clear the high bits, it's
8201         // always profitable to do this xform.
8202         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8203         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8204         if (MaskedValueIsZero(TryRes, Mask))
8205           return ReplaceInstUsesWith(CI, TryRes);
8206         
8207         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8208           if (TryI->use_empty())
8209             EraseInstFromFunction(*TryI);
8210       }
8211       break;
8212     }
8213     case Instruction::SExt: {
8214       DoXForm = NumCastsRemoved >= 2;
8215       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8216         // If we do not have to emit the truncate + sext pair, then it's always
8217         // profitable to do this xform.
8218         //
8219         // It's not safe to eliminate the trunc + sext pair if one of the
8220         // eliminated cast is a truncate. e.g.
8221         // t2 = trunc i32 t1 to i16
8222         // t3 = sext i16 t2 to i32
8223         // !=
8224         // i32 t1
8225         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8226         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8227         if (NumSignBits > (DestBitSize - SrcBitSize))
8228           return ReplaceInstUsesWith(CI, TryRes);
8229         
8230         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8231           if (TryI->use_empty())
8232             EraseInstFromFunction(*TryI);
8233       }
8234       break;
8235     }
8236     }
8237     
8238     if (DoXForm) {
8239       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8240            << " cast: " << CI;
8241       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8242                                            CI.getOpcode() == Instruction::SExt);
8243       if (JustReplace)
8244         // Just replace this cast with the result.
8245         return ReplaceInstUsesWith(CI, Res);
8246
8247       assert(Res->getType() == DestTy);
8248       switch (CI.getOpcode()) {
8249       default: assert(0 && "Unknown cast type!");
8250       case Instruction::Trunc:
8251       case Instruction::BitCast:
8252         // Just replace this cast with the result.
8253         return ReplaceInstUsesWith(CI, Res);
8254       case Instruction::ZExt: {
8255         assert(SrcBitSize < DestBitSize && "Not a zext?");
8256
8257         // If the high bits are already zero, just replace this cast with the
8258         // result.
8259         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8260         if (MaskedValueIsZero(Res, Mask))
8261           return ReplaceInstUsesWith(CI, Res);
8262
8263         // We need to emit an AND to clear the high bits.
8264         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8265                                                             SrcBitSize));
8266         return BinaryOperator::CreateAnd(Res, C);
8267       }
8268       case Instruction::SExt: {
8269         // If the high bits are already filled with sign bit, just replace this
8270         // cast with the result.
8271         unsigned NumSignBits = ComputeNumSignBits(Res);
8272         if (NumSignBits > (DestBitSize - SrcBitSize))
8273           return ReplaceInstUsesWith(CI, Res);
8274
8275         // We need to emit a cast to truncate, then a cast to sext.
8276         return CastInst::Create(Instruction::SExt,
8277             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8278                              CI), DestTy);
8279       }
8280       }
8281     }
8282   }
8283   
8284   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8285   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8286
8287   switch (SrcI->getOpcode()) {
8288   case Instruction::Add:
8289   case Instruction::Mul:
8290   case Instruction::And:
8291   case Instruction::Or:
8292   case Instruction::Xor:
8293     // If we are discarding information, rewrite.
8294     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8295       // Don't insert two casts if they cannot be eliminated.  We allow 
8296       // two casts to be inserted if the sizes are the same.  This could 
8297       // only be converting signedness, which is a noop.
8298       if (DestBitSize == SrcBitSize || 
8299           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8300           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8301         Instruction::CastOps opcode = CI.getOpcode();
8302         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8303         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8304         return BinaryOperator::Create(
8305             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8306       }
8307     }
8308
8309     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8310     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8311         SrcI->getOpcode() == Instruction::Xor &&
8312         Op1 == ConstantInt::getTrue() &&
8313         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8314       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8315       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
8316     }
8317     break;
8318   case Instruction::SDiv:
8319   case Instruction::UDiv:
8320   case Instruction::SRem:
8321   case Instruction::URem:
8322     // If we are just changing the sign, rewrite.
8323     if (DestBitSize == SrcBitSize) {
8324       // Don't insert two casts if they cannot be eliminated.  We allow 
8325       // two casts to be inserted if the sizes are the same.  This could 
8326       // only be converting signedness, which is a noop.
8327       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
8328           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8329         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
8330                                        Op0, DestTy, *SrcI);
8331         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
8332                                        Op1, DestTy, *SrcI);
8333         return BinaryOperator::Create(
8334           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8335       }
8336     }
8337     break;
8338
8339   case Instruction::Shl:
8340     // Allow changing the sign of the source operand.  Do not allow 
8341     // changing the size of the shift, UNLESS the shift amount is a 
8342     // constant.  We must not change variable sized shifts to a smaller 
8343     // size, because it is undefined to shift more bits out than exist 
8344     // in the value.
8345     if (DestBitSize == SrcBitSize ||
8346         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8347       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8348           Instruction::BitCast : Instruction::Trunc);
8349       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8350       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8351       return BinaryOperator::CreateShl(Op0c, Op1c);
8352     }
8353     break;
8354   case Instruction::AShr:
8355     // If this is a signed shr, and if all bits shifted in are about to be
8356     // truncated off, turn it into an unsigned shr to allow greater
8357     // simplifications.
8358     if (DestBitSize < SrcBitSize &&
8359         isa<ConstantInt>(Op1)) {
8360       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8361       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8362         // Insert the new logical shift right.
8363         return BinaryOperator::CreateLShr(Op0, Op1);
8364       }
8365     }
8366     break;
8367   }
8368   return 0;
8369 }
8370
8371 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8372   if (Instruction *Result = commonIntCastTransforms(CI))
8373     return Result;
8374   
8375   Value *Src = CI.getOperand(0);
8376   const Type *Ty = CI.getType();
8377   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8378   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8379
8380   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8381   if (DestBitWidth == 1 &&
8382       isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
8383     Constant *One = ConstantInt::get(Src->getType(), 1);
8384     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8385     Value *Zero = Constant::getNullValue(Src->getType());
8386     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8387   }
8388
8389   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8390   ConstantInt *ShAmtV = 0;
8391   Value *ShiftOp = 0;
8392   if (Src->hasOneUse() &&
8393       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8394     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8395     
8396     // Get a mask for the bits shifting in.
8397     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8398     if (MaskedValueIsZero(ShiftOp, Mask)) {
8399       if (ShAmt >= DestBitWidth)        // All zeros.
8400         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8401       
8402       // Okay, we can shrink this.  Truncate the input, then return a new
8403       // shift.
8404       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8405       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8406       return BinaryOperator::CreateLShr(V1, V2);
8407     }
8408   }
8409   
8410   return 0;
8411 }
8412
8413 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8414 /// in order to eliminate the icmp.
8415 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8416                                              bool DoXform) {
8417   // If we are just checking for a icmp eq of a single bit and zext'ing it
8418   // to an integer, then shift the bit to the appropriate place and then
8419   // cast to integer to avoid the comparison.
8420   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8421     const APInt &Op1CV = Op1C->getValue();
8422       
8423     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8424     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8425     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8426         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8427       if (!DoXform) return ICI;
8428
8429       Value *In = ICI->getOperand(0);
8430       Value *Sh = ConstantInt::get(In->getType(),
8431                                    In->getType()->getScalarSizeInBits()-1);
8432       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8433                                                         In->getName()+".lobit"),
8434                                CI);
8435       if (In->getType() != CI.getType())
8436         In = CastInst::CreateIntegerCast(In, CI.getType(),
8437                                          false/*ZExt*/, "tmp", &CI);
8438
8439       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8440         Constant *One = ConstantInt::get(In->getType(), 1);
8441         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8442                                                          In->getName()+".not"),
8443                                  CI);
8444       }
8445
8446       return ReplaceInstUsesWith(CI, In);
8447     }
8448       
8449       
8450       
8451     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8452     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8453     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8454     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8455     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8456     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8457     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8458     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8459     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8460         // This only works for EQ and NE
8461         ICI->isEquality()) {
8462       // If Op1C some other power of two, convert:
8463       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8464       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8465       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8466       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8467         
8468       APInt KnownZeroMask(~KnownZero);
8469       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8470         if (!DoXform) return ICI;
8471
8472         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8473         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8474           // (X&4) == 2 --> false
8475           // (X&4) != 2 --> true
8476           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8477           Res = ConstantExpr::getZExt(Res, CI.getType());
8478           return ReplaceInstUsesWith(CI, Res);
8479         }
8480           
8481         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8482         Value *In = ICI->getOperand(0);
8483         if (ShiftAmt) {
8484           // Perform a logical shr by shiftamt.
8485           // Insert the shift to put the result in the low bit.
8486           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8487                                   ConstantInt::get(In->getType(), ShiftAmt),
8488                                                    In->getName()+".lobit"), CI);
8489         }
8490           
8491         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8492           Constant *One = ConstantInt::get(In->getType(), 1);
8493           In = BinaryOperator::CreateXor(In, One, "tmp");
8494           InsertNewInstBefore(cast<Instruction>(In), CI);
8495         }
8496           
8497         if (CI.getType() == In->getType())
8498           return ReplaceInstUsesWith(CI, In);
8499         else
8500           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8501       }
8502     }
8503   }
8504
8505   return 0;
8506 }
8507
8508 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8509   // If one of the common conversion will work ..
8510   if (Instruction *Result = commonIntCastTransforms(CI))
8511     return Result;
8512
8513   Value *Src = CI.getOperand(0);
8514
8515   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8516   // types and if the sizes are just right we can convert this into a logical
8517   // 'and' which will be much cheaper than the pair of casts.
8518   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8519     // Get the sizes of the types involved.  We know that the intermediate type
8520     // will be smaller than A or C, but don't know the relation between A and C.
8521     Value *A = CSrc->getOperand(0);
8522     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8523     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8524     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8525     // If we're actually extending zero bits, then if
8526     // SrcSize <  DstSize: zext(a & mask)
8527     // SrcSize == DstSize: a & mask
8528     // SrcSize  > DstSize: trunc(a) & mask
8529     if (SrcSize < DstSize) {
8530       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8531       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8532       Instruction *And =
8533         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8534       InsertNewInstBefore(And, CI);
8535       return new ZExtInst(And, CI.getType());
8536     } else if (SrcSize == DstSize) {
8537       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8538       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8539                                                            AndValue));
8540     } else if (SrcSize > DstSize) {
8541       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8542       InsertNewInstBefore(Trunc, CI);
8543       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8544       return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(Trunc->getType(),
8545                                                                AndValue));
8546     }
8547   }
8548
8549   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8550     return transformZExtICmp(ICI, CI);
8551
8552   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8553   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8554     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8555     // of the (zext icmp) will be transformed.
8556     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8557     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8558     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8559         (transformZExtICmp(LHS, CI, false) ||
8560          transformZExtICmp(RHS, CI, false))) {
8561       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8562       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8563       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8564     }
8565   }
8566
8567   // zext(trunc(t) & C) -> (t & zext(C)).
8568   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8569     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8570       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8571         Value *TI0 = TI->getOperand(0);
8572         if (TI0->getType() == CI.getType())
8573           return
8574             BinaryOperator::CreateAnd(TI0,
8575                                       ConstantExpr::getZExt(C, CI.getType()));
8576       }
8577
8578   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8579   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8580     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8581       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8582         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8583             And->getOperand(1) == C)
8584           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8585             Value *TI0 = TI->getOperand(0);
8586             if (TI0->getType() == CI.getType()) {
8587               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8588               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8589               InsertNewInstBefore(NewAnd, *And);
8590               return BinaryOperator::CreateXor(NewAnd, ZC);
8591             }
8592           }
8593
8594   return 0;
8595 }
8596
8597 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8598   if (Instruction *I = commonIntCastTransforms(CI))
8599     return I;
8600   
8601   Value *Src = CI.getOperand(0);
8602   
8603   // Canonicalize sign-extend from i1 to a select.
8604   if (Src->getType() == Type::Int1Ty)
8605     return SelectInst::Create(Src,
8606                               ConstantInt::getAllOnesValue(CI.getType()),
8607                               Constant::getNullValue(CI.getType()));
8608
8609   // See if the value being truncated is already sign extended.  If so, just
8610   // eliminate the trunc/sext pair.
8611   if (getOpcode(Src) == Instruction::Trunc) {
8612     Value *Op = cast<User>(Src)->getOperand(0);
8613     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8614     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8615     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8616     unsigned NumSignBits = ComputeNumSignBits(Op);
8617
8618     if (OpBits == DestBits) {
8619       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8620       // bits, it is already ready.
8621       if (NumSignBits > DestBits-MidBits)
8622         return ReplaceInstUsesWith(CI, Op);
8623     } else if (OpBits < DestBits) {
8624       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8625       // bits, just sext from i32.
8626       if (NumSignBits > OpBits-MidBits)
8627         return new SExtInst(Op, CI.getType(), "tmp");
8628     } else {
8629       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8630       // bits, just truncate to i32.
8631       if (NumSignBits > OpBits-MidBits)
8632         return new TruncInst(Op, CI.getType(), "tmp");
8633     }
8634   }
8635
8636   // If the input is a shl/ashr pair of a same constant, then this is a sign
8637   // extension from a smaller value.  If we could trust arbitrary bitwidth
8638   // integers, we could turn this into a truncate to the smaller bit and then
8639   // use a sext for the whole extension.  Since we don't, look deeper and check
8640   // for a truncate.  If the source and dest are the same type, eliminate the
8641   // trunc and extend and just do shifts.  For example, turn:
8642   //   %a = trunc i32 %i to i8
8643   //   %b = shl i8 %a, 6
8644   //   %c = ashr i8 %b, 6
8645   //   %d = sext i8 %c to i32
8646   // into:
8647   //   %a = shl i32 %i, 30
8648   //   %d = ashr i32 %a, 30
8649   Value *A = 0;
8650   ConstantInt *BA = 0, *CA = 0;
8651   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8652                         m_ConstantInt(CA))) &&
8653       BA == CA && isa<TruncInst>(A)) {
8654     Value *I = cast<TruncInst>(A)->getOperand(0);
8655     if (I->getType() == CI.getType()) {
8656       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8657       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8658       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8659       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8660       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8661                                                         CI.getName()), CI);
8662       return BinaryOperator::CreateAShr(I, ShAmtV);
8663     }
8664   }
8665   
8666   return 0;
8667 }
8668
8669 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8670 /// in the specified FP type without changing its value.
8671 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8672   bool losesInfo;
8673   APFloat F = CFP->getValueAPF();
8674   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8675   if (!losesInfo)
8676     return ConstantFP::get(F);
8677   return 0;
8678 }
8679
8680 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8681 /// through it until we get the source value.
8682 static Value *LookThroughFPExtensions(Value *V) {
8683   if (Instruction *I = dyn_cast<Instruction>(V))
8684     if (I->getOpcode() == Instruction::FPExt)
8685       return LookThroughFPExtensions(I->getOperand(0));
8686   
8687   // If this value is a constant, return the constant in the smallest FP type
8688   // that can accurately represent it.  This allows us to turn
8689   // (float)((double)X+2.0) into x+2.0f.
8690   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8691     if (CFP->getType() == Type::PPC_FP128Ty)
8692       return V;  // No constant folding of this.
8693     // See if the value can be truncated to float and then reextended.
8694     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8695       return V;
8696     if (CFP->getType() == Type::DoubleTy)
8697       return V;  // Won't shrink.
8698     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8699       return V;
8700     // Don't try to shrink to various long double types.
8701   }
8702   
8703   return V;
8704 }
8705
8706 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8707   if (Instruction *I = commonCastTransforms(CI))
8708     return I;
8709   
8710   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8711   // smaller than the destination type, we can eliminate the truncate by doing
8712   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8713   // many builtins (sqrt, etc).
8714   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8715   if (OpI && OpI->hasOneUse()) {
8716     switch (OpI->getOpcode()) {
8717     default: break;
8718     case Instruction::FAdd:
8719     case Instruction::FSub:
8720     case Instruction::FMul:
8721     case Instruction::FDiv:
8722     case Instruction::FRem:
8723       const Type *SrcTy = OpI->getType();
8724       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8725       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8726       if (LHSTrunc->getType() != SrcTy && 
8727           RHSTrunc->getType() != SrcTy) {
8728         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8729         // If the source types were both smaller than the destination type of
8730         // the cast, do this xform.
8731         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8732             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8733           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8734                                       CI.getType(), CI);
8735           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8736                                       CI.getType(), CI);
8737           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8738         }
8739       }
8740       break;  
8741     }
8742   }
8743   return 0;
8744 }
8745
8746 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8747   return commonCastTransforms(CI);
8748 }
8749
8750 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8751   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8752   if (OpI == 0)
8753     return commonCastTransforms(FI);
8754
8755   // fptoui(uitofp(X)) --> X
8756   // fptoui(sitofp(X)) --> X
8757   // This is safe if the intermediate type has enough bits in its mantissa to
8758   // accurately represent all values of X.  For example, do not do this with
8759   // i64->float->i64.  This is also safe for sitofp case, because any negative
8760   // 'X' value would cause an undefined result for the fptoui. 
8761   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8762       OpI->getOperand(0)->getType() == FI.getType() &&
8763       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8764                     OpI->getType()->getFPMantissaWidth())
8765     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8766
8767   return commonCastTransforms(FI);
8768 }
8769
8770 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8771   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8772   if (OpI == 0)
8773     return commonCastTransforms(FI);
8774   
8775   // fptosi(sitofp(X)) --> X
8776   // fptosi(uitofp(X)) --> X
8777   // This is safe if the intermediate type has enough bits in its mantissa to
8778   // accurately represent all values of X.  For example, do not do this with
8779   // i64->float->i64.  This is also safe for sitofp case, because any negative
8780   // 'X' value would cause an undefined result for the fptoui. 
8781   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8782       OpI->getOperand(0)->getType() == FI.getType() &&
8783       (int)FI.getType()->getScalarSizeInBits() <=
8784                     OpI->getType()->getFPMantissaWidth())
8785     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8786   
8787   return commonCastTransforms(FI);
8788 }
8789
8790 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8791   return commonCastTransforms(CI);
8792 }
8793
8794 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8795   return commonCastTransforms(CI);
8796 }
8797
8798 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8799   // If the destination integer type is smaller than the intptr_t type for
8800   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8801   // trunc to be exposed to other transforms.  Don't do this for extending
8802   // ptrtoint's, because we don't know if the target sign or zero extends its
8803   // pointers.
8804   if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8805     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8806                                                     TD->getIntPtrType(),
8807                                                     "tmp"), CI);
8808     return new TruncInst(P, CI.getType());
8809   }
8810   
8811   return commonPointerCastTransforms(CI);
8812 }
8813
8814 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8815   // If the source integer type is larger than the intptr_t type for
8816   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8817   // allows the trunc to be exposed to other transforms.  Don't do this for
8818   // extending inttoptr's, because we don't know if the target sign or zero
8819   // extends to pointers.
8820   if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8821       TD->getPointerSizeInBits()) {
8822     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8823                                                  TD->getIntPtrType(),
8824                                                  "tmp"), CI);
8825     return new IntToPtrInst(P, CI.getType());
8826   }
8827   
8828   if (Instruction *I = commonCastTransforms(CI))
8829     return I;
8830   
8831   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8832   if (!DestPointee->isSized()) return 0;
8833
8834   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8835   ConstantInt *Cst;
8836   Value *X;
8837   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8838                                     m_ConstantInt(Cst)))) {
8839     // If the source and destination operands have the same type, see if this
8840     // is a single-index GEP.
8841     if (X->getType() == CI.getType()) {
8842       // Get the size of the pointee type.
8843       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8844
8845       // Convert the constant to intptr type.
8846       APInt Offset = Cst->getValue();
8847       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8848
8849       // If Offset is evenly divisible by Size, we can do this xform.
8850       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8851         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8852         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8853       }
8854     }
8855     // TODO: Could handle other cases, e.g. where add is indexing into field of
8856     // struct etc.
8857   } else if (CI.getOperand(0)->hasOneUse() &&
8858              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8859     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8860     // "inttoptr+GEP" instead of "add+intptr".
8861     
8862     // Get the size of the pointee type.
8863     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8864     
8865     // Convert the constant to intptr type.
8866     APInt Offset = Cst->getValue();
8867     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8868     
8869     // If Offset is evenly divisible by Size, we can do this xform.
8870     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8871       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8872       
8873       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8874                                                             "tmp"), CI);
8875       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8876     }
8877   }
8878   return 0;
8879 }
8880
8881 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8882   // If the operands are integer typed then apply the integer transforms,
8883   // otherwise just apply the common ones.
8884   Value *Src = CI.getOperand(0);
8885   const Type *SrcTy = Src->getType();
8886   const Type *DestTy = CI.getType();
8887
8888   if (SrcTy->isInteger() && DestTy->isInteger()) {
8889     if (Instruction *Result = commonIntCastTransforms(CI))
8890       return Result;
8891   } else if (isa<PointerType>(SrcTy)) {
8892     if (Instruction *I = commonPointerCastTransforms(CI))
8893       return I;
8894   } else {
8895     if (Instruction *Result = commonCastTransforms(CI))
8896       return Result;
8897   }
8898
8899
8900   // Get rid of casts from one type to the same type. These are useless and can
8901   // be replaced by the operand.
8902   if (DestTy == Src->getType())
8903     return ReplaceInstUsesWith(CI, Src);
8904
8905   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8906     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8907     const Type *DstElTy = DstPTy->getElementType();
8908     const Type *SrcElTy = SrcPTy->getElementType();
8909     
8910     // If the address spaces don't match, don't eliminate the bitcast, which is
8911     // required for changing types.
8912     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8913       return 0;
8914     
8915     // If we are casting a malloc or alloca to a pointer to a type of the same
8916     // size, rewrite the allocation instruction to allocate the "right" type.
8917     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8918       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8919         return V;
8920     
8921     // If the source and destination are pointers, and this cast is equivalent
8922     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8923     // This can enhance SROA and other transforms that want type-safe pointers.
8924     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8925     unsigned NumZeros = 0;
8926     while (SrcElTy != DstElTy && 
8927            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8928            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8929       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8930       ++NumZeros;
8931     }
8932
8933     // If we found a path from the src to dest, create the getelementptr now.
8934     if (SrcElTy == DstElTy) {
8935       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8936       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8937                                        ((Instruction*) NULL));
8938     }
8939   }
8940
8941   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8942     if (SVI->hasOneUse()) {
8943       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8944       // a bitconvert to a vector with the same # elts.
8945       if (isa<VectorType>(DestTy) && 
8946           cast<VectorType>(DestTy)->getNumElements() ==
8947                 SVI->getType()->getNumElements() &&
8948           SVI->getType()->getNumElements() ==
8949             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8950         CastInst *Tmp;
8951         // If either of the operands is a cast from CI.getType(), then
8952         // evaluating the shuffle in the casted destination's type will allow
8953         // us to eliminate at least one cast.
8954         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8955              Tmp->getOperand(0)->getType() == DestTy) ||
8956             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8957              Tmp->getOperand(0)->getType() == DestTy)) {
8958           Value *LHS = InsertCastBefore(Instruction::BitCast,
8959                                         SVI->getOperand(0), DestTy, CI);
8960           Value *RHS = InsertCastBefore(Instruction::BitCast,
8961                                         SVI->getOperand(1), DestTy, CI);
8962           // Return a new shuffle vector.  Use the same element ID's, as we
8963           // know the vector types match #elts.
8964           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8965         }
8966       }
8967     }
8968   }
8969   return 0;
8970 }
8971
8972 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8973 ///   %C = or %A, %B
8974 ///   %D = select %cond, %C, %A
8975 /// into:
8976 ///   %C = select %cond, %B, 0
8977 ///   %D = or %A, %C
8978 ///
8979 /// Assuming that the specified instruction is an operand to the select, return
8980 /// a bitmask indicating which operands of this instruction are foldable if they
8981 /// equal the other incoming value of the select.
8982 ///
8983 static unsigned GetSelectFoldableOperands(Instruction *I) {
8984   switch (I->getOpcode()) {
8985   case Instruction::Add:
8986   case Instruction::Mul:
8987   case Instruction::And:
8988   case Instruction::Or:
8989   case Instruction::Xor:
8990     return 3;              // Can fold through either operand.
8991   case Instruction::Sub:   // Can only fold on the amount subtracted.
8992   case Instruction::Shl:   // Can only fold on the shift amount.
8993   case Instruction::LShr:
8994   case Instruction::AShr:
8995     return 1;
8996   default:
8997     return 0;              // Cannot fold
8998   }
8999 }
9000
9001 /// GetSelectFoldableConstant - For the same transformation as the previous
9002 /// function, return the identity constant that goes into the select.
9003 static Constant *GetSelectFoldableConstant(Instruction *I) {
9004   switch (I->getOpcode()) {
9005   default: assert(0 && "This cannot happen!"); abort();
9006   case Instruction::Add:
9007   case Instruction::Sub:
9008   case Instruction::Or:
9009   case Instruction::Xor:
9010   case Instruction::Shl:
9011   case Instruction::LShr:
9012   case Instruction::AShr:
9013     return Constant::getNullValue(I->getType());
9014   case Instruction::And:
9015     return Constant::getAllOnesValue(I->getType());
9016   case Instruction::Mul:
9017     return ConstantInt::get(I->getType(), 1);
9018   }
9019 }
9020
9021 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9022 /// have the same opcode and only one use each.  Try to simplify this.
9023 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9024                                           Instruction *FI) {
9025   if (TI->getNumOperands() == 1) {
9026     // If this is a non-volatile load or a cast from the same type,
9027     // merge.
9028     if (TI->isCast()) {
9029       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9030         return 0;
9031     } else {
9032       return 0;  // unknown unary op.
9033     }
9034
9035     // Fold this by inserting a select from the input values.
9036     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9037                                            FI->getOperand(0), SI.getName()+".v");
9038     InsertNewInstBefore(NewSI, SI);
9039     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9040                             TI->getType());
9041   }
9042
9043   // Only handle binary operators here.
9044   if (!isa<BinaryOperator>(TI))
9045     return 0;
9046
9047   // Figure out if the operations have any operands in common.
9048   Value *MatchOp, *OtherOpT, *OtherOpF;
9049   bool MatchIsOpZero;
9050   if (TI->getOperand(0) == FI->getOperand(0)) {
9051     MatchOp  = TI->getOperand(0);
9052     OtherOpT = TI->getOperand(1);
9053     OtherOpF = FI->getOperand(1);
9054     MatchIsOpZero = true;
9055   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9056     MatchOp  = TI->getOperand(1);
9057     OtherOpT = TI->getOperand(0);
9058     OtherOpF = FI->getOperand(0);
9059     MatchIsOpZero = false;
9060   } else if (!TI->isCommutative()) {
9061     return 0;
9062   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9063     MatchOp  = TI->getOperand(0);
9064     OtherOpT = TI->getOperand(1);
9065     OtherOpF = FI->getOperand(0);
9066     MatchIsOpZero = true;
9067   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9068     MatchOp  = TI->getOperand(1);
9069     OtherOpT = TI->getOperand(0);
9070     OtherOpF = FI->getOperand(1);
9071     MatchIsOpZero = true;
9072   } else {
9073     return 0;
9074   }
9075
9076   // If we reach here, they do have operations in common.
9077   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9078                                          OtherOpF, SI.getName()+".v");
9079   InsertNewInstBefore(NewSI, SI);
9080
9081   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9082     if (MatchIsOpZero)
9083       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9084     else
9085       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9086   }
9087   assert(0 && "Shouldn't get here");
9088   return 0;
9089 }
9090
9091 static bool isSelect01(Constant *C1, Constant *C2) {
9092   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9093   if (!C1I)
9094     return false;
9095   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9096   if (!C2I)
9097     return false;
9098   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9099 }
9100
9101 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9102 /// facilitate further optimization.
9103 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9104                                             Value *FalseVal) {
9105   // See the comment above GetSelectFoldableOperands for a description of the
9106   // transformation we are doing here.
9107   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9108     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9109         !isa<Constant>(FalseVal)) {
9110       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9111         unsigned OpToFold = 0;
9112         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9113           OpToFold = 1;
9114         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9115           OpToFold = 2;
9116         }
9117
9118         if (OpToFold) {
9119           Constant *C = GetSelectFoldableConstant(TVI);
9120           Value *OOp = TVI->getOperand(2-OpToFold);
9121           // Avoid creating select between 2 constants unless it's selecting
9122           // between 0 and 1.
9123           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9124             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9125             InsertNewInstBefore(NewSel, SI);
9126             NewSel->takeName(TVI);
9127             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9128               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9129             assert(0 && "Unknown instruction!!");
9130           }
9131         }
9132       }
9133     }
9134   }
9135
9136   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9137     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9138         !isa<Constant>(TrueVal)) {
9139       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9140         unsigned OpToFold = 0;
9141         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9142           OpToFold = 1;
9143         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9144           OpToFold = 2;
9145         }
9146
9147         if (OpToFold) {
9148           Constant *C = GetSelectFoldableConstant(FVI);
9149           Value *OOp = FVI->getOperand(2-OpToFold);
9150           // Avoid creating select between 2 constants unless it's selecting
9151           // between 0 and 1.
9152           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9153             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9154             InsertNewInstBefore(NewSel, SI);
9155             NewSel->takeName(FVI);
9156             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9157               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9158             assert(0 && "Unknown instruction!!");
9159           }
9160         }
9161       }
9162     }
9163   }
9164
9165   return 0;
9166 }
9167
9168 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9169 /// ICmpInst as its first operand.
9170 ///
9171 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9172                                                    ICmpInst *ICI) {
9173   bool Changed = false;
9174   ICmpInst::Predicate Pred = ICI->getPredicate();
9175   Value *CmpLHS = ICI->getOperand(0);
9176   Value *CmpRHS = ICI->getOperand(1);
9177   Value *TrueVal = SI.getTrueValue();
9178   Value *FalseVal = SI.getFalseValue();
9179
9180   // Check cases where the comparison is with a constant that
9181   // can be adjusted to fit the min/max idiom. We may edit ICI in
9182   // place here, so make sure the select is the only user.
9183   if (ICI->hasOneUse())
9184     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9185       switch (Pred) {
9186       default: break;
9187       case ICmpInst::ICMP_ULT:
9188       case ICmpInst::ICMP_SLT: {
9189         // X < MIN ? T : F  -->  F
9190         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9191           return ReplaceInstUsesWith(SI, FalseVal);
9192         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9193         Constant *AdjustedRHS = SubOne(CI);
9194         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9195             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9196           Pred = ICmpInst::getSwappedPredicate(Pred);
9197           CmpRHS = AdjustedRHS;
9198           std::swap(FalseVal, TrueVal);
9199           ICI->setPredicate(Pred);
9200           ICI->setOperand(1, CmpRHS);
9201           SI.setOperand(1, TrueVal);
9202           SI.setOperand(2, FalseVal);
9203           Changed = true;
9204         }
9205         break;
9206       }
9207       case ICmpInst::ICMP_UGT:
9208       case ICmpInst::ICMP_SGT: {
9209         // X > MAX ? T : F  -->  F
9210         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9211           return ReplaceInstUsesWith(SI, FalseVal);
9212         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9213         Constant *AdjustedRHS = AddOne(CI);
9214         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9215             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9216           Pred = ICmpInst::getSwappedPredicate(Pred);
9217           CmpRHS = AdjustedRHS;
9218           std::swap(FalseVal, TrueVal);
9219           ICI->setPredicate(Pred);
9220           ICI->setOperand(1, CmpRHS);
9221           SI.setOperand(1, TrueVal);
9222           SI.setOperand(2, FalseVal);
9223           Changed = true;
9224         }
9225         break;
9226       }
9227       }
9228
9229       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9230       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9231       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9232       if (match(TrueVal, m_ConstantInt<-1>()) &&
9233           match(FalseVal, m_ConstantInt<0>()))
9234         Pred = ICI->getPredicate();
9235       else if (match(TrueVal, m_ConstantInt<0>()) &&
9236                match(FalseVal, m_ConstantInt<-1>()))
9237         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9238       
9239       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9240         // If we are just checking for a icmp eq of a single bit and zext'ing it
9241         // to an integer, then shift the bit to the appropriate place and then
9242         // cast to integer to avoid the comparison.
9243         const APInt &Op1CV = CI->getValue();
9244     
9245         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9246         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9247         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9248             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9249           Value *In = ICI->getOperand(0);
9250           Value *Sh = ConstantInt::get(In->getType(),
9251                                        In->getType()->getScalarSizeInBits()-1);
9252           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9253                                                           In->getName()+".lobit"),
9254                                    *ICI);
9255           if (In->getType() != SI.getType())
9256             In = CastInst::CreateIntegerCast(In, SI.getType(),
9257                                              true/*SExt*/, "tmp", ICI);
9258     
9259           if (Pred == ICmpInst::ICMP_SGT)
9260             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9261                                        In->getName()+".not"), *ICI);
9262     
9263           return ReplaceInstUsesWith(SI, In);
9264         }
9265       }
9266     }
9267
9268   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9269     // Transform (X == Y) ? X : Y  -> Y
9270     if (Pred == ICmpInst::ICMP_EQ)
9271       return ReplaceInstUsesWith(SI, FalseVal);
9272     // Transform (X != Y) ? X : Y  -> X
9273     if (Pred == ICmpInst::ICMP_NE)
9274       return ReplaceInstUsesWith(SI, TrueVal);
9275     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9276
9277   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9278     // Transform (X == Y) ? Y : X  -> X
9279     if (Pred == ICmpInst::ICMP_EQ)
9280       return ReplaceInstUsesWith(SI, FalseVal);
9281     // Transform (X != Y) ? Y : X  -> Y
9282     if (Pred == ICmpInst::ICMP_NE)
9283       return ReplaceInstUsesWith(SI, TrueVal);
9284     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9285   }
9286
9287   /// NOTE: if we wanted to, this is where to detect integer ABS
9288
9289   return Changed ? &SI : 0;
9290 }
9291
9292 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9293   Value *CondVal = SI.getCondition();
9294   Value *TrueVal = SI.getTrueValue();
9295   Value *FalseVal = SI.getFalseValue();
9296
9297   // select true, X, Y  -> X
9298   // select false, X, Y -> Y
9299   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9300     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9301
9302   // select C, X, X -> X
9303   if (TrueVal == FalseVal)
9304     return ReplaceInstUsesWith(SI, TrueVal);
9305
9306   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9307     return ReplaceInstUsesWith(SI, FalseVal);
9308   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9309     return ReplaceInstUsesWith(SI, TrueVal);
9310   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9311     if (isa<Constant>(TrueVal))
9312       return ReplaceInstUsesWith(SI, TrueVal);
9313     else
9314       return ReplaceInstUsesWith(SI, FalseVal);
9315   }
9316
9317   if (SI.getType() == Type::Int1Ty) {
9318     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9319       if (C->getZExtValue()) {
9320         // Change: A = select B, true, C --> A = or B, C
9321         return BinaryOperator::CreateOr(CondVal, FalseVal);
9322       } else {
9323         // Change: A = select B, false, C --> A = and !B, C
9324         Value *NotCond =
9325           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9326                                              "not."+CondVal->getName()), SI);
9327         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9328       }
9329     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9330       if (C->getZExtValue() == false) {
9331         // Change: A = select B, C, false --> A = and B, C
9332         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9333       } else {
9334         // Change: A = select B, C, true --> A = or !B, C
9335         Value *NotCond =
9336           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9337                                              "not."+CondVal->getName()), SI);
9338         return BinaryOperator::CreateOr(NotCond, TrueVal);
9339       }
9340     }
9341     
9342     // select a, b, a  -> a&b
9343     // select a, a, b  -> a|b
9344     if (CondVal == TrueVal)
9345       return BinaryOperator::CreateOr(CondVal, FalseVal);
9346     else if (CondVal == FalseVal)
9347       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9348   }
9349
9350   // Selecting between two integer constants?
9351   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9352     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9353       // select C, 1, 0 -> zext C to int
9354       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9355         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9356       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9357         // select C, 0, 1 -> zext !C to int
9358         Value *NotCond =
9359           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9360                                                "not."+CondVal->getName()), SI);
9361         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9362       }
9363
9364       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9365
9366         // (x <s 0) ? -1 : 0 -> ashr x, 31
9367         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9368           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9369             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9370               // The comparison constant and the result are not neccessarily the
9371               // same width. Make an all-ones value by inserting a AShr.
9372               Value *X = IC->getOperand(0);
9373               uint32_t Bits = X->getType()->getScalarSizeInBits();
9374               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
9375               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
9376                                                         ShAmt, "ones");
9377               InsertNewInstBefore(SRA, SI);
9378
9379               // Then cast to the appropriate width.
9380               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
9381             }
9382           }
9383
9384
9385         // If one of the constants is zero (we know they can't both be) and we
9386         // have an icmp instruction with zero, and we have an 'and' with the
9387         // non-constant value, eliminate this whole mess.  This corresponds to
9388         // cases like this: ((X & 27) ? 27 : 0)
9389         if (TrueValC->isZero() || FalseValC->isZero())
9390           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9391               cast<Constant>(IC->getOperand(1))->isNullValue())
9392             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9393               if (ICA->getOpcode() == Instruction::And &&
9394                   isa<ConstantInt>(ICA->getOperand(1)) &&
9395                   (ICA->getOperand(1) == TrueValC ||
9396                    ICA->getOperand(1) == FalseValC) &&
9397                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9398                 // Okay, now we know that everything is set up, we just don't
9399                 // know whether we have a icmp_ne or icmp_eq and whether the 
9400                 // true or false val is the zero.
9401                 bool ShouldNotVal = !TrueValC->isZero();
9402                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9403                 Value *V = ICA;
9404                 if (ShouldNotVal)
9405                   V = InsertNewInstBefore(BinaryOperator::Create(
9406                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9407                 return ReplaceInstUsesWith(SI, V);
9408               }
9409       }
9410     }
9411
9412   // See if we are selecting two values based on a comparison of the two values.
9413   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9414     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9415       // Transform (X == Y) ? X : Y  -> Y
9416       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9417         // This is not safe in general for floating point:  
9418         // consider X== -0, Y== +0.
9419         // It becomes safe if either operand is a nonzero constant.
9420         ConstantFP *CFPt, *CFPf;
9421         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9422               !CFPt->getValueAPF().isZero()) ||
9423             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9424              !CFPf->getValueAPF().isZero()))
9425         return ReplaceInstUsesWith(SI, FalseVal);
9426       }
9427       // Transform (X != Y) ? X : Y  -> X
9428       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9429         return ReplaceInstUsesWith(SI, TrueVal);
9430       // NOTE: if we wanted to, this is where to detect MIN/MAX
9431
9432     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9433       // Transform (X == Y) ? Y : X  -> X
9434       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9435         // This is not safe in general for floating point:  
9436         // consider X== -0, Y== +0.
9437         // It becomes safe if either operand is a nonzero constant.
9438         ConstantFP *CFPt, *CFPf;
9439         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9440               !CFPt->getValueAPF().isZero()) ||
9441             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9442              !CFPf->getValueAPF().isZero()))
9443           return ReplaceInstUsesWith(SI, FalseVal);
9444       }
9445       // Transform (X != Y) ? Y : X  -> Y
9446       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9447         return ReplaceInstUsesWith(SI, TrueVal);
9448       // NOTE: if we wanted to, this is where to detect MIN/MAX
9449     }
9450     // NOTE: if we wanted to, this is where to detect ABS
9451   }
9452
9453   // See if we are selecting two values based on a comparison of the two values.
9454   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9455     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9456       return Result;
9457
9458   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9459     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9460       if (TI->hasOneUse() && FI->hasOneUse()) {
9461         Instruction *AddOp = 0, *SubOp = 0;
9462
9463         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9464         if (TI->getOpcode() == FI->getOpcode())
9465           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9466             return IV;
9467
9468         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9469         // even legal for FP.
9470         if ((TI->getOpcode() == Instruction::Sub &&
9471              FI->getOpcode() == Instruction::Add) ||
9472             (TI->getOpcode() == Instruction::FSub &&
9473              FI->getOpcode() == Instruction::FAdd)) {
9474           AddOp = FI; SubOp = TI;
9475         } else if ((FI->getOpcode() == Instruction::Sub &&
9476                     TI->getOpcode() == Instruction::Add) ||
9477                    (FI->getOpcode() == Instruction::FSub &&
9478                     TI->getOpcode() == Instruction::FAdd)) {
9479           AddOp = TI; SubOp = FI;
9480         }
9481
9482         if (AddOp) {
9483           Value *OtherAddOp = 0;
9484           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9485             OtherAddOp = AddOp->getOperand(1);
9486           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9487             OtherAddOp = AddOp->getOperand(0);
9488           }
9489
9490           if (OtherAddOp) {
9491             // So at this point we know we have (Y -> OtherAddOp):
9492             //        select C, (add X, Y), (sub X, Z)
9493             Value *NegVal;  // Compute -Z
9494             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9495               NegVal = ConstantExpr::getNeg(C);
9496             } else {
9497               NegVal = InsertNewInstBefore(
9498                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9499             }
9500
9501             Value *NewTrueOp = OtherAddOp;
9502             Value *NewFalseOp = NegVal;
9503             if (AddOp != TI)
9504               std::swap(NewTrueOp, NewFalseOp);
9505             Instruction *NewSel =
9506               SelectInst::Create(CondVal, NewTrueOp,
9507                                  NewFalseOp, SI.getName() + ".p");
9508
9509             NewSel = InsertNewInstBefore(NewSel, SI);
9510             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9511           }
9512         }
9513       }
9514
9515   // See if we can fold the select into one of our operands.
9516   if (SI.getType()->isInteger()) {
9517     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9518     if (FoldI)
9519       return FoldI;
9520   }
9521
9522   if (BinaryOperator::isNot(CondVal)) {
9523     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9524     SI.setOperand(1, FalseVal);
9525     SI.setOperand(2, TrueVal);
9526     return &SI;
9527   }
9528
9529   return 0;
9530 }
9531
9532 /// EnforceKnownAlignment - If the specified pointer points to an object that
9533 /// we control, modify the object's alignment to PrefAlign. This isn't
9534 /// often possible though. If alignment is important, a more reliable approach
9535 /// is to simply align all global variables and allocation instructions to
9536 /// their preferred alignment from the beginning.
9537 ///
9538 static unsigned EnforceKnownAlignment(Value *V,
9539                                       unsigned Align, unsigned PrefAlign) {
9540
9541   User *U = dyn_cast<User>(V);
9542   if (!U) return Align;
9543
9544   switch (getOpcode(U)) {
9545   default: break;
9546   case Instruction::BitCast:
9547     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9548   case Instruction::GetElementPtr: {
9549     // If all indexes are zero, it is just the alignment of the base pointer.
9550     bool AllZeroOperands = true;
9551     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9552       if (!isa<Constant>(*i) ||
9553           !cast<Constant>(*i)->isNullValue()) {
9554         AllZeroOperands = false;
9555         break;
9556       }
9557
9558     if (AllZeroOperands) {
9559       // Treat this like a bitcast.
9560       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9561     }
9562     break;
9563   }
9564   }
9565
9566   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9567     // If there is a large requested alignment and we can, bump up the alignment
9568     // of the global.
9569     if (!GV->isDeclaration()) {
9570       if (GV->getAlignment() >= PrefAlign)
9571         Align = GV->getAlignment();
9572       else {
9573         GV->setAlignment(PrefAlign);
9574         Align = PrefAlign;
9575       }
9576     }
9577   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9578     // If there is a requested alignment and if this is an alloca, round up.  We
9579     // don't do this for malloc, because some systems can't respect the request.
9580     if (isa<AllocaInst>(AI)) {
9581       if (AI->getAlignment() >= PrefAlign)
9582         Align = AI->getAlignment();
9583       else {
9584         AI->setAlignment(PrefAlign);
9585         Align = PrefAlign;
9586       }
9587     }
9588   }
9589
9590   return Align;
9591 }
9592
9593 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9594 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9595 /// and it is more than the alignment of the ultimate object, see if we can
9596 /// increase the alignment of the ultimate object, making this check succeed.
9597 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9598                                                   unsigned PrefAlign) {
9599   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9600                       sizeof(PrefAlign) * CHAR_BIT;
9601   APInt Mask = APInt::getAllOnesValue(BitWidth);
9602   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9603   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9604   unsigned TrailZ = KnownZero.countTrailingOnes();
9605   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9606
9607   if (PrefAlign > Align)
9608     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9609   
9610     // We don't need to make any adjustment.
9611   return Align;
9612 }
9613
9614 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9615   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9616   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9617   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9618   unsigned CopyAlign = MI->getAlignment();
9619
9620   if (CopyAlign < MinAlign) {
9621     MI->setAlignment(MinAlign);
9622     return MI;
9623   }
9624   
9625   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9626   // load/store.
9627   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9628   if (MemOpLength == 0) return 0;
9629   
9630   // Source and destination pointer types are always "i8*" for intrinsic.  See
9631   // if the size is something we can handle with a single primitive load/store.
9632   // A single load+store correctly handles overlapping memory in the memmove
9633   // case.
9634   unsigned Size = MemOpLength->getZExtValue();
9635   if (Size == 0) return MI;  // Delete this mem transfer.
9636   
9637   if (Size > 8 || (Size&(Size-1)))
9638     return 0;  // If not 1/2/4/8 bytes, exit.
9639   
9640   // Use an integer load+store unless we can find something better.
9641   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9642   
9643   // Memcpy forces the use of i8* for the source and destination.  That means
9644   // that if you're using memcpy to move one double around, you'll get a cast
9645   // from double* to i8*.  We'd much rather use a double load+store rather than
9646   // an i64 load+store, here because this improves the odds that the source or
9647   // dest address will be promotable.  See if we can find a better type than the
9648   // integer datatype.
9649   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9650     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9651     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9652       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9653       // down through these levels if so.
9654       while (!SrcETy->isSingleValueType()) {
9655         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9656           if (STy->getNumElements() == 1)
9657             SrcETy = STy->getElementType(0);
9658           else
9659             break;
9660         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9661           if (ATy->getNumElements() == 1)
9662             SrcETy = ATy->getElementType();
9663           else
9664             break;
9665         } else
9666           break;
9667       }
9668       
9669       if (SrcETy->isSingleValueType())
9670         NewPtrTy = PointerType::getUnqual(SrcETy);
9671     }
9672   }
9673   
9674   
9675   // If the memcpy/memmove provides better alignment info than we can
9676   // infer, use it.
9677   SrcAlign = std::max(SrcAlign, CopyAlign);
9678   DstAlign = std::max(DstAlign, CopyAlign);
9679   
9680   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9681   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9682   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9683   InsertNewInstBefore(L, *MI);
9684   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9685
9686   // Set the size of the copy to 0, it will be deleted on the next iteration.
9687   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9688   return MI;
9689 }
9690
9691 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9692   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9693   if (MI->getAlignment() < Alignment) {
9694     MI->setAlignment(Alignment);
9695     return MI;
9696   }
9697   
9698   // Extract the length and alignment and fill if they are constant.
9699   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9700   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9701   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9702     return 0;
9703   uint64_t Len = LenC->getZExtValue();
9704   Alignment = MI->getAlignment();
9705   
9706   // If the length is zero, this is a no-op
9707   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9708   
9709   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9710   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9711     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9712     
9713     Value *Dest = MI->getDest();
9714     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9715
9716     // Alignment 0 is identity for alignment 1 for memset, but not store.
9717     if (Alignment == 0) Alignment = 1;
9718     
9719     // Extract the fill value and store.
9720     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9721     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9722                                       Alignment), *MI);
9723     
9724     // Set the size of the copy to 0, it will be deleted on the next iteration.
9725     MI->setLength(Constant::getNullValue(LenC->getType()));
9726     return MI;
9727   }
9728
9729   return 0;
9730 }
9731
9732
9733 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9734 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9735 /// the heavy lifting.
9736 ///
9737 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9738   // If the caller function is nounwind, mark the call as nounwind, even if the
9739   // callee isn't.
9740   if (CI.getParent()->getParent()->doesNotThrow() &&
9741       !CI.doesNotThrow()) {
9742     CI.setDoesNotThrow();
9743     return &CI;
9744   }
9745   
9746   
9747   
9748   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9749   if (!II) return visitCallSite(&CI);
9750   
9751   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9752   // visitCallSite.
9753   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9754     bool Changed = false;
9755
9756     // memmove/cpy/set of zero bytes is a noop.
9757     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9758       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9759
9760       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9761         if (CI->getZExtValue() == 1) {
9762           // Replace the instruction with just byte operations.  We would
9763           // transform other cases to loads/stores, but we don't know if
9764           // alignment is sufficient.
9765         }
9766     }
9767
9768     // If we have a memmove and the source operation is a constant global,
9769     // then the source and dest pointers can't alias, so we can change this
9770     // into a call to memcpy.
9771     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9772       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9773         if (GVSrc->isConstant()) {
9774           Module *M = CI.getParent()->getParent()->getParent();
9775           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9776           const Type *Tys[1];
9777           Tys[0] = CI.getOperand(3)->getType();
9778           CI.setOperand(0, 
9779                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9780           Changed = true;
9781         }
9782
9783       // memmove(x,x,size) -> noop.
9784       if (MMI->getSource() == MMI->getDest())
9785         return EraseInstFromFunction(CI);
9786     }
9787
9788     // If we can determine a pointer alignment that is bigger than currently
9789     // set, update the alignment.
9790     if (isa<MemTransferInst>(MI)) {
9791       if (Instruction *I = SimplifyMemTransfer(MI))
9792         return I;
9793     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9794       if (Instruction *I = SimplifyMemSet(MSI))
9795         return I;
9796     }
9797           
9798     if (Changed) return II;
9799   }
9800   
9801   switch (II->getIntrinsicID()) {
9802   default: break;
9803   case Intrinsic::bswap:
9804     // bswap(bswap(x)) -> x
9805     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9806       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9807         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9808     break;
9809   case Intrinsic::ppc_altivec_lvx:
9810   case Intrinsic::ppc_altivec_lvxl:
9811   case Intrinsic::x86_sse_loadu_ps:
9812   case Intrinsic::x86_sse2_loadu_pd:
9813   case Intrinsic::x86_sse2_loadu_dq:
9814     // Turn PPC lvx     -> load if the pointer is known aligned.
9815     // Turn X86 loadups -> load if the pointer is known aligned.
9816     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9817       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9818                                        PointerType::getUnqual(II->getType()),
9819                                        CI);
9820       return new LoadInst(Ptr);
9821     }
9822     break;
9823   case Intrinsic::ppc_altivec_stvx:
9824   case Intrinsic::ppc_altivec_stvxl:
9825     // Turn stvx -> store if the pointer is known aligned.
9826     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9827       const Type *OpPtrTy = 
9828         PointerType::getUnqual(II->getOperand(1)->getType());
9829       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9830       return new StoreInst(II->getOperand(1), Ptr);
9831     }
9832     break;
9833   case Intrinsic::x86_sse_storeu_ps:
9834   case Intrinsic::x86_sse2_storeu_pd:
9835   case Intrinsic::x86_sse2_storeu_dq:
9836     // Turn X86 storeu -> store if the pointer is known aligned.
9837     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9838       const Type *OpPtrTy = 
9839         PointerType::getUnqual(II->getOperand(2)->getType());
9840       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9841       return new StoreInst(II->getOperand(2), Ptr);
9842     }
9843     break;
9844     
9845   case Intrinsic::x86_sse_cvttss2si: {
9846     // These intrinsics only demands the 0th element of its input vector.  If
9847     // we can simplify the input based on that, do so now.
9848     unsigned VWidth =
9849       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9850     APInt DemandedElts(VWidth, 1);
9851     APInt UndefElts(VWidth, 0);
9852     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9853                                               UndefElts)) {
9854       II->setOperand(1, V);
9855       return II;
9856     }
9857     break;
9858   }
9859     
9860   case Intrinsic::ppc_altivec_vperm:
9861     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9862     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9863       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9864       
9865       // Check that all of the elements are integer constants or undefs.
9866       bool AllEltsOk = true;
9867       for (unsigned i = 0; i != 16; ++i) {
9868         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9869             !isa<UndefValue>(Mask->getOperand(i))) {
9870           AllEltsOk = false;
9871           break;
9872         }
9873       }
9874       
9875       if (AllEltsOk) {
9876         // Cast the input vectors to byte vectors.
9877         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9878         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9879         Value *Result = UndefValue::get(Op0->getType());
9880         
9881         // Only extract each element once.
9882         Value *ExtractedElts[32];
9883         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9884         
9885         for (unsigned i = 0; i != 16; ++i) {
9886           if (isa<UndefValue>(Mask->getOperand(i)))
9887             continue;
9888           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9889           Idx &= 31;  // Match the hardware behavior.
9890           
9891           if (ExtractedElts[Idx] == 0) {
9892             Instruction *Elt = 
9893               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9894             InsertNewInstBefore(Elt, CI);
9895             ExtractedElts[Idx] = Elt;
9896           }
9897         
9898           // Insert this value into the result vector.
9899           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9900                                              i, "tmp");
9901           InsertNewInstBefore(cast<Instruction>(Result), CI);
9902         }
9903         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9904       }
9905     }
9906     break;
9907
9908   case Intrinsic::stackrestore: {
9909     // If the save is right next to the restore, remove the restore.  This can
9910     // happen when variable allocas are DCE'd.
9911     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9912       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9913         BasicBlock::iterator BI = SS;
9914         if (&*++BI == II)
9915           return EraseInstFromFunction(CI);
9916       }
9917     }
9918     
9919     // Scan down this block to see if there is another stack restore in the
9920     // same block without an intervening call/alloca.
9921     BasicBlock::iterator BI = II;
9922     TerminatorInst *TI = II->getParent()->getTerminator();
9923     bool CannotRemove = false;
9924     for (++BI; &*BI != TI; ++BI) {
9925       if (isa<AllocaInst>(BI)) {
9926         CannotRemove = true;
9927         break;
9928       }
9929       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9930         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9931           // If there is a stackrestore below this one, remove this one.
9932           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9933             return EraseInstFromFunction(CI);
9934           // Otherwise, ignore the intrinsic.
9935         } else {
9936           // If we found a non-intrinsic call, we can't remove the stack
9937           // restore.
9938           CannotRemove = true;
9939           break;
9940         }
9941       }
9942     }
9943     
9944     // If the stack restore is in a return/unwind block and if there are no
9945     // allocas or calls between the restore and the return, nuke the restore.
9946     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9947       return EraseInstFromFunction(CI);
9948     break;
9949   }
9950   }
9951
9952   return visitCallSite(II);
9953 }
9954
9955 // InvokeInst simplification
9956 //
9957 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9958   return visitCallSite(&II);
9959 }
9960
9961 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9962 /// passed through the varargs area, we can eliminate the use of the cast.
9963 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9964                                          const CastInst * const CI,
9965                                          const TargetData * const TD,
9966                                          const int ix) {
9967   if (!CI->isLosslessCast())
9968     return false;
9969
9970   // The size of ByVal arguments is derived from the type, so we
9971   // can't change to a type with a different size.  If the size were
9972   // passed explicitly we could avoid this check.
9973   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9974     return true;
9975
9976   const Type* SrcTy = 
9977             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9978   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9979   if (!SrcTy->isSized() || !DstTy->isSized())
9980     return false;
9981   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9982     return false;
9983   return true;
9984 }
9985
9986 // visitCallSite - Improvements for call and invoke instructions.
9987 //
9988 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9989   bool Changed = false;
9990
9991   // If the callee is a constexpr cast of a function, attempt to move the cast
9992   // to the arguments of the call/invoke.
9993   if (transformConstExprCastCall(CS)) return 0;
9994
9995   Value *Callee = CS.getCalledValue();
9996
9997   if (Function *CalleeF = dyn_cast<Function>(Callee))
9998     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9999       Instruction *OldCall = CS.getInstruction();
10000       // If the call and callee calling conventions don't match, this call must
10001       // be unreachable, as the call is undefined.
10002       new StoreInst(ConstantInt::getTrue(),
10003                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
10004                                     OldCall);
10005       if (!OldCall->use_empty())
10006         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10007       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10008         return EraseInstFromFunction(*OldCall);
10009       return 0;
10010     }
10011
10012   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10013     // This instruction is not reachable, just remove it.  We insert a store to
10014     // undef so that we know that this code is not reachable, despite the fact
10015     // that we can't modify the CFG here.
10016     new StoreInst(ConstantInt::getTrue(),
10017                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
10018                   CS.getInstruction());
10019
10020     if (!CS.getInstruction()->use_empty())
10021       CS.getInstruction()->
10022         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10023
10024     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10025       // Don't break the CFG, insert a dummy cond branch.
10026       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10027                          ConstantInt::getTrue(), II);
10028     }
10029     return EraseInstFromFunction(*CS.getInstruction());
10030   }
10031
10032   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10033     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10034       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10035         return transformCallThroughTrampoline(CS);
10036
10037   const PointerType *PTy = cast<PointerType>(Callee->getType());
10038   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10039   if (FTy->isVarArg()) {
10040     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10041     // See if we can optimize any arguments passed through the varargs area of
10042     // the call.
10043     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10044            E = CS.arg_end(); I != E; ++I, ++ix) {
10045       CastInst *CI = dyn_cast<CastInst>(*I);
10046       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10047         *I = CI->getOperand(0);
10048         Changed = true;
10049       }
10050     }
10051   }
10052
10053   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10054     // Inline asm calls cannot throw - mark them 'nounwind'.
10055     CS.setDoesNotThrow();
10056     Changed = true;
10057   }
10058
10059   return Changed ? CS.getInstruction() : 0;
10060 }
10061
10062 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10063 // attempt to move the cast to the arguments of the call/invoke.
10064 //
10065 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10066   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10067   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10068   if (CE->getOpcode() != Instruction::BitCast || 
10069       !isa<Function>(CE->getOperand(0)))
10070     return false;
10071   Function *Callee = cast<Function>(CE->getOperand(0));
10072   Instruction *Caller = CS.getInstruction();
10073   const AttrListPtr &CallerPAL = CS.getAttributes();
10074
10075   // Okay, this is a cast from a function to a different type.  Unless doing so
10076   // would cause a type conversion of one of our arguments, change this call to
10077   // be a direct call with arguments casted to the appropriate types.
10078   //
10079   const FunctionType *FT = Callee->getFunctionType();
10080   const Type *OldRetTy = Caller->getType();
10081   const Type *NewRetTy = FT->getReturnType();
10082
10083   if (isa<StructType>(NewRetTy))
10084     return false; // TODO: Handle multiple return values.
10085
10086   // Check to see if we are changing the return type...
10087   if (OldRetTy != NewRetTy) {
10088     if (Callee->isDeclaration() &&
10089         // Conversion is ok if changing from one pointer type to another or from
10090         // a pointer to an integer of the same size.
10091         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10092           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10093       return false;   // Cannot transform this return value.
10094
10095     if (!Caller->use_empty() &&
10096         // void -> non-void is handled specially
10097         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10098       return false;   // Cannot transform this return value.
10099
10100     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10101       Attributes RAttrs = CallerPAL.getRetAttributes();
10102       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10103         return false;   // Attribute not compatible with transformed value.
10104     }
10105
10106     // If the callsite is an invoke instruction, and the return value is used by
10107     // a PHI node in a successor, we cannot change the return type of the call
10108     // because there is no place to put the cast instruction (without breaking
10109     // the critical edge).  Bail out in this case.
10110     if (!Caller->use_empty())
10111       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10112         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10113              UI != E; ++UI)
10114           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10115             if (PN->getParent() == II->getNormalDest() ||
10116                 PN->getParent() == II->getUnwindDest())
10117               return false;
10118   }
10119
10120   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10121   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10122
10123   CallSite::arg_iterator AI = CS.arg_begin();
10124   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10125     const Type *ParamTy = FT->getParamType(i);
10126     const Type *ActTy = (*AI)->getType();
10127
10128     if (!CastInst::isCastable(ActTy, ParamTy))
10129       return false;   // Cannot transform this parameter value.
10130
10131     if (CallerPAL.getParamAttributes(i + 1) 
10132         & Attribute::typeIncompatible(ParamTy))
10133       return false;   // Attribute not compatible with transformed value.
10134
10135     // Converting from one pointer type to another or between a pointer and an
10136     // integer of the same size is safe even if we do not have a body.
10137     bool isConvertible = ActTy == ParamTy ||
10138       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10139        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10140     if (Callee->isDeclaration() && !isConvertible) return false;
10141   }
10142
10143   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10144       Callee->isDeclaration())
10145     return false;   // Do not delete arguments unless we have a function body.
10146
10147   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10148       !CallerPAL.isEmpty())
10149     // In this case we have more arguments than the new function type, but we
10150     // won't be dropping them.  Check that these extra arguments have attributes
10151     // that are compatible with being a vararg call argument.
10152     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10153       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10154         break;
10155       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10156       if (PAttrs & Attribute::VarArgsIncompatible)
10157         return false;
10158     }
10159
10160   // Okay, we decided that this is a safe thing to do: go ahead and start
10161   // inserting cast instructions as necessary...
10162   std::vector<Value*> Args;
10163   Args.reserve(NumActualArgs);
10164   SmallVector<AttributeWithIndex, 8> attrVec;
10165   attrVec.reserve(NumCommonArgs);
10166
10167   // Get any return attributes.
10168   Attributes RAttrs = CallerPAL.getRetAttributes();
10169
10170   // If the return value is not being used, the type may not be compatible
10171   // with the existing attributes.  Wipe out any problematic attributes.
10172   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10173
10174   // Add the new return attributes.
10175   if (RAttrs)
10176     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10177
10178   AI = CS.arg_begin();
10179   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10180     const Type *ParamTy = FT->getParamType(i);
10181     if ((*AI)->getType() == ParamTy) {
10182       Args.push_back(*AI);
10183     } else {
10184       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10185           false, ParamTy, false);
10186       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10187       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10188     }
10189
10190     // Add any parameter attributes.
10191     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10192       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10193   }
10194
10195   // If the function takes more arguments than the call was taking, add them
10196   // now...
10197   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10198     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10199
10200   // If we are removing arguments to the function, emit an obnoxious warning...
10201   if (FT->getNumParams() < NumActualArgs) {
10202     if (!FT->isVarArg()) {
10203       cerr << "WARNING: While resolving call to function '"
10204            << Callee->getName() << "' arguments were dropped!\n";
10205     } else {
10206       // Add all of the arguments in their promoted form to the arg list...
10207       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10208         const Type *PTy = getPromotedType((*AI)->getType());
10209         if (PTy != (*AI)->getType()) {
10210           // Must promote to pass through va_arg area!
10211           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10212                                                                 PTy, false);
10213           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10214           InsertNewInstBefore(Cast, *Caller);
10215           Args.push_back(Cast);
10216         } else {
10217           Args.push_back(*AI);
10218         }
10219
10220         // Add any parameter attributes.
10221         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10222           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10223       }
10224     }
10225   }
10226
10227   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10228     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10229
10230   if (NewRetTy == Type::VoidTy)
10231     Caller->setName("");   // Void type should not have a name.
10232
10233   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10234
10235   Instruction *NC;
10236   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10237     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10238                             Args.begin(), Args.end(),
10239                             Caller->getName(), Caller);
10240     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10241     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10242   } else {
10243     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10244                           Caller->getName(), Caller);
10245     CallInst *CI = cast<CallInst>(Caller);
10246     if (CI->isTailCall())
10247       cast<CallInst>(NC)->setTailCall();
10248     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10249     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10250   }
10251
10252   // Insert a cast of the return type as necessary.
10253   Value *NV = NC;
10254   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10255     if (NV->getType() != Type::VoidTy) {
10256       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10257                                                             OldRetTy, false);
10258       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10259
10260       // If this is an invoke instruction, we should insert it after the first
10261       // non-phi, instruction in the normal successor block.
10262       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10263         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10264         InsertNewInstBefore(NC, *I);
10265       } else {
10266         // Otherwise, it's a call, just insert cast right after the call instr
10267         InsertNewInstBefore(NC, *Caller);
10268       }
10269       AddUsersToWorkList(*Caller);
10270     } else {
10271       NV = UndefValue::get(Caller->getType());
10272     }
10273   }
10274
10275   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10276     Caller->replaceAllUsesWith(NV);
10277   Caller->eraseFromParent();
10278   RemoveFromWorkList(Caller);
10279   return true;
10280 }
10281
10282 // transformCallThroughTrampoline - Turn a call to a function created by the
10283 // init_trampoline intrinsic into a direct call to the underlying function.
10284 //
10285 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10286   Value *Callee = CS.getCalledValue();
10287   const PointerType *PTy = cast<PointerType>(Callee->getType());
10288   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10289   const AttrListPtr &Attrs = CS.getAttributes();
10290
10291   // If the call already has the 'nest' attribute somewhere then give up -
10292   // otherwise 'nest' would occur twice after splicing in the chain.
10293   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10294     return 0;
10295
10296   IntrinsicInst *Tramp =
10297     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10298
10299   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10300   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10301   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10302
10303   const AttrListPtr &NestAttrs = NestF->getAttributes();
10304   if (!NestAttrs.isEmpty()) {
10305     unsigned NestIdx = 1;
10306     const Type *NestTy = 0;
10307     Attributes NestAttr = Attribute::None;
10308
10309     // Look for a parameter marked with the 'nest' attribute.
10310     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10311          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10312       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10313         // Record the parameter type and any other attributes.
10314         NestTy = *I;
10315         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10316         break;
10317       }
10318
10319     if (NestTy) {
10320       Instruction *Caller = CS.getInstruction();
10321       std::vector<Value*> NewArgs;
10322       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10323
10324       SmallVector<AttributeWithIndex, 8> NewAttrs;
10325       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10326
10327       // Insert the nest argument into the call argument list, which may
10328       // mean appending it.  Likewise for attributes.
10329
10330       // Add any result attributes.
10331       if (Attributes Attr = Attrs.getRetAttributes())
10332         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10333
10334       {
10335         unsigned Idx = 1;
10336         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10337         do {
10338           if (Idx == NestIdx) {
10339             // Add the chain argument and attributes.
10340             Value *NestVal = Tramp->getOperand(3);
10341             if (NestVal->getType() != NestTy)
10342               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10343             NewArgs.push_back(NestVal);
10344             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10345           }
10346
10347           if (I == E)
10348             break;
10349
10350           // Add the original argument and attributes.
10351           NewArgs.push_back(*I);
10352           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10353             NewAttrs.push_back
10354               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10355
10356           ++Idx, ++I;
10357         } while (1);
10358       }
10359
10360       // Add any function attributes.
10361       if (Attributes Attr = Attrs.getFnAttributes())
10362         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10363
10364       // The trampoline may have been bitcast to a bogus type (FTy).
10365       // Handle this by synthesizing a new function type, equal to FTy
10366       // with the chain parameter inserted.
10367
10368       std::vector<const Type*> NewTypes;
10369       NewTypes.reserve(FTy->getNumParams()+1);
10370
10371       // Insert the chain's type into the list of parameter types, which may
10372       // mean appending it.
10373       {
10374         unsigned Idx = 1;
10375         FunctionType::param_iterator I = FTy->param_begin(),
10376           E = FTy->param_end();
10377
10378         do {
10379           if (Idx == NestIdx)
10380             // Add the chain's type.
10381             NewTypes.push_back(NestTy);
10382
10383           if (I == E)
10384             break;
10385
10386           // Add the original type.
10387           NewTypes.push_back(*I);
10388
10389           ++Idx, ++I;
10390         } while (1);
10391       }
10392
10393       // Replace the trampoline call with a direct call.  Let the generic
10394       // code sort out any function type mismatches.
10395       FunctionType *NewFTy =
10396         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
10397       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10398         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
10399       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10400
10401       Instruction *NewCaller;
10402       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10403         NewCaller = InvokeInst::Create(NewCallee,
10404                                        II->getNormalDest(), II->getUnwindDest(),
10405                                        NewArgs.begin(), NewArgs.end(),
10406                                        Caller->getName(), Caller);
10407         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10408         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10409       } else {
10410         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10411                                      Caller->getName(), Caller);
10412         if (cast<CallInst>(Caller)->isTailCall())
10413           cast<CallInst>(NewCaller)->setTailCall();
10414         cast<CallInst>(NewCaller)->
10415           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10416         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10417       }
10418       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10419         Caller->replaceAllUsesWith(NewCaller);
10420       Caller->eraseFromParent();
10421       RemoveFromWorkList(Caller);
10422       return 0;
10423     }
10424   }
10425
10426   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10427   // parameter, there is no need to adjust the argument list.  Let the generic
10428   // code sort out any function type mismatches.
10429   Constant *NewCallee =
10430     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10431   CS.setCalledFunction(NewCallee);
10432   return CS.getInstruction();
10433 }
10434
10435 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10436 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10437 /// and a single binop.
10438 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10439   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10440   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10441   unsigned Opc = FirstInst->getOpcode();
10442   Value *LHSVal = FirstInst->getOperand(0);
10443   Value *RHSVal = FirstInst->getOperand(1);
10444     
10445   const Type *LHSType = LHSVal->getType();
10446   const Type *RHSType = RHSVal->getType();
10447   
10448   // Scan to see if all operands are the same opcode, all have one use, and all
10449   // kill their operands (i.e. the operands have one use).
10450   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10451     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10452     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10453         // Verify type of the LHS matches so we don't fold cmp's of different
10454         // types or GEP's with different index types.
10455         I->getOperand(0)->getType() != LHSType ||
10456         I->getOperand(1)->getType() != RHSType)
10457       return 0;
10458
10459     // If they are CmpInst instructions, check their predicates
10460     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10461       if (cast<CmpInst>(I)->getPredicate() !=
10462           cast<CmpInst>(FirstInst)->getPredicate())
10463         return 0;
10464     
10465     // Keep track of which operand needs a phi node.
10466     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10467     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10468   }
10469   
10470   // Otherwise, this is safe to transform!
10471   
10472   Value *InLHS = FirstInst->getOperand(0);
10473   Value *InRHS = FirstInst->getOperand(1);
10474   PHINode *NewLHS = 0, *NewRHS = 0;
10475   if (LHSVal == 0) {
10476     NewLHS = PHINode::Create(LHSType,
10477                              FirstInst->getOperand(0)->getName() + ".pn");
10478     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10479     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10480     InsertNewInstBefore(NewLHS, PN);
10481     LHSVal = NewLHS;
10482   }
10483   
10484   if (RHSVal == 0) {
10485     NewRHS = PHINode::Create(RHSType,
10486                              FirstInst->getOperand(1)->getName() + ".pn");
10487     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10488     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10489     InsertNewInstBefore(NewRHS, PN);
10490     RHSVal = NewRHS;
10491   }
10492   
10493   // Add all operands to the new PHIs.
10494   if (NewLHS || NewRHS) {
10495     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10496       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10497       if (NewLHS) {
10498         Value *NewInLHS = InInst->getOperand(0);
10499         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10500       }
10501       if (NewRHS) {
10502         Value *NewInRHS = InInst->getOperand(1);
10503         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10504       }
10505     }
10506   }
10507     
10508   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10509     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10510   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10511   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10512                          RHSVal);
10513 }
10514
10515 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10516   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10517   
10518   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10519                                         FirstInst->op_end());
10520   // This is true if all GEP bases are allocas and if all indices into them are
10521   // constants.
10522   bool AllBasePointersAreAllocas = true;
10523   
10524   // Scan to see if all operands are the same opcode, all have one use, and all
10525   // kill their operands (i.e. the operands have one use).
10526   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10527     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10528     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10529       GEP->getNumOperands() != FirstInst->getNumOperands())
10530       return 0;
10531
10532     // Keep track of whether or not all GEPs are of alloca pointers.
10533     if (AllBasePointersAreAllocas &&
10534         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10535          !GEP->hasAllConstantIndices()))
10536       AllBasePointersAreAllocas = false;
10537     
10538     // Compare the operand lists.
10539     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10540       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10541         continue;
10542       
10543       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10544       // if one of the PHIs has a constant for the index.  The index may be
10545       // substantially cheaper to compute for the constants, so making it a
10546       // variable index could pessimize the path.  This also handles the case
10547       // for struct indices, which must always be constant.
10548       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10549           isa<ConstantInt>(GEP->getOperand(op)))
10550         return 0;
10551       
10552       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10553         return 0;
10554       FixedOperands[op] = 0;  // Needs a PHI.
10555     }
10556   }
10557   
10558   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10559   // bother doing this transformation.  At best, this will just save a bit of
10560   // offset calculation, but all the predecessors will have to materialize the
10561   // stack address into a register anyway.  We'd actually rather *clone* the
10562   // load up into the predecessors so that we have a load of a gep of an alloca,
10563   // which can usually all be folded into the load.
10564   if (AllBasePointersAreAllocas)
10565     return 0;
10566   
10567   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10568   // that is variable.
10569   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10570   
10571   bool HasAnyPHIs = false;
10572   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10573     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10574     Value *FirstOp = FirstInst->getOperand(i);
10575     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10576                                      FirstOp->getName()+".pn");
10577     InsertNewInstBefore(NewPN, PN);
10578     
10579     NewPN->reserveOperandSpace(e);
10580     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10581     OperandPhis[i] = NewPN;
10582     FixedOperands[i] = NewPN;
10583     HasAnyPHIs = true;
10584   }
10585
10586   
10587   // Add all operands to the new PHIs.
10588   if (HasAnyPHIs) {
10589     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10590       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10591       BasicBlock *InBB = PN.getIncomingBlock(i);
10592       
10593       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10594         if (PHINode *OpPhi = OperandPhis[op])
10595           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10596     }
10597   }
10598   
10599   Value *Base = FixedOperands[0];
10600   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10601                                    FixedOperands.end());
10602 }
10603
10604
10605 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10606 /// sink the load out of the block that defines it.  This means that it must be
10607 /// obvious the value of the load is not changed from the point of the load to
10608 /// the end of the block it is in.
10609 ///
10610 /// Finally, it is safe, but not profitable, to sink a load targetting a
10611 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10612 /// to a register.
10613 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10614   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10615   
10616   for (++BBI; BBI != E; ++BBI)
10617     if (BBI->mayWriteToMemory())
10618       return false;
10619   
10620   // Check for non-address taken alloca.  If not address-taken already, it isn't
10621   // profitable to do this xform.
10622   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10623     bool isAddressTaken = false;
10624     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10625          UI != E; ++UI) {
10626       if (isa<LoadInst>(UI)) continue;
10627       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10628         // If storing TO the alloca, then the address isn't taken.
10629         if (SI->getOperand(1) == AI) continue;
10630       }
10631       isAddressTaken = true;
10632       break;
10633     }
10634     
10635     if (!isAddressTaken && AI->isStaticAlloca())
10636       return false;
10637   }
10638   
10639   // If this load is a load from a GEP with a constant offset from an alloca,
10640   // then we don't want to sink it.  In its present form, it will be
10641   // load [constant stack offset].  Sinking it will cause us to have to
10642   // materialize the stack addresses in each predecessor in a register only to
10643   // do a shared load from register in the successor.
10644   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10645     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10646       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10647         return false;
10648   
10649   return true;
10650 }
10651
10652
10653 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10654 // operator and they all are only used by the PHI, PHI together their
10655 // inputs, and do the operation once, to the result of the PHI.
10656 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10657   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10658
10659   // Scan the instruction, looking for input operations that can be folded away.
10660   // If all input operands to the phi are the same instruction (e.g. a cast from
10661   // the same type or "+42") we can pull the operation through the PHI, reducing
10662   // code size and simplifying code.
10663   Constant *ConstantOp = 0;
10664   const Type *CastSrcTy = 0;
10665   bool isVolatile = false;
10666   if (isa<CastInst>(FirstInst)) {
10667     CastSrcTy = FirstInst->getOperand(0)->getType();
10668   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10669     // Can fold binop, compare or shift here if the RHS is a constant, 
10670     // otherwise call FoldPHIArgBinOpIntoPHI.
10671     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10672     if (ConstantOp == 0)
10673       return FoldPHIArgBinOpIntoPHI(PN);
10674   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10675     isVolatile = LI->isVolatile();
10676     // We can't sink the load if the loaded value could be modified between the
10677     // load and the PHI.
10678     if (LI->getParent() != PN.getIncomingBlock(0) ||
10679         !isSafeAndProfitableToSinkLoad(LI))
10680       return 0;
10681     
10682     // If the PHI is of volatile loads and the load block has multiple
10683     // successors, sinking it would remove a load of the volatile value from
10684     // the path through the other successor.
10685     if (isVolatile &&
10686         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10687       return 0;
10688     
10689   } else if (isa<GetElementPtrInst>(FirstInst)) {
10690     return FoldPHIArgGEPIntoPHI(PN);
10691   } else {
10692     return 0;  // Cannot fold this operation.
10693   }
10694
10695   // Check to see if all arguments are the same operation.
10696   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10697     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10698     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10699     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10700       return 0;
10701     if (CastSrcTy) {
10702       if (I->getOperand(0)->getType() != CastSrcTy)
10703         return 0;  // Cast operation must match.
10704     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10705       // We can't sink the load if the loaded value could be modified between 
10706       // the load and the PHI.
10707       if (LI->isVolatile() != isVolatile ||
10708           LI->getParent() != PN.getIncomingBlock(i) ||
10709           !isSafeAndProfitableToSinkLoad(LI))
10710         return 0;
10711       
10712       // If the PHI is of volatile loads and the load block has multiple
10713       // successors, sinking it would remove a load of the volatile value from
10714       // the path through the other successor.
10715       if (isVolatile &&
10716           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10717         return 0;
10718       
10719     } else if (I->getOperand(1) != ConstantOp) {
10720       return 0;
10721     }
10722   }
10723
10724   // Okay, they are all the same operation.  Create a new PHI node of the
10725   // correct type, and PHI together all of the LHS's of the instructions.
10726   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10727                                    PN.getName()+".in");
10728   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10729
10730   Value *InVal = FirstInst->getOperand(0);
10731   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10732
10733   // Add all operands to the new PHI.
10734   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10735     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10736     if (NewInVal != InVal)
10737       InVal = 0;
10738     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10739   }
10740
10741   Value *PhiVal;
10742   if (InVal) {
10743     // The new PHI unions all of the same values together.  This is really
10744     // common, so we handle it intelligently here for compile-time speed.
10745     PhiVal = InVal;
10746     delete NewPN;
10747   } else {
10748     InsertNewInstBefore(NewPN, PN);
10749     PhiVal = NewPN;
10750   }
10751
10752   // Insert and return the new operation.
10753   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10754     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10755   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10756     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10757   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10758     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10759                            PhiVal, ConstantOp);
10760   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10761   
10762   // If this was a volatile load that we are merging, make sure to loop through
10763   // and mark all the input loads as non-volatile.  If we don't do this, we will
10764   // insert a new volatile load and the old ones will not be deletable.
10765   if (isVolatile)
10766     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10767       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10768   
10769   return new LoadInst(PhiVal, "", isVolatile);
10770 }
10771
10772 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10773 /// that is dead.
10774 static bool DeadPHICycle(PHINode *PN,
10775                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10776   if (PN->use_empty()) return true;
10777   if (!PN->hasOneUse()) return false;
10778
10779   // Remember this node, and if we find the cycle, return.
10780   if (!PotentiallyDeadPHIs.insert(PN))
10781     return true;
10782   
10783   // Don't scan crazily complex things.
10784   if (PotentiallyDeadPHIs.size() == 16)
10785     return false;
10786
10787   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10788     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10789
10790   return false;
10791 }
10792
10793 /// PHIsEqualValue - Return true if this phi node is always equal to
10794 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10795 ///   z = some value; x = phi (y, z); y = phi (x, z)
10796 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10797                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10798   // See if we already saw this PHI node.
10799   if (!ValueEqualPHIs.insert(PN))
10800     return true;
10801   
10802   // Don't scan crazily complex things.
10803   if (ValueEqualPHIs.size() == 16)
10804     return false;
10805  
10806   // Scan the operands to see if they are either phi nodes or are equal to
10807   // the value.
10808   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10809     Value *Op = PN->getIncomingValue(i);
10810     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10811       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10812         return false;
10813     } else if (Op != NonPhiInVal)
10814       return false;
10815   }
10816   
10817   return true;
10818 }
10819
10820
10821 // PHINode simplification
10822 //
10823 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10824   // If LCSSA is around, don't mess with Phi nodes
10825   if (MustPreserveLCSSA) return 0;
10826   
10827   if (Value *V = PN.hasConstantValue())
10828     return ReplaceInstUsesWith(PN, V);
10829
10830   // If all PHI operands are the same operation, pull them through the PHI,
10831   // reducing code size.
10832   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10833       isa<Instruction>(PN.getIncomingValue(1)) &&
10834       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10835       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10836       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10837       // than themselves more than once.
10838       PN.getIncomingValue(0)->hasOneUse())
10839     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10840       return Result;
10841
10842   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10843   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10844   // PHI)... break the cycle.
10845   if (PN.hasOneUse()) {
10846     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10847     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10848       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10849       PotentiallyDeadPHIs.insert(&PN);
10850       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10851         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10852     }
10853    
10854     // If this phi has a single use, and if that use just computes a value for
10855     // the next iteration of a loop, delete the phi.  This occurs with unused
10856     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10857     // common case here is good because the only other things that catch this
10858     // are induction variable analysis (sometimes) and ADCE, which is only run
10859     // late.
10860     if (PHIUser->hasOneUse() &&
10861         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10862         PHIUser->use_back() == &PN) {
10863       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10864     }
10865   }
10866
10867   // We sometimes end up with phi cycles that non-obviously end up being the
10868   // same value, for example:
10869   //   z = some value; x = phi (y, z); y = phi (x, z)
10870   // where the phi nodes don't necessarily need to be in the same block.  Do a
10871   // quick check to see if the PHI node only contains a single non-phi value, if
10872   // so, scan to see if the phi cycle is actually equal to that value.
10873   {
10874     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10875     // Scan for the first non-phi operand.
10876     while (InValNo != NumOperandVals && 
10877            isa<PHINode>(PN.getIncomingValue(InValNo)))
10878       ++InValNo;
10879
10880     if (InValNo != NumOperandVals) {
10881       Value *NonPhiInVal = PN.getOperand(InValNo);
10882       
10883       // Scan the rest of the operands to see if there are any conflicts, if so
10884       // there is no need to recursively scan other phis.
10885       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10886         Value *OpVal = PN.getIncomingValue(InValNo);
10887         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10888           break;
10889       }
10890       
10891       // If we scanned over all operands, then we have one unique value plus
10892       // phi values.  Scan PHI nodes to see if they all merge in each other or
10893       // the value.
10894       if (InValNo == NumOperandVals) {
10895         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10896         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10897           return ReplaceInstUsesWith(PN, NonPhiInVal);
10898       }
10899     }
10900   }
10901   return 0;
10902 }
10903
10904 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10905                                    Instruction *InsertPoint,
10906                                    InstCombiner *IC) {
10907   unsigned PtrSize = DTy->getScalarSizeInBits();
10908   unsigned VTySize = V->getType()->getScalarSizeInBits();
10909   // We must cast correctly to the pointer type. Ensure that we
10910   // sign extend the integer value if it is smaller as this is
10911   // used for address computation.
10912   Instruction::CastOps opcode = 
10913      (VTySize < PtrSize ? Instruction::SExt :
10914       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10915   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10916 }
10917
10918
10919 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10920   Value *PtrOp = GEP.getOperand(0);
10921   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10922   // If so, eliminate the noop.
10923   if (GEP.getNumOperands() == 1)
10924     return ReplaceInstUsesWith(GEP, PtrOp);
10925
10926   if (isa<UndefValue>(GEP.getOperand(0)))
10927     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10928
10929   bool HasZeroPointerIndex = false;
10930   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10931     HasZeroPointerIndex = C->isNullValue();
10932
10933   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10934     return ReplaceInstUsesWith(GEP, PtrOp);
10935
10936   // Eliminate unneeded casts for indices.
10937   bool MadeChange = false;
10938   
10939   gep_type_iterator GTI = gep_type_begin(GEP);
10940   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10941        i != e; ++i, ++GTI) {
10942     if (isa<SequentialType>(*GTI)) {
10943       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10944         if (CI->getOpcode() == Instruction::ZExt ||
10945             CI->getOpcode() == Instruction::SExt) {
10946           const Type *SrcTy = CI->getOperand(0)->getType();
10947           // We can eliminate a cast from i32 to i64 iff the target 
10948           // is a 32-bit pointer target.
10949           if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
10950             MadeChange = true;
10951             *i = CI->getOperand(0);
10952           }
10953         }
10954       }
10955       // If we are using a wider index than needed for this platform, shrink it
10956       // to what we need.  If narrower, sign-extend it to what we need.
10957       // If the incoming value needs a cast instruction,
10958       // insert it.  This explicit cast can make subsequent optimizations more
10959       // obvious.
10960       Value *Op = *i;
10961       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10962         if (Constant *C = dyn_cast<Constant>(Op)) {
10963           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10964           MadeChange = true;
10965         } else {
10966           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10967                                 GEP);
10968           *i = Op;
10969           MadeChange = true;
10970         }
10971       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10972         if (Constant *C = dyn_cast<Constant>(Op)) {
10973           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10974           MadeChange = true;
10975         } else {
10976           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10977                                 GEP);
10978           *i = Op;
10979           MadeChange = true;
10980         }
10981       }
10982     }
10983   }
10984   if (MadeChange) return &GEP;
10985
10986   // Combine Indices - If the source pointer to this getelementptr instruction
10987   // is a getelementptr instruction, combine the indices of the two
10988   // getelementptr instructions into a single instruction.
10989   //
10990   SmallVector<Value*, 8> SrcGEPOperands;
10991   if (User *Src = dyn_castGetElementPtr(PtrOp))
10992     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10993
10994   if (!SrcGEPOperands.empty()) {
10995     // Note that if our source is a gep chain itself that we wait for that
10996     // chain to be resolved before we perform this transformation.  This
10997     // avoids us creating a TON of code in some cases.
10998     //
10999     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11000         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11001       return 0;   // Wait until our source is folded to completion.
11002
11003     SmallVector<Value*, 8> Indices;
11004
11005     // Find out whether the last index in the source GEP is a sequential idx.
11006     bool EndsWithSequential = false;
11007     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11008            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11009       EndsWithSequential = !isa<StructType>(*I);
11010
11011     // Can we combine the two pointer arithmetics offsets?
11012     if (EndsWithSequential) {
11013       // Replace: gep (gep %P, long B), long A, ...
11014       // With:    T = long A+B; gep %P, T, ...
11015       //
11016       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11017       if (SO1 == Constant::getNullValue(SO1->getType())) {
11018         Sum = GO1;
11019       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11020         Sum = SO1;
11021       } else {
11022         // If they aren't the same type, convert both to an integer of the
11023         // target's pointer size.
11024         if (SO1->getType() != GO1->getType()) {
11025           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11026             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
11027           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11028             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
11029           } else {
11030             unsigned PS = TD->getPointerSizeInBits();
11031             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11032               // Convert GO1 to SO1's type.
11033               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11034
11035             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11036               // Convert SO1 to GO1's type.
11037               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11038             } else {
11039               const Type *PT = TD->getIntPtrType();
11040               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11041               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11042             }
11043           }
11044         }
11045         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11046           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
11047         else {
11048           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11049           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11050         }
11051       }
11052
11053       // Recycle the GEP we already have if possible.
11054       if (SrcGEPOperands.size() == 2) {
11055         GEP.setOperand(0, SrcGEPOperands[0]);
11056         GEP.setOperand(1, Sum);
11057         return &GEP;
11058       } else {
11059         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11060                        SrcGEPOperands.end()-1);
11061         Indices.push_back(Sum);
11062         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11063       }
11064     } else if (isa<Constant>(*GEP.idx_begin()) &&
11065                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11066                SrcGEPOperands.size() != 1) {
11067       // Otherwise we can do the fold if the first index of the GEP is a zero
11068       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11069                      SrcGEPOperands.end());
11070       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11071     }
11072
11073     if (!Indices.empty())
11074       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11075                                        Indices.end(), GEP.getName());
11076
11077   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11078     // GEP of global variable.  If all of the indices for this GEP are
11079     // constants, we can promote this to a constexpr instead of an instruction.
11080
11081     // Scan for nonconstants...
11082     SmallVector<Constant*, 8> Indices;
11083     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11084     for (; I != E && isa<Constant>(*I); ++I)
11085       Indices.push_back(cast<Constant>(*I));
11086
11087     if (I == E) {  // If they are all constants...
11088       Constant *CE = ConstantExpr::getGetElementPtr(GV,
11089                                                     &Indices[0],Indices.size());
11090
11091       // Replace all uses of the GEP with the new constexpr...
11092       return ReplaceInstUsesWith(GEP, CE);
11093     }
11094   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11095     if (!isa<PointerType>(X->getType())) {
11096       // Not interesting.  Source pointer must be a cast from pointer.
11097     } else if (HasZeroPointerIndex) {
11098       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11099       // into     : GEP [10 x i8]* X, i32 0, ...
11100       //
11101       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11102       //           into     : GEP i8* X, ...
11103       // 
11104       // This occurs when the program declares an array extern like "int X[];"
11105       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11106       const PointerType *XTy = cast<PointerType>(X->getType());
11107       if (const ArrayType *CATy =
11108           dyn_cast<ArrayType>(CPTy->getElementType())) {
11109         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11110         if (CATy->getElementType() == XTy->getElementType()) {
11111           // -> GEP i8* X, ...
11112           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11113           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11114                                            GEP.getName());
11115         } else if (const ArrayType *XATy =
11116                  dyn_cast<ArrayType>(XTy->getElementType())) {
11117           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11118           if (CATy->getElementType() == XATy->getElementType()) {
11119             // -> GEP [10 x i8]* X, i32 0, ...
11120             // At this point, we know that the cast source type is a pointer
11121             // to an array of the same type as the destination pointer
11122             // array.  Because the array type is never stepped over (there
11123             // is a leading zero) we can fold the cast into this GEP.
11124             GEP.setOperand(0, X);
11125             return &GEP;
11126           }
11127         }
11128       }
11129     } else if (GEP.getNumOperands() == 2) {
11130       // Transform things like:
11131       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11132       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11133       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11134       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11135       if (isa<ArrayType>(SrcElTy) &&
11136           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11137           TD->getTypeAllocSize(ResElTy)) {
11138         Value *Idx[2];
11139         Idx[0] = Constant::getNullValue(Type::Int32Ty);
11140         Idx[1] = GEP.getOperand(1);
11141         Value *V = InsertNewInstBefore(
11142                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11143         // V and GEP are both pointer types --> BitCast
11144         return new BitCastInst(V, GEP.getType());
11145       }
11146       
11147       // Transform things like:
11148       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11149       //   (where tmp = 8*tmp2) into:
11150       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11151       
11152       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11153         uint64_t ArrayEltSize =
11154             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11155         
11156         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11157         // allow either a mul, shift, or constant here.
11158         Value *NewIdx = 0;
11159         ConstantInt *Scale = 0;
11160         if (ArrayEltSize == 1) {
11161           NewIdx = GEP.getOperand(1);
11162           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11163         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11164           NewIdx = ConstantInt::get(CI->getType(), 1);
11165           Scale = CI;
11166         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11167           if (Inst->getOpcode() == Instruction::Shl &&
11168               isa<ConstantInt>(Inst->getOperand(1))) {
11169             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11170             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11171             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11172                                      1ULL << ShAmtVal);
11173             NewIdx = Inst->getOperand(0);
11174           } else if (Inst->getOpcode() == Instruction::Mul &&
11175                      isa<ConstantInt>(Inst->getOperand(1))) {
11176             Scale = cast<ConstantInt>(Inst->getOperand(1));
11177             NewIdx = Inst->getOperand(0);
11178           }
11179         }
11180         
11181         // If the index will be to exactly the right offset with the scale taken
11182         // out, perform the transformation. Note, we don't know whether Scale is
11183         // signed or not. We'll use unsigned version of division/modulo
11184         // operation after making sure Scale doesn't have the sign bit set.
11185         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11186             Scale->getZExtValue() % ArrayEltSize == 0) {
11187           Scale = ConstantInt::get(Scale->getType(),
11188                                    Scale->getZExtValue() / ArrayEltSize);
11189           if (Scale->getZExtValue() != 1) {
11190             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11191                                                        false /*ZExt*/);
11192             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11193             NewIdx = InsertNewInstBefore(Sc, GEP);
11194           }
11195
11196           // Insert the new GEP instruction.
11197           Value *Idx[2];
11198           Idx[0] = Constant::getNullValue(Type::Int32Ty);
11199           Idx[1] = NewIdx;
11200           Instruction *NewGEP =
11201             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11202           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11203           // The NewGEP must be pointer typed, so must the old one -> BitCast
11204           return new BitCastInst(NewGEP, GEP.getType());
11205         }
11206       }
11207     }
11208   }
11209   
11210   /// See if we can simplify:
11211   ///   X = bitcast A to B*
11212   ///   Y = gep X, <...constant indices...>
11213   /// into a gep of the original struct.  This is important for SROA and alias
11214   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11215   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11216     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11217       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11218       // a constant back from EmitGEPOffset.
11219       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11220       int64_t Offset = OffsetV->getSExtValue();
11221       
11222       // If this GEP instruction doesn't move the pointer, just replace the GEP
11223       // with a bitcast of the real input to the dest type.
11224       if (Offset == 0) {
11225         // If the bitcast is of an allocation, and the allocation will be
11226         // converted to match the type of the cast, don't touch this.
11227         if (isa<AllocationInst>(BCI->getOperand(0))) {
11228           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11229           if (Instruction *I = visitBitCast(*BCI)) {
11230             if (I != BCI) {
11231               I->takeName(BCI);
11232               BCI->getParent()->getInstList().insert(BCI, I);
11233               ReplaceInstUsesWith(*BCI, I);
11234             }
11235             return &GEP;
11236           }
11237         }
11238         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11239       }
11240       
11241       // Otherwise, if the offset is non-zero, we need to find out if there is a
11242       // field at Offset in 'A's type.  If so, we can pull the cast through the
11243       // GEP.
11244       SmallVector<Value*, 8> NewIndices;
11245       const Type *InTy =
11246         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11247       if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
11248         Instruction *NGEP =
11249            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11250                                      NewIndices.end());
11251         if (NGEP->getType() == GEP.getType()) return NGEP;
11252         InsertNewInstBefore(NGEP, GEP);
11253         NGEP->takeName(&GEP);
11254         return new BitCastInst(NGEP, GEP.getType());
11255       }
11256     }
11257   }    
11258     
11259   return 0;
11260 }
11261
11262 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11263   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11264   if (AI.isArrayAllocation()) {  // Check C != 1
11265     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11266       const Type *NewTy = 
11267         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11268       AllocationInst *New = 0;
11269
11270       // Create and insert the replacement instruction...
11271       if (isa<MallocInst>(AI))
11272         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11273       else {
11274         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11275         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11276       }
11277
11278       InsertNewInstBefore(New, AI);
11279
11280       // Scan to the end of the allocation instructions, to skip over a block of
11281       // allocas if possible...also skip interleaved debug info
11282       //
11283       BasicBlock::iterator It = New;
11284       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11285
11286       // Now that I is pointing to the first non-allocation-inst in the block,
11287       // insert our getelementptr instruction...
11288       //
11289       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
11290       Value *Idx[2];
11291       Idx[0] = NullIdx;
11292       Idx[1] = NullIdx;
11293       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11294                                            New->getName()+".sub", It);
11295
11296       // Now make everything use the getelementptr instead of the original
11297       // allocation.
11298       return ReplaceInstUsesWith(AI, V);
11299     } else if (isa<UndefValue>(AI.getArraySize())) {
11300       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11301     }
11302   }
11303
11304   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11305     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11306     // Note that we only do this for alloca's, because malloc should allocate
11307     // and return a unique pointer, even for a zero byte allocation.
11308     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11309       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11310
11311     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11312     if (AI.getAlignment() == 0)
11313       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11314   }
11315
11316   return 0;
11317 }
11318
11319 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11320   Value *Op = FI.getOperand(0);
11321
11322   // free undef -> unreachable.
11323   if (isa<UndefValue>(Op)) {
11324     // Insert a new store to null because we cannot modify the CFG here.
11325     new StoreInst(ConstantInt::getTrue(),
11326                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
11327     return EraseInstFromFunction(FI);
11328   }
11329   
11330   // If we have 'free null' delete the instruction.  This can happen in stl code
11331   // when lots of inlining happens.
11332   if (isa<ConstantPointerNull>(Op))
11333     return EraseInstFromFunction(FI);
11334   
11335   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11336   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11337     FI.setOperand(0, CI->getOperand(0));
11338     return &FI;
11339   }
11340   
11341   // Change free (gep X, 0,0,0,0) into free(X)
11342   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11343     if (GEPI->hasAllZeroIndices()) {
11344       AddToWorkList(GEPI);
11345       FI.setOperand(0, GEPI->getOperand(0));
11346       return &FI;
11347     }
11348   }
11349   
11350   // Change free(malloc) into nothing, if the malloc has a single use.
11351   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11352     if (MI->hasOneUse()) {
11353       EraseInstFromFunction(FI);
11354       return EraseInstFromFunction(*MI);
11355     }
11356
11357   return 0;
11358 }
11359
11360
11361 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11362 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11363                                         const TargetData *TD) {
11364   User *CI = cast<User>(LI.getOperand(0));
11365   Value *CastOp = CI->getOperand(0);
11366
11367   if (TD) {
11368     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11369       // Instead of loading constant c string, use corresponding integer value
11370       // directly if string length is small enough.
11371       std::string Str;
11372       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11373         unsigned len = Str.length();
11374         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11375         unsigned numBits = Ty->getPrimitiveSizeInBits();
11376         // Replace LI with immediate integer store.
11377         if ((numBits >> 3) == len + 1) {
11378           APInt StrVal(numBits, 0);
11379           APInt SingleChar(numBits, 0);
11380           if (TD->isLittleEndian()) {
11381             for (signed i = len-1; i >= 0; i--) {
11382               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11383               StrVal = (StrVal << 8) | SingleChar;
11384             }
11385           } else {
11386             for (unsigned i = 0; i < len; i++) {
11387               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11388               StrVal = (StrVal << 8) | SingleChar;
11389             }
11390             // Append NULL at the end.
11391             SingleChar = 0;
11392             StrVal = (StrVal << 8) | SingleChar;
11393           }
11394           Value *NL = ConstantInt::get(StrVal);
11395           return IC.ReplaceInstUsesWith(LI, NL);
11396         }
11397       }
11398     }
11399   }
11400
11401   const PointerType *DestTy = cast<PointerType>(CI->getType());
11402   const Type *DestPTy = DestTy->getElementType();
11403   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11404
11405     // If the address spaces don't match, don't eliminate the cast.
11406     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11407       return 0;
11408
11409     const Type *SrcPTy = SrcTy->getElementType();
11410
11411     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11412          isa<VectorType>(DestPTy)) {
11413       // If the source is an array, the code below will not succeed.  Check to
11414       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11415       // constants.
11416       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11417         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11418           if (ASrcTy->getNumElements() != 0) {
11419             Value *Idxs[2];
11420             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11421             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11422             SrcTy = cast<PointerType>(CastOp->getType());
11423             SrcPTy = SrcTy->getElementType();
11424           }
11425
11426       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11427             isa<VectorType>(SrcPTy)) &&
11428           // Do not allow turning this into a load of an integer, which is then
11429           // casted to a pointer, this pessimizes pointer analysis a lot.
11430           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11431           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11432                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11433
11434         // Okay, we are casting from one integer or pointer type to another of
11435         // the same size.  Instead of casting the pointer before the load, cast
11436         // the result of the loaded value.
11437         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11438                                                              CI->getName(),
11439                                                          LI.isVolatile()),LI);
11440         // Now cast the result of the load.
11441         return new BitCastInst(NewLoad, LI.getType());
11442       }
11443     }
11444   }
11445   return 0;
11446 }
11447
11448 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11449   Value *Op = LI.getOperand(0);
11450
11451   // Attempt to improve the alignment.
11452   unsigned KnownAlign =
11453     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11454   if (KnownAlign >
11455       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11456                                 LI.getAlignment()))
11457     LI.setAlignment(KnownAlign);
11458
11459   // load (cast X) --> cast (load X) iff safe
11460   if (isa<CastInst>(Op))
11461     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11462       return Res;
11463
11464   // None of the following transforms are legal for volatile loads.
11465   if (LI.isVolatile()) return 0;
11466   
11467   // Do really simple store-to-load forwarding and load CSE, to catch cases
11468   // where there are several consequtive memory accesses to the same location,
11469   // separated by a few arithmetic operations.
11470   BasicBlock::iterator BBI = &LI;
11471   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11472     return ReplaceInstUsesWith(LI, AvailableVal);
11473
11474   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11475     const Value *GEPI0 = GEPI->getOperand(0);
11476     // TODO: Consider a target hook for valid address spaces for this xform.
11477     if (isa<ConstantPointerNull>(GEPI0) &&
11478         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11479       // Insert a new store to null instruction before the load to indicate
11480       // that this code is not reachable.  We do this instead of inserting
11481       // an unreachable instruction directly because we cannot modify the
11482       // CFG.
11483       new StoreInst(UndefValue::get(LI.getType()),
11484                     Constant::getNullValue(Op->getType()), &LI);
11485       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11486     }
11487   } 
11488
11489   if (Constant *C = dyn_cast<Constant>(Op)) {
11490     // load null/undef -> undef
11491     // TODO: Consider a target hook for valid address spaces for this xform.
11492     if (isa<UndefValue>(C) || (C->isNullValue() && 
11493         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11494       // Insert a new store to null instruction before the load to indicate that
11495       // this code is not reachable.  We do this instead of inserting an
11496       // unreachable instruction directly because we cannot modify the CFG.
11497       new StoreInst(UndefValue::get(LI.getType()),
11498                     Constant::getNullValue(Op->getType()), &LI);
11499       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11500     }
11501
11502     // Instcombine load (constant global) into the value loaded.
11503     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11504       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11505         return ReplaceInstUsesWith(LI, GV->getInitializer());
11506
11507     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11508     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11509       if (CE->getOpcode() == Instruction::GetElementPtr) {
11510         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11511           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11512             if (Constant *V = 
11513                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11514               return ReplaceInstUsesWith(LI, V);
11515         if (CE->getOperand(0)->isNullValue()) {
11516           // Insert a new store to null instruction before the load to indicate
11517           // that this code is not reachable.  We do this instead of inserting
11518           // an unreachable instruction directly because we cannot modify the
11519           // CFG.
11520           new StoreInst(UndefValue::get(LI.getType()),
11521                         Constant::getNullValue(Op->getType()), &LI);
11522           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11523         }
11524
11525       } else if (CE->isCast()) {
11526         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11527           return Res;
11528       }
11529     }
11530   }
11531     
11532   // If this load comes from anywhere in a constant global, and if the global
11533   // is all undef or zero, we know what it loads.
11534   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11535     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11536       if (GV->getInitializer()->isNullValue())
11537         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11538       else if (isa<UndefValue>(GV->getInitializer()))
11539         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11540     }
11541   }
11542
11543   if (Op->hasOneUse()) {
11544     // Change select and PHI nodes to select values instead of addresses: this
11545     // helps alias analysis out a lot, allows many others simplifications, and
11546     // exposes redundancy in the code.
11547     //
11548     // Note that we cannot do the transformation unless we know that the
11549     // introduced loads cannot trap!  Something like this is valid as long as
11550     // the condition is always false: load (select bool %C, int* null, int* %G),
11551     // but it would not be valid if we transformed it to load from null
11552     // unconditionally.
11553     //
11554     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11555       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11556       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11557           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11558         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11559                                      SI->getOperand(1)->getName()+".val"), LI);
11560         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11561                                      SI->getOperand(2)->getName()+".val"), LI);
11562         return SelectInst::Create(SI->getCondition(), V1, V2);
11563       }
11564
11565       // load (select (cond, null, P)) -> load P
11566       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11567         if (C->isNullValue()) {
11568           LI.setOperand(0, SI->getOperand(2));
11569           return &LI;
11570         }
11571
11572       // load (select (cond, P, null)) -> load P
11573       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11574         if (C->isNullValue()) {
11575           LI.setOperand(0, SI->getOperand(1));
11576           return &LI;
11577         }
11578     }
11579   }
11580   return 0;
11581 }
11582
11583 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11584 /// when possible.  This makes it generally easy to do alias analysis and/or
11585 /// SROA/mem2reg of the memory object.
11586 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11587   User *CI = cast<User>(SI.getOperand(1));
11588   Value *CastOp = CI->getOperand(0);
11589
11590   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11591   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11592   if (SrcTy == 0) return 0;
11593   
11594   const Type *SrcPTy = SrcTy->getElementType();
11595
11596   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11597     return 0;
11598   
11599   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11600   /// to its first element.  This allows us to handle things like:
11601   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11602   /// on 32-bit hosts.
11603   SmallVector<Value*, 4> NewGEPIndices;
11604   
11605   // If the source is an array, the code below will not succeed.  Check to
11606   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11607   // constants.
11608   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11609     // Index through pointer.
11610     Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11611     NewGEPIndices.push_back(Zero);
11612     
11613     while (1) {
11614       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11615         if (!STy->getNumElements()) /* Struct can be empty {} */
11616           break;
11617         NewGEPIndices.push_back(Zero);
11618         SrcPTy = STy->getElementType(0);
11619       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11620         NewGEPIndices.push_back(Zero);
11621         SrcPTy = ATy->getElementType();
11622       } else {
11623         break;
11624       }
11625     }
11626     
11627     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11628   }
11629
11630   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11631     return 0;
11632   
11633   // If the pointers point into different address spaces or if they point to
11634   // values with different sizes, we can't do the transformation.
11635   if (SrcTy->getAddressSpace() != 
11636         cast<PointerType>(CI->getType())->getAddressSpace() ||
11637       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11638       IC.getTargetData().getTypeSizeInBits(DestPTy))
11639     return 0;
11640
11641   // Okay, we are casting from one integer or pointer type to another of
11642   // the same size.  Instead of casting the pointer before 
11643   // the store, cast the value to be stored.
11644   Value *NewCast;
11645   Value *SIOp0 = SI.getOperand(0);
11646   Instruction::CastOps opcode = Instruction::BitCast;
11647   const Type* CastSrcTy = SIOp0->getType();
11648   const Type* CastDstTy = SrcPTy;
11649   if (isa<PointerType>(CastDstTy)) {
11650     if (CastSrcTy->isInteger())
11651       opcode = Instruction::IntToPtr;
11652   } else if (isa<IntegerType>(CastDstTy)) {
11653     if (isa<PointerType>(SIOp0->getType()))
11654       opcode = Instruction::PtrToInt;
11655   }
11656   
11657   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11658   // emit a GEP to index into its first field.
11659   if (!NewGEPIndices.empty()) {
11660     if (Constant *C = dyn_cast<Constant>(CastOp))
11661       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11662                                               NewGEPIndices.size());
11663     else
11664       CastOp = IC.InsertNewInstBefore(
11665               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11666                                         NewGEPIndices.end()), SI);
11667   }
11668   
11669   if (Constant *C = dyn_cast<Constant>(SIOp0))
11670     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11671   else
11672     NewCast = IC.InsertNewInstBefore(
11673       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11674       SI);
11675   return new StoreInst(NewCast, CastOp);
11676 }
11677
11678 /// equivalentAddressValues - Test if A and B will obviously have the same
11679 /// value. This includes recognizing that %t0 and %t1 will have the same
11680 /// value in code like this:
11681 ///   %t0 = getelementptr \@a, 0, 3
11682 ///   store i32 0, i32* %t0
11683 ///   %t1 = getelementptr \@a, 0, 3
11684 ///   %t2 = load i32* %t1
11685 ///
11686 static bool equivalentAddressValues(Value *A, Value *B) {
11687   // Test if the values are trivially equivalent.
11688   if (A == B) return true;
11689   
11690   // Test if the values come form identical arithmetic instructions.
11691   if (isa<BinaryOperator>(A) ||
11692       isa<CastInst>(A) ||
11693       isa<PHINode>(A) ||
11694       isa<GetElementPtrInst>(A))
11695     if (Instruction *BI = dyn_cast<Instruction>(B))
11696       if (cast<Instruction>(A)->isIdenticalTo(BI))
11697         return true;
11698   
11699   // Otherwise they may not be equivalent.
11700   return false;
11701 }
11702
11703 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11704 // return the llvm.dbg.declare.
11705 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11706   if (!V->hasNUses(2))
11707     return 0;
11708   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11709        UI != E; ++UI) {
11710     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11711       return DI;
11712     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11713       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11714         return DI;
11715       }
11716   }
11717   return 0;
11718 }
11719
11720 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11721   Value *Val = SI.getOperand(0);
11722   Value *Ptr = SI.getOperand(1);
11723
11724   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11725     EraseInstFromFunction(SI);
11726     ++NumCombined;
11727     return 0;
11728   }
11729   
11730   // If the RHS is an alloca with a single use, zapify the store, making the
11731   // alloca dead.
11732   // If the RHS is an alloca with a two uses, the other one being a 
11733   // llvm.dbg.declare, zapify the store and the declare, making the
11734   // alloca dead.  We must do this to prevent declare's from affecting
11735   // codegen.
11736   if (!SI.isVolatile()) {
11737     if (Ptr->hasOneUse()) {
11738       if (isa<AllocaInst>(Ptr)) {
11739         EraseInstFromFunction(SI);
11740         ++NumCombined;
11741         return 0;
11742       }
11743       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11744         if (isa<AllocaInst>(GEP->getOperand(0))) {
11745           if (GEP->getOperand(0)->hasOneUse()) {
11746             EraseInstFromFunction(SI);
11747             ++NumCombined;
11748             return 0;
11749           }
11750           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11751             EraseInstFromFunction(*DI);
11752             EraseInstFromFunction(SI);
11753             ++NumCombined;
11754             return 0;
11755           }
11756         }
11757       }
11758     }
11759     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11760       EraseInstFromFunction(*DI);
11761       EraseInstFromFunction(SI);
11762       ++NumCombined;
11763       return 0;
11764     }
11765   }
11766
11767   // Attempt to improve the alignment.
11768   unsigned KnownAlign =
11769     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11770   if (KnownAlign >
11771       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11772                                 SI.getAlignment()))
11773     SI.setAlignment(KnownAlign);
11774
11775   // Do really simple DSE, to catch cases where there are several consecutive
11776   // stores to the same location, separated by a few arithmetic operations. This
11777   // situation often occurs with bitfield accesses.
11778   BasicBlock::iterator BBI = &SI;
11779   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11780        --ScanInsts) {
11781     --BBI;
11782     // Don't count debug info directives, lest they affect codegen,
11783     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11784     // It is necessary for correctness to skip those that feed into a
11785     // llvm.dbg.declare, as these are not present when debugging is off.
11786     if (isa<DbgInfoIntrinsic>(BBI) ||
11787         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11788       ScanInsts++;
11789       continue;
11790     }    
11791     
11792     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11793       // Prev store isn't volatile, and stores to the same location?
11794       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11795                                                           SI.getOperand(1))) {
11796         ++NumDeadStore;
11797         ++BBI;
11798         EraseInstFromFunction(*PrevSI);
11799         continue;
11800       }
11801       break;
11802     }
11803     
11804     // If this is a load, we have to stop.  However, if the loaded value is from
11805     // the pointer we're loading and is producing the pointer we're storing,
11806     // then *this* store is dead (X = load P; store X -> P).
11807     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11808       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11809           !SI.isVolatile()) {
11810         EraseInstFromFunction(SI);
11811         ++NumCombined;
11812         return 0;
11813       }
11814       // Otherwise, this is a load from some other location.  Stores before it
11815       // may not be dead.
11816       break;
11817     }
11818     
11819     // Don't skip over loads or things that can modify memory.
11820     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11821       break;
11822   }
11823   
11824   
11825   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11826
11827   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11828   if (isa<ConstantPointerNull>(Ptr) &&
11829       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11830     if (!isa<UndefValue>(Val)) {
11831       SI.setOperand(0, UndefValue::get(Val->getType()));
11832       if (Instruction *U = dyn_cast<Instruction>(Val))
11833         AddToWorkList(U);  // Dropped a use.
11834       ++NumCombined;
11835     }
11836     return 0;  // Do not modify these!
11837   }
11838
11839   // store undef, Ptr -> noop
11840   if (isa<UndefValue>(Val)) {
11841     EraseInstFromFunction(SI);
11842     ++NumCombined;
11843     return 0;
11844   }
11845
11846   // If the pointer destination is a cast, see if we can fold the cast into the
11847   // source instead.
11848   if (isa<CastInst>(Ptr))
11849     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11850       return Res;
11851   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11852     if (CE->isCast())
11853       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11854         return Res;
11855
11856   
11857   // If this store is the last instruction in the basic block (possibly
11858   // excepting debug info instructions and the pointer bitcasts that feed
11859   // into them), and if the block ends with an unconditional branch, try
11860   // to move it to the successor block.
11861   BBI = &SI; 
11862   do {
11863     ++BBI;
11864   } while (isa<DbgInfoIntrinsic>(BBI) ||
11865            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11866   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11867     if (BI->isUnconditional())
11868       if (SimplifyStoreAtEndOfBlock(SI))
11869         return 0;  // xform done!
11870   
11871   return 0;
11872 }
11873
11874 /// SimplifyStoreAtEndOfBlock - Turn things like:
11875 ///   if () { *P = v1; } else { *P = v2 }
11876 /// into a phi node with a store in the successor.
11877 ///
11878 /// Simplify things like:
11879 ///   *P = v1; if () { *P = v2; }
11880 /// into a phi node with a store in the successor.
11881 ///
11882 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11883   BasicBlock *StoreBB = SI.getParent();
11884   
11885   // Check to see if the successor block has exactly two incoming edges.  If
11886   // so, see if the other predecessor contains a store to the same location.
11887   // if so, insert a PHI node (if needed) and move the stores down.
11888   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11889   
11890   // Determine whether Dest has exactly two predecessors and, if so, compute
11891   // the other predecessor.
11892   pred_iterator PI = pred_begin(DestBB);
11893   BasicBlock *OtherBB = 0;
11894   if (*PI != StoreBB)
11895     OtherBB = *PI;
11896   ++PI;
11897   if (PI == pred_end(DestBB))
11898     return false;
11899   
11900   if (*PI != StoreBB) {
11901     if (OtherBB)
11902       return false;
11903     OtherBB = *PI;
11904   }
11905   if (++PI != pred_end(DestBB))
11906     return false;
11907
11908   // Bail out if all the relevant blocks aren't distinct (this can happen,
11909   // for example, if SI is in an infinite loop)
11910   if (StoreBB == DestBB || OtherBB == DestBB)
11911     return false;
11912
11913   // Verify that the other block ends in a branch and is not otherwise empty.
11914   BasicBlock::iterator BBI = OtherBB->getTerminator();
11915   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11916   if (!OtherBr || BBI == OtherBB->begin())
11917     return false;
11918   
11919   // If the other block ends in an unconditional branch, check for the 'if then
11920   // else' case.  there is an instruction before the branch.
11921   StoreInst *OtherStore = 0;
11922   if (OtherBr->isUnconditional()) {
11923     --BBI;
11924     // Skip over debugging info.
11925     while (isa<DbgInfoIntrinsic>(BBI) ||
11926            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11927       if (BBI==OtherBB->begin())
11928         return false;
11929       --BBI;
11930     }
11931     // If this isn't a store, or isn't a store to the same location, bail out.
11932     OtherStore = dyn_cast<StoreInst>(BBI);
11933     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11934       return false;
11935   } else {
11936     // Otherwise, the other block ended with a conditional branch. If one of the
11937     // destinations is StoreBB, then we have the if/then case.
11938     if (OtherBr->getSuccessor(0) != StoreBB && 
11939         OtherBr->getSuccessor(1) != StoreBB)
11940       return false;
11941     
11942     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11943     // if/then triangle.  See if there is a store to the same ptr as SI that
11944     // lives in OtherBB.
11945     for (;; --BBI) {
11946       // Check to see if we find the matching store.
11947       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11948         if (OtherStore->getOperand(1) != SI.getOperand(1))
11949           return false;
11950         break;
11951       }
11952       // If we find something that may be using or overwriting the stored
11953       // value, or if we run out of instructions, we can't do the xform.
11954       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11955           BBI == OtherBB->begin())
11956         return false;
11957     }
11958     
11959     // In order to eliminate the store in OtherBr, we have to
11960     // make sure nothing reads or overwrites the stored value in
11961     // StoreBB.
11962     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11963       // FIXME: This should really be AA driven.
11964       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11965         return false;
11966     }
11967   }
11968   
11969   // Insert a PHI node now if we need it.
11970   Value *MergedVal = OtherStore->getOperand(0);
11971   if (MergedVal != SI.getOperand(0)) {
11972     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11973     PN->reserveOperandSpace(2);
11974     PN->addIncoming(SI.getOperand(0), SI.getParent());
11975     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11976     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11977   }
11978   
11979   // Advance to a place where it is safe to insert the new store and
11980   // insert it.
11981   BBI = DestBB->getFirstNonPHI();
11982   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11983                                     OtherStore->isVolatile()), *BBI);
11984   
11985   // Nuke the old stores.
11986   EraseInstFromFunction(SI);
11987   EraseInstFromFunction(*OtherStore);
11988   ++NumCombined;
11989   return true;
11990 }
11991
11992
11993 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11994   // Change br (not X), label True, label False to: br X, label False, True
11995   Value *X = 0;
11996   BasicBlock *TrueDest;
11997   BasicBlock *FalseDest;
11998   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11999       !isa<Constant>(X)) {
12000     // Swap Destinations and condition...
12001     BI.setCondition(X);
12002     BI.setSuccessor(0, FalseDest);
12003     BI.setSuccessor(1, TrueDest);
12004     return &BI;
12005   }
12006
12007   // Cannonicalize fcmp_one -> fcmp_oeq
12008   FCmpInst::Predicate FPred; Value *Y;
12009   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12010                              TrueDest, FalseDest)))
12011     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12012          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12013       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12014       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12015       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
12016       NewSCC->takeName(I);
12017       // Swap Destinations and condition...
12018       BI.setCondition(NewSCC);
12019       BI.setSuccessor(0, FalseDest);
12020       BI.setSuccessor(1, TrueDest);
12021       RemoveFromWorkList(I);
12022       I->eraseFromParent();
12023       AddToWorkList(NewSCC);
12024       return &BI;
12025     }
12026
12027   // Cannonicalize icmp_ne -> icmp_eq
12028   ICmpInst::Predicate IPred;
12029   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12030                       TrueDest, FalseDest)))
12031     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12032          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12033          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12034       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12035       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12036       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
12037       NewSCC->takeName(I);
12038       // Swap Destinations and condition...
12039       BI.setCondition(NewSCC);
12040       BI.setSuccessor(0, FalseDest);
12041       BI.setSuccessor(1, TrueDest);
12042       RemoveFromWorkList(I);
12043       I->eraseFromParent();;
12044       AddToWorkList(NewSCC);
12045       return &BI;
12046     }
12047
12048   return 0;
12049 }
12050
12051 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12052   Value *Cond = SI.getCondition();
12053   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12054     if (I->getOpcode() == Instruction::Add)
12055       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12056         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12057         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12058           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12059                                                 AddRHS));
12060         SI.setOperand(0, I->getOperand(0));
12061         AddToWorkList(I);
12062         return &SI;
12063       }
12064   }
12065   return 0;
12066 }
12067
12068 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12069   Value *Agg = EV.getAggregateOperand();
12070
12071   if (!EV.hasIndices())
12072     return ReplaceInstUsesWith(EV, Agg);
12073
12074   if (Constant *C = dyn_cast<Constant>(Agg)) {
12075     if (isa<UndefValue>(C))
12076       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12077       
12078     if (isa<ConstantAggregateZero>(C))
12079       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12080
12081     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12082       // Extract the element indexed by the first index out of the constant
12083       Value *V = C->getOperand(*EV.idx_begin());
12084       if (EV.getNumIndices() > 1)
12085         // Extract the remaining indices out of the constant indexed by the
12086         // first index
12087         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12088       else
12089         return ReplaceInstUsesWith(EV, V);
12090     }
12091     return 0; // Can't handle other constants
12092   } 
12093   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12094     // We're extracting from an insertvalue instruction, compare the indices
12095     const unsigned *exti, *exte, *insi, *inse;
12096     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12097          exte = EV.idx_end(), inse = IV->idx_end();
12098          exti != exte && insi != inse;
12099          ++exti, ++insi) {
12100       if (*insi != *exti)
12101         // The insert and extract both reference distinctly different elements.
12102         // This means the extract is not influenced by the insert, and we can
12103         // replace the aggregate operand of the extract with the aggregate
12104         // operand of the insert. i.e., replace
12105         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12106         // %E = extractvalue { i32, { i32 } } %I, 0
12107         // with
12108         // %E = extractvalue { i32, { i32 } } %A, 0
12109         return ExtractValueInst::Create(IV->getAggregateOperand(),
12110                                         EV.idx_begin(), EV.idx_end());
12111     }
12112     if (exti == exte && insi == inse)
12113       // Both iterators are at the end: Index lists are identical. Replace
12114       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12115       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12116       // with "i32 42"
12117       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12118     if (exti == exte) {
12119       // The extract list is a prefix of the insert list. i.e. replace
12120       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12121       // %E = extractvalue { i32, { i32 } } %I, 1
12122       // with
12123       // %X = extractvalue { i32, { i32 } } %A, 1
12124       // %E = insertvalue { i32 } %X, i32 42, 0
12125       // by switching the order of the insert and extract (though the
12126       // insertvalue should be left in, since it may have other uses).
12127       Value *NewEV = InsertNewInstBefore(
12128         ExtractValueInst::Create(IV->getAggregateOperand(),
12129                                  EV.idx_begin(), EV.idx_end()),
12130         EV);
12131       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12132                                      insi, inse);
12133     }
12134     if (insi == inse)
12135       // The insert list is a prefix of the extract list
12136       // We can simply remove the common indices from the extract and make it
12137       // operate on the inserted value instead of the insertvalue result.
12138       // i.e., replace
12139       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12140       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12141       // with
12142       // %E extractvalue { i32 } { i32 42 }, 0
12143       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12144                                       exti, exte);
12145   }
12146   // Can't simplify extracts from other values. Note that nested extracts are
12147   // already simplified implicitely by the above (extract ( extract (insert) )
12148   // will be translated into extract ( insert ( extract ) ) first and then just
12149   // the value inserted, if appropriate).
12150   return 0;
12151 }
12152
12153 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12154 /// is to leave as a vector operation.
12155 static bool CheapToScalarize(Value *V, bool isConstant) {
12156   if (isa<ConstantAggregateZero>(V)) 
12157     return true;
12158   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12159     if (isConstant) return true;
12160     // If all elts are the same, we can extract.
12161     Constant *Op0 = C->getOperand(0);
12162     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12163       if (C->getOperand(i) != Op0)
12164         return false;
12165     return true;
12166   }
12167   Instruction *I = dyn_cast<Instruction>(V);
12168   if (!I) return false;
12169   
12170   // Insert element gets simplified to the inserted element or is deleted if
12171   // this is constant idx extract element and its a constant idx insertelt.
12172   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12173       isa<ConstantInt>(I->getOperand(2)))
12174     return true;
12175   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12176     return true;
12177   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12178     if (BO->hasOneUse() &&
12179         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12180          CheapToScalarize(BO->getOperand(1), isConstant)))
12181       return true;
12182   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12183     if (CI->hasOneUse() &&
12184         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12185          CheapToScalarize(CI->getOperand(1), isConstant)))
12186       return true;
12187   
12188   return false;
12189 }
12190
12191 /// Read and decode a shufflevector mask.
12192 ///
12193 /// It turns undef elements into values that are larger than the number of
12194 /// elements in the input.
12195 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12196   unsigned NElts = SVI->getType()->getNumElements();
12197   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12198     return std::vector<unsigned>(NElts, 0);
12199   if (isa<UndefValue>(SVI->getOperand(2)))
12200     return std::vector<unsigned>(NElts, 2*NElts);
12201
12202   std::vector<unsigned> Result;
12203   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12204   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12205     if (isa<UndefValue>(*i))
12206       Result.push_back(NElts*2);  // undef -> 8
12207     else
12208       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12209   return Result;
12210 }
12211
12212 /// FindScalarElement - Given a vector and an element number, see if the scalar
12213 /// value is already around as a register, for example if it were inserted then
12214 /// extracted from the vector.
12215 static Value *FindScalarElement(Value *V, unsigned EltNo) {
12216   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12217   const VectorType *PTy = cast<VectorType>(V->getType());
12218   unsigned Width = PTy->getNumElements();
12219   if (EltNo >= Width)  // Out of range access.
12220     return UndefValue::get(PTy->getElementType());
12221   
12222   if (isa<UndefValue>(V))
12223     return UndefValue::get(PTy->getElementType());
12224   else if (isa<ConstantAggregateZero>(V))
12225     return Constant::getNullValue(PTy->getElementType());
12226   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12227     return CP->getOperand(EltNo);
12228   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12229     // If this is an insert to a variable element, we don't know what it is.
12230     if (!isa<ConstantInt>(III->getOperand(2))) 
12231       return 0;
12232     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12233     
12234     // If this is an insert to the element we are looking for, return the
12235     // inserted value.
12236     if (EltNo == IIElt) 
12237       return III->getOperand(1);
12238     
12239     // Otherwise, the insertelement doesn't modify the value, recurse on its
12240     // vector input.
12241     return FindScalarElement(III->getOperand(0), EltNo);
12242   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12243     unsigned LHSWidth =
12244       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12245     unsigned InEl = getShuffleMask(SVI)[EltNo];
12246     if (InEl < LHSWidth)
12247       return FindScalarElement(SVI->getOperand(0), InEl);
12248     else if (InEl < LHSWidth*2)
12249       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
12250     else
12251       return UndefValue::get(PTy->getElementType());
12252   }
12253   
12254   // Otherwise, we don't know.
12255   return 0;
12256 }
12257
12258 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12259   // If vector val is undef, replace extract with scalar undef.
12260   if (isa<UndefValue>(EI.getOperand(0)))
12261     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12262
12263   // If vector val is constant 0, replace extract with scalar 0.
12264   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12265     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12266   
12267   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12268     // If vector val is constant with all elements the same, replace EI with
12269     // that element. When the elements are not identical, we cannot replace yet
12270     // (we do that below, but only when the index is constant).
12271     Constant *op0 = C->getOperand(0);
12272     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12273       if (C->getOperand(i) != op0) {
12274         op0 = 0; 
12275         break;
12276       }
12277     if (op0)
12278       return ReplaceInstUsesWith(EI, op0);
12279   }
12280   
12281   // If extracting a specified index from the vector, see if we can recursively
12282   // find a previously computed scalar that was inserted into the vector.
12283   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12284     unsigned IndexVal = IdxC->getZExtValue();
12285     unsigned VectorWidth = 
12286       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12287       
12288     // If this is extracting an invalid index, turn this into undef, to avoid
12289     // crashing the code below.
12290     if (IndexVal >= VectorWidth)
12291       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12292     
12293     // This instruction only demands the single element from the input vector.
12294     // If the input vector has a single use, simplify it based on this use
12295     // property.
12296     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12297       APInt UndefElts(VectorWidth, 0);
12298       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12299       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12300                                                 DemandedMask, UndefElts)) {
12301         EI.setOperand(0, V);
12302         return &EI;
12303       }
12304     }
12305     
12306     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
12307       return ReplaceInstUsesWith(EI, Elt);
12308     
12309     // If the this extractelement is directly using a bitcast from a vector of
12310     // the same number of elements, see if we can find the source element from
12311     // it.  In this case, we will end up needing to bitcast the scalars.
12312     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12313       if (const VectorType *VT = 
12314               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12315         if (VT->getNumElements() == VectorWidth)
12316           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12317             return new BitCastInst(Elt, EI.getType());
12318     }
12319   }
12320   
12321   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12322     if (I->hasOneUse()) {
12323       // Push extractelement into predecessor operation if legal and
12324       // profitable to do so
12325       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12326         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12327         if (CheapToScalarize(BO, isConstantElt)) {
12328           ExtractElementInst *newEI0 = 
12329             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12330                                    EI.getName()+".lhs");
12331           ExtractElementInst *newEI1 =
12332             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12333                                    EI.getName()+".rhs");
12334           InsertNewInstBefore(newEI0, EI);
12335           InsertNewInstBefore(newEI1, EI);
12336           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12337         }
12338       } else if (isa<LoadInst>(I)) {
12339         unsigned AS = 
12340           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12341         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12342                                          PointerType::get(EI.getType(), AS),EI);
12343         GetElementPtrInst *GEP =
12344           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12345         InsertNewInstBefore(GEP, EI);
12346         return new LoadInst(GEP);
12347       }
12348     }
12349     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12350       // Extracting the inserted element?
12351       if (IE->getOperand(2) == EI.getOperand(1))
12352         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12353       // If the inserted and extracted elements are constants, they must not
12354       // be the same value, extract from the pre-inserted value instead.
12355       if (isa<Constant>(IE->getOperand(2)) &&
12356           isa<Constant>(EI.getOperand(1))) {
12357         AddUsesToWorkList(EI);
12358         EI.setOperand(0, IE->getOperand(0));
12359         return &EI;
12360       }
12361     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12362       // If this is extracting an element from a shufflevector, figure out where
12363       // it came from and extract from the appropriate input element instead.
12364       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12365         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12366         Value *Src;
12367         unsigned LHSWidth =
12368           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12369
12370         if (SrcIdx < LHSWidth)
12371           Src = SVI->getOperand(0);
12372         else if (SrcIdx < LHSWidth*2) {
12373           SrcIdx -= LHSWidth;
12374           Src = SVI->getOperand(1);
12375         } else {
12376           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12377         }
12378         return new ExtractElementInst(Src, SrcIdx);
12379       }
12380     }
12381   }
12382   return 0;
12383 }
12384
12385 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12386 /// elements from either LHS or RHS, return the shuffle mask and true. 
12387 /// Otherwise, return false.
12388 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12389                                          std::vector<Constant*> &Mask) {
12390   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12391          "Invalid CollectSingleShuffleElements");
12392   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12393
12394   if (isa<UndefValue>(V)) {
12395     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12396     return true;
12397   } else if (V == LHS) {
12398     for (unsigned i = 0; i != NumElts; ++i)
12399       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12400     return true;
12401   } else if (V == RHS) {
12402     for (unsigned i = 0; i != NumElts; ++i)
12403       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12404     return true;
12405   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12406     // If this is an insert of an extract from some other vector, include it.
12407     Value *VecOp    = IEI->getOperand(0);
12408     Value *ScalarOp = IEI->getOperand(1);
12409     Value *IdxOp    = IEI->getOperand(2);
12410     
12411     if (!isa<ConstantInt>(IdxOp))
12412       return false;
12413     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12414     
12415     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12416       // Okay, we can handle this if the vector we are insertinting into is
12417       // transitively ok.
12418       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12419         // If so, update the mask to reflect the inserted undef.
12420         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12421         return true;
12422       }      
12423     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12424       if (isa<ConstantInt>(EI->getOperand(1)) &&
12425           EI->getOperand(0)->getType() == V->getType()) {
12426         unsigned ExtractedIdx =
12427           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12428         
12429         // This must be extracting from either LHS or RHS.
12430         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12431           // Okay, we can handle this if the vector we are insertinting into is
12432           // transitively ok.
12433           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12434             // If so, update the mask to reflect the inserted value.
12435             if (EI->getOperand(0) == LHS) {
12436               Mask[InsertedIdx % NumElts] = 
12437                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12438             } else {
12439               assert(EI->getOperand(0) == RHS);
12440               Mask[InsertedIdx % NumElts] = 
12441                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12442               
12443             }
12444             return true;
12445           }
12446         }
12447       }
12448     }
12449   }
12450   // TODO: Handle shufflevector here!
12451   
12452   return false;
12453 }
12454
12455 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12456 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12457 /// that computes V and the LHS value of the shuffle.
12458 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12459                                      Value *&RHS) {
12460   assert(isa<VectorType>(V->getType()) && 
12461          (RHS == 0 || V->getType() == RHS->getType()) &&
12462          "Invalid shuffle!");
12463   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12464
12465   if (isa<UndefValue>(V)) {
12466     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12467     return V;
12468   } else if (isa<ConstantAggregateZero>(V)) {
12469     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12470     return V;
12471   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12472     // If this is an insert of an extract from some other vector, include it.
12473     Value *VecOp    = IEI->getOperand(0);
12474     Value *ScalarOp = IEI->getOperand(1);
12475     Value *IdxOp    = IEI->getOperand(2);
12476     
12477     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12478       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12479           EI->getOperand(0)->getType() == V->getType()) {
12480         unsigned ExtractedIdx =
12481           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12482         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12483         
12484         // Either the extracted from or inserted into vector must be RHSVec,
12485         // otherwise we'd end up with a shuffle of three inputs.
12486         if (EI->getOperand(0) == RHS || RHS == 0) {
12487           RHS = EI->getOperand(0);
12488           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
12489           Mask[InsertedIdx % NumElts] = 
12490             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12491           return V;
12492         }
12493         
12494         if (VecOp == RHS) {
12495           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
12496           // Everything but the extracted element is replaced with the RHS.
12497           for (unsigned i = 0; i != NumElts; ++i) {
12498             if (i != InsertedIdx)
12499               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12500           }
12501           return V;
12502         }
12503         
12504         // If this insertelement is a chain that comes from exactly these two
12505         // vectors, return the vector and the effective shuffle.
12506         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12507           return EI->getOperand(0);
12508         
12509       }
12510     }
12511   }
12512   // TODO: Handle shufflevector here!
12513   
12514   // Otherwise, can't do anything fancy.  Return an identity vector.
12515   for (unsigned i = 0; i != NumElts; ++i)
12516     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12517   return V;
12518 }
12519
12520 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12521   Value *VecOp    = IE.getOperand(0);
12522   Value *ScalarOp = IE.getOperand(1);
12523   Value *IdxOp    = IE.getOperand(2);
12524   
12525   // Inserting an undef or into an undefined place, remove this.
12526   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12527     ReplaceInstUsesWith(IE, VecOp);
12528   
12529   // If the inserted element was extracted from some other vector, and if the 
12530   // indexes are constant, try to turn this into a shufflevector operation.
12531   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12532     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12533         EI->getOperand(0)->getType() == IE.getType()) {
12534       unsigned NumVectorElts = IE.getType()->getNumElements();
12535       unsigned ExtractedIdx =
12536         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12537       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12538       
12539       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12540         return ReplaceInstUsesWith(IE, VecOp);
12541       
12542       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12543         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12544       
12545       // If we are extracting a value from a vector, then inserting it right
12546       // back into the same place, just use the input vector.
12547       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12548         return ReplaceInstUsesWith(IE, VecOp);      
12549       
12550       // We could theoretically do this for ANY input.  However, doing so could
12551       // turn chains of insertelement instructions into a chain of shufflevector
12552       // instructions, and right now we do not merge shufflevectors.  As such,
12553       // only do this in a situation where it is clear that there is benefit.
12554       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12555         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12556         // the values of VecOp, except then one read from EIOp0.
12557         // Build a new shuffle mask.
12558         std::vector<Constant*> Mask;
12559         if (isa<UndefValue>(VecOp))
12560           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12561         else {
12562           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12563           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12564                                                        NumVectorElts));
12565         } 
12566         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12567         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12568                                      ConstantVector::get(Mask));
12569       }
12570       
12571       // If this insertelement isn't used by some other insertelement, turn it
12572       // (and any insertelements it points to), into one big shuffle.
12573       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12574         std::vector<Constant*> Mask;
12575         Value *RHS = 0;
12576         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12577         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12578         // We now have a shuffle of LHS, RHS, Mask.
12579         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12580       }
12581     }
12582   }
12583
12584   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12585   APInt UndefElts(VWidth, 0);
12586   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12587   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12588     return &IE;
12589
12590   return 0;
12591 }
12592
12593
12594 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12595   Value *LHS = SVI.getOperand(0);
12596   Value *RHS = SVI.getOperand(1);
12597   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12598
12599   bool MadeChange = false;
12600
12601   // Undefined shuffle mask -> undefined value.
12602   if (isa<UndefValue>(SVI.getOperand(2)))
12603     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12604
12605   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12606
12607   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12608     return 0;
12609
12610   APInt UndefElts(VWidth, 0);
12611   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12612   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12613     LHS = SVI.getOperand(0);
12614     RHS = SVI.getOperand(1);
12615     MadeChange = true;
12616   }
12617   
12618   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12619   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12620   if (LHS == RHS || isa<UndefValue>(LHS)) {
12621     if (isa<UndefValue>(LHS) && LHS == RHS) {
12622       // shuffle(undef,undef,mask) -> undef.
12623       return ReplaceInstUsesWith(SVI, LHS);
12624     }
12625     
12626     // Remap any references to RHS to use LHS.
12627     std::vector<Constant*> Elts;
12628     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12629       if (Mask[i] >= 2*e)
12630         Elts.push_back(UndefValue::get(Type::Int32Ty));
12631       else {
12632         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12633             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12634           Mask[i] = 2*e;     // Turn into undef.
12635           Elts.push_back(UndefValue::get(Type::Int32Ty));
12636         } else {
12637           Mask[i] = Mask[i] % e;  // Force to LHS.
12638           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12639         }
12640       }
12641     }
12642     SVI.setOperand(0, SVI.getOperand(1));
12643     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12644     SVI.setOperand(2, ConstantVector::get(Elts));
12645     LHS = SVI.getOperand(0);
12646     RHS = SVI.getOperand(1);
12647     MadeChange = true;
12648   }
12649   
12650   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12651   bool isLHSID = true, isRHSID = true;
12652     
12653   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12654     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12655     // Is this an identity shuffle of the LHS value?
12656     isLHSID &= (Mask[i] == i);
12657       
12658     // Is this an identity shuffle of the RHS value?
12659     isRHSID &= (Mask[i]-e == i);
12660   }
12661
12662   // Eliminate identity shuffles.
12663   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12664   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12665   
12666   // If the LHS is a shufflevector itself, see if we can combine it with this
12667   // one without producing an unusual shuffle.  Here we are really conservative:
12668   // we are absolutely afraid of producing a shuffle mask not in the input
12669   // program, because the code gen may not be smart enough to turn a merged
12670   // shuffle into two specific shuffles: it may produce worse code.  As such,
12671   // we only merge two shuffles if the result is one of the two input shuffle
12672   // masks.  In this case, merging the shuffles just removes one instruction,
12673   // which we know is safe.  This is good for things like turning:
12674   // (splat(splat)) -> splat.
12675   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12676     if (isa<UndefValue>(RHS)) {
12677       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12678
12679       std::vector<unsigned> NewMask;
12680       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12681         if (Mask[i] >= 2*e)
12682           NewMask.push_back(2*e);
12683         else
12684           NewMask.push_back(LHSMask[Mask[i]]);
12685       
12686       // If the result mask is equal to the src shuffle or this shuffle mask, do
12687       // the replacement.
12688       if (NewMask == LHSMask || NewMask == Mask) {
12689         unsigned LHSInNElts =
12690           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12691         std::vector<Constant*> Elts;
12692         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12693           if (NewMask[i] >= LHSInNElts*2) {
12694             Elts.push_back(UndefValue::get(Type::Int32Ty));
12695           } else {
12696             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12697           }
12698         }
12699         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12700                                      LHSSVI->getOperand(1),
12701                                      ConstantVector::get(Elts));
12702       }
12703     }
12704   }
12705
12706   return MadeChange ? &SVI : 0;
12707 }
12708
12709
12710
12711
12712 /// TryToSinkInstruction - Try to move the specified instruction from its
12713 /// current block into the beginning of DestBlock, which can only happen if it's
12714 /// safe to move the instruction past all of the instructions between it and the
12715 /// end of its block.
12716 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12717   assert(I->hasOneUse() && "Invariants didn't hold!");
12718
12719   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12720   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12721     return false;
12722
12723   // Do not sink alloca instructions out of the entry block.
12724   if (isa<AllocaInst>(I) && I->getParent() ==
12725         &DestBlock->getParent()->getEntryBlock())
12726     return false;
12727
12728   // We can only sink load instructions if there is nothing between the load and
12729   // the end of block that could change the value.
12730   if (I->mayReadFromMemory()) {
12731     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12732          Scan != E; ++Scan)
12733       if (Scan->mayWriteToMemory())
12734         return false;
12735   }
12736
12737   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12738
12739   CopyPrecedingStopPoint(I, InsertPos);
12740   I->moveBefore(InsertPos);
12741   ++NumSunkInst;
12742   return true;
12743 }
12744
12745
12746 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12747 /// all reachable code to the worklist.
12748 ///
12749 /// This has a couple of tricks to make the code faster and more powerful.  In
12750 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12751 /// them to the worklist (this significantly speeds up instcombine on code where
12752 /// many instructions are dead or constant).  Additionally, if we find a branch
12753 /// whose condition is a known constant, we only visit the reachable successors.
12754 ///
12755 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12756                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12757                                        InstCombiner &IC,
12758                                        const TargetData *TD) {
12759   SmallVector<BasicBlock*, 256> Worklist;
12760   Worklist.push_back(BB);
12761
12762   while (!Worklist.empty()) {
12763     BB = Worklist.back();
12764     Worklist.pop_back();
12765     
12766     // We have now visited this block!  If we've already been here, ignore it.
12767     if (!Visited.insert(BB)) continue;
12768
12769     DbgInfoIntrinsic *DBI_Prev = NULL;
12770     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12771       Instruction *Inst = BBI++;
12772       
12773       // DCE instruction if trivially dead.
12774       if (isInstructionTriviallyDead(Inst)) {
12775         ++NumDeadInst;
12776         DOUT << "IC: DCE: " << *Inst;
12777         Inst->eraseFromParent();
12778         continue;
12779       }
12780       
12781       // ConstantProp instruction if trivially constant.
12782       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12783         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12784         Inst->replaceAllUsesWith(C);
12785         ++NumConstProp;
12786         Inst->eraseFromParent();
12787         continue;
12788       }
12789      
12790       // If there are two consecutive llvm.dbg.stoppoint calls then
12791       // it is likely that the optimizer deleted code in between these
12792       // two intrinsics. 
12793       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12794       if (DBI_Next) {
12795         if (DBI_Prev
12796             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12797             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12798           IC.RemoveFromWorkList(DBI_Prev);
12799           DBI_Prev->eraseFromParent();
12800         }
12801         DBI_Prev = DBI_Next;
12802       } else {
12803         DBI_Prev = 0;
12804       }
12805
12806       IC.AddToWorkList(Inst);
12807     }
12808
12809     // Recursively visit successors.  If this is a branch or switch on a
12810     // constant, only visit the reachable successor.
12811     TerminatorInst *TI = BB->getTerminator();
12812     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12813       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12814         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12815         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12816         Worklist.push_back(ReachableBB);
12817         continue;
12818       }
12819     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12820       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12821         // See if this is an explicit destination.
12822         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12823           if (SI->getCaseValue(i) == Cond) {
12824             BasicBlock *ReachableBB = SI->getSuccessor(i);
12825             Worklist.push_back(ReachableBB);
12826             continue;
12827           }
12828         
12829         // Otherwise it is the default destination.
12830         Worklist.push_back(SI->getSuccessor(0));
12831         continue;
12832       }
12833     }
12834     
12835     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12836       Worklist.push_back(TI->getSuccessor(i));
12837   }
12838 }
12839
12840 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12841   bool Changed = false;
12842   TD = &getAnalysis<TargetData>();
12843   
12844   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12845              << F.getNameStr() << "\n");
12846
12847   {
12848     // Do a depth-first traversal of the function, populate the worklist with
12849     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12850     // track of which blocks we visit.
12851     SmallPtrSet<BasicBlock*, 64> Visited;
12852     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12853
12854     // Do a quick scan over the function.  If we find any blocks that are
12855     // unreachable, remove any instructions inside of them.  This prevents
12856     // the instcombine code from having to deal with some bad special cases.
12857     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12858       if (!Visited.count(BB)) {
12859         Instruction *Term = BB->getTerminator();
12860         while (Term != BB->begin()) {   // Remove instrs bottom-up
12861           BasicBlock::iterator I = Term; --I;
12862
12863           DOUT << "IC: DCE: " << *I;
12864           // A debug intrinsic shouldn't force another iteration if we weren't
12865           // going to do one without it.
12866           if (!isa<DbgInfoIntrinsic>(I)) {
12867             ++NumDeadInst;
12868             Changed = true;
12869           }
12870           if (!I->use_empty())
12871             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12872           I->eraseFromParent();
12873         }
12874       }
12875   }
12876
12877   while (!Worklist.empty()) {
12878     Instruction *I = RemoveOneFromWorkList();
12879     if (I == 0) continue;  // skip null values.
12880
12881     // Check to see if we can DCE the instruction.
12882     if (isInstructionTriviallyDead(I)) {
12883       // Add operands to the worklist.
12884       if (I->getNumOperands() < 4)
12885         AddUsesToWorkList(*I);
12886       ++NumDeadInst;
12887
12888       DOUT << "IC: DCE: " << *I;
12889
12890       I->eraseFromParent();
12891       RemoveFromWorkList(I);
12892       Changed = true;
12893       continue;
12894     }
12895
12896     // Instruction isn't dead, see if we can constant propagate it.
12897     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12898       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12899
12900       // Add operands to the worklist.
12901       AddUsesToWorkList(*I);
12902       ReplaceInstUsesWith(*I, C);
12903
12904       ++NumConstProp;
12905       I->eraseFromParent();
12906       RemoveFromWorkList(I);
12907       Changed = true;
12908       continue;
12909     }
12910
12911     if (TD &&
12912         (I->getType()->getTypeID() == Type::VoidTyID ||
12913          I->isTrapping())) {
12914       // See if we can constant fold its operands.
12915       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12916         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12917           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12918             if (NewC != CE) {
12919               i->set(NewC);
12920               Changed = true;
12921             }
12922     }
12923
12924     // See if we can trivially sink this instruction to a successor basic block.
12925     if (I->hasOneUse()) {
12926       BasicBlock *BB = I->getParent();
12927       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12928       if (UserParent != BB) {
12929         bool UserIsSuccessor = false;
12930         // See if the user is one of our successors.
12931         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12932           if (*SI == UserParent) {
12933             UserIsSuccessor = true;
12934             break;
12935           }
12936
12937         // If the user is one of our immediate successors, and if that successor
12938         // only has us as a predecessors (we'd have to split the critical edge
12939         // otherwise), we can keep going.
12940         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12941             next(pred_begin(UserParent)) == pred_end(UserParent))
12942           // Okay, the CFG is simple enough, try to sink this instruction.
12943           Changed |= TryToSinkInstruction(I, UserParent);
12944       }
12945     }
12946
12947     // Now that we have an instruction, try combining it to simplify it...
12948 #ifndef NDEBUG
12949     std::string OrigI;
12950 #endif
12951     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12952     if (Instruction *Result = visit(*I)) {
12953       ++NumCombined;
12954       // Should we replace the old instruction with a new one?
12955       if (Result != I) {
12956         DOUT << "IC: Old = " << *I
12957              << "    New = " << *Result;
12958
12959         // Everything uses the new instruction now.
12960         I->replaceAllUsesWith(Result);
12961
12962         // Push the new instruction and any users onto the worklist.
12963         AddToWorkList(Result);
12964         AddUsersToWorkList(*Result);
12965
12966         // Move the name to the new instruction first.
12967         Result->takeName(I);
12968
12969         // Insert the new instruction into the basic block...
12970         BasicBlock *InstParent = I->getParent();
12971         BasicBlock::iterator InsertPos = I;
12972
12973         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12974           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12975             ++InsertPos;
12976
12977         InstParent->getInstList().insert(InsertPos, Result);
12978
12979         // Make sure that we reprocess all operands now that we reduced their
12980         // use counts.
12981         AddUsesToWorkList(*I);
12982
12983         // Instructions can end up on the worklist more than once.  Make sure
12984         // we do not process an instruction that has been deleted.
12985         RemoveFromWorkList(I);
12986
12987         // Erase the old instruction.
12988         InstParent->getInstList().erase(I);
12989       } else {
12990 #ifndef NDEBUG
12991         DOUT << "IC: Mod = " << OrigI
12992              << "    New = " << *I;
12993 #endif
12994
12995         // If the instruction was modified, it's possible that it is now dead.
12996         // if so, remove it.
12997         if (isInstructionTriviallyDead(I)) {
12998           // Make sure we process all operands now that we are reducing their
12999           // use counts.
13000           AddUsesToWorkList(*I);
13001
13002           // Instructions may end up in the worklist more than once.  Erase all
13003           // occurrences of this instruction.
13004           RemoveFromWorkList(I);
13005           I->eraseFromParent();
13006         } else {
13007           AddToWorkList(I);
13008           AddUsersToWorkList(*I);
13009         }
13010       }
13011       Changed = true;
13012     }
13013   }
13014
13015   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13016     
13017   // Do an explicit clear, this shrinks the map if needed.
13018   WorklistMap.clear();
13019   return Changed;
13020 }
13021
13022
13023 bool InstCombiner::runOnFunction(Function &F) {
13024   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13025   
13026   bool EverMadeChange = false;
13027
13028   // Iterate while there is work to do.
13029   unsigned Iteration = 0;
13030   while (DoOneIteration(F, Iteration++))
13031     EverMadeChange = true;
13032   return EverMadeChange;
13033 }
13034
13035 FunctionPass *llvm::createInstructionCombiningPass() {
13036   return new InstCombiner();
13037 }