remove some more Context arguments.
[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/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/MemoryBuiltins.h"
46 #include "llvm/Analysis/ValueTracking.h"
47 #include "llvm/Target/TargetData.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 #include "llvm/Support/CallSite.h"
51 #include "llvm/Support/ConstantRange.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/GetElementPtrTypeIterator.h"
55 #include "llvm/Support/InstVisitor.h"
56 #include "llvm/Support/IRBuilder.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/PatternMatch.h"
59 #include "llvm/Support/TargetFolder.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/ADT/DenseMap.h"
62 #include "llvm/ADT/SmallVector.h"
63 #include "llvm/ADT/SmallPtrSet.h"
64 #include "llvm/ADT/Statistic.h"
65 #include "llvm/ADT/STLExtras.h"
66 #include <algorithm>
67 #include <climits>
68 using namespace llvm;
69 using namespace llvm::PatternMatch;
70
71 STATISTIC(NumCombined , "Number of insts combined");
72 STATISTIC(NumConstProp, "Number of constant folds");
73 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
74 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
75 STATISTIC(NumSunkInst , "Number of instructions sunk");
76
77 namespace {
78   /// InstCombineWorklist - This is the worklist management logic for
79   /// InstCombine.
80   class InstCombineWorklist {
81     SmallVector<Instruction*, 256> Worklist;
82     DenseMap<Instruction*, unsigned> WorklistMap;
83     
84     void operator=(const InstCombineWorklist&RHS);   // DO NOT IMPLEMENT
85     InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
86   public:
87     InstCombineWorklist() {}
88     
89     bool isEmpty() const { return Worklist.empty(); }
90     
91     /// Add - Add the specified instruction to the worklist if it isn't already
92     /// in it.
93     void Add(Instruction *I) {
94       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
95         DEBUG(errs() << "IC: ADD: " << *I << '\n');
96         Worklist.push_back(I);
97       }
98     }
99     
100     void AddValue(Value *V) {
101       if (Instruction *I = dyn_cast<Instruction>(V))
102         Add(I);
103     }
104     
105     /// AddInitialGroup - Add the specified batch of stuff in reverse order.
106     /// which should only be done when the worklist is empty and when the group
107     /// has no duplicates.
108     void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
109       assert(Worklist.empty() && "Worklist must be empty to add initial group");
110       Worklist.reserve(NumEntries+16);
111       DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
112       for (; NumEntries; --NumEntries) {
113         Instruction *I = List[NumEntries-1];
114         WorklistMap.insert(std::make_pair(I, Worklist.size()));
115         Worklist.push_back(I);
116       }
117     }
118     
119     // Remove - remove I from the worklist if it exists.
120     void Remove(Instruction *I) {
121       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
122       if (It == WorklistMap.end()) return; // Not in worklist.
123       
124       // Don't bother moving everything down, just null out the slot.
125       Worklist[It->second] = 0;
126       
127       WorklistMap.erase(It);
128     }
129     
130     Instruction *RemoveOne() {
131       Instruction *I = Worklist.back();
132       Worklist.pop_back();
133       WorklistMap.erase(I);
134       return I;
135     }
136
137     /// AddUsersToWorkList - When an instruction is simplified, add all users of
138     /// the instruction to the work lists because they might get more simplified
139     /// now.
140     ///
141     void AddUsersToWorkList(Instruction &I) {
142       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
143            UI != UE; ++UI)
144         Add(cast<Instruction>(*UI));
145     }
146     
147     
148     /// Zap - check that the worklist is empty and nuke the backing store for
149     /// the map if it is large.
150     void Zap() {
151       assert(WorklistMap.empty() && "Worklist empty, but map not?");
152       
153       // Do an explicit clear, this shrinks the map if needed.
154       WorklistMap.clear();
155     }
156   };
157 } // end anonymous namespace.
158
159
160 namespace {
161   /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
162   /// just like the normal insertion helper, but also adds any new instructions
163   /// to the instcombine worklist.
164   class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
165     InstCombineWorklist &Worklist;
166   public:
167     InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
168     
169     void InsertHelper(Instruction *I, const Twine &Name,
170                       BasicBlock *BB, BasicBlock::iterator InsertPt) const {
171       IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
172       Worklist.Add(I);
173     }
174   };
175 } // end anonymous namespace
176
177
178 namespace {
179   class InstCombiner : public FunctionPass,
180                        public InstVisitor<InstCombiner, Instruction*> {
181     TargetData *TD;
182     bool MustPreserveLCSSA;
183     bool MadeIRChange;
184   public:
185     /// Worklist - All of the instructions that need to be simplified.
186     InstCombineWorklist Worklist;
187
188     /// Builder - This is an IRBuilder that automatically inserts new
189     /// instructions into the worklist when they are created.
190     typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
191     BuilderTy *Builder;
192         
193     static char ID; // Pass identification, replacement for typeid
194     InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
195
196     LLVMContext *Context;
197     LLVMContext *getContext() const { return Context; }
198
199   public:
200     virtual bool runOnFunction(Function &F);
201     
202     bool DoOneIteration(Function &F, unsigned ItNum);
203
204     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
205       AU.addPreservedID(LCSSAID);
206       AU.setPreservesCFG();
207     }
208
209     TargetData *getTargetData() const { return TD; }
210
211     // Visitation implementation - Implement instruction combining for different
212     // instruction types.  The semantics are as follows:
213     // Return Value:
214     //    null        - No change was made
215     //     I          - Change was made, I is still valid, I may be dead though
216     //   otherwise    - Change was made, replace I with returned instruction
217     //
218     Instruction *visitAdd(BinaryOperator &I);
219     Instruction *visitFAdd(BinaryOperator &I);
220     Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
221     Instruction *visitSub(BinaryOperator &I);
222     Instruction *visitFSub(BinaryOperator &I);
223     Instruction *visitMul(BinaryOperator &I);
224     Instruction *visitFMul(BinaryOperator &I);
225     Instruction *visitURem(BinaryOperator &I);
226     Instruction *visitSRem(BinaryOperator &I);
227     Instruction *visitFRem(BinaryOperator &I);
228     bool SimplifyDivRemOfSelect(BinaryOperator &I);
229     Instruction *commonRemTransforms(BinaryOperator &I);
230     Instruction *commonIRemTransforms(BinaryOperator &I);
231     Instruction *commonDivTransforms(BinaryOperator &I);
232     Instruction *commonIDivTransforms(BinaryOperator &I);
233     Instruction *visitUDiv(BinaryOperator &I);
234     Instruction *visitSDiv(BinaryOperator &I);
235     Instruction *visitFDiv(BinaryOperator &I);
236     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
237     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
238     Instruction *visitAnd(BinaryOperator &I);
239     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
240     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
241     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
242                                      Value *A, Value *B, Value *C);
243     Instruction *visitOr (BinaryOperator &I);
244     Instruction *visitXor(BinaryOperator &I);
245     Instruction *visitShl(BinaryOperator &I);
246     Instruction *visitAShr(BinaryOperator &I);
247     Instruction *visitLShr(BinaryOperator &I);
248     Instruction *commonShiftTransforms(BinaryOperator &I);
249     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
250                                       Constant *RHSC);
251     Instruction *visitFCmpInst(FCmpInst &I);
252     Instruction *visitICmpInst(ICmpInst &I);
253     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
254     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
255                                                 Instruction *LHS,
256                                                 ConstantInt *RHS);
257     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
258                                 ConstantInt *DivRHS);
259
260     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
261                              ICmpInst::Predicate Cond, Instruction &I);
262     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
263                                      BinaryOperator &I);
264     Instruction *commonCastTransforms(CastInst &CI);
265     Instruction *commonIntCastTransforms(CastInst &CI);
266     Instruction *commonPointerCastTransforms(CastInst &CI);
267     Instruction *visitTrunc(TruncInst &CI);
268     Instruction *visitZExt(ZExtInst &CI);
269     Instruction *visitSExt(SExtInst &CI);
270     Instruction *visitFPTrunc(FPTruncInst &CI);
271     Instruction *visitFPExt(CastInst &CI);
272     Instruction *visitFPToUI(FPToUIInst &FI);
273     Instruction *visitFPToSI(FPToSIInst &FI);
274     Instruction *visitUIToFP(CastInst &CI);
275     Instruction *visitSIToFP(CastInst &CI);
276     Instruction *visitPtrToInt(PtrToIntInst &CI);
277     Instruction *visitIntToPtr(IntToPtrInst &CI);
278     Instruction *visitBitCast(BitCastInst &CI);
279     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
280                                 Instruction *FI);
281     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
282     Instruction *visitSelectInst(SelectInst &SI);
283     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
284     Instruction *visitCallInst(CallInst &CI);
285     Instruction *visitInvokeInst(InvokeInst &II);
286     Instruction *visitPHINode(PHINode &PN);
287     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
288     Instruction *visitAllocaInst(AllocaInst &AI);
289     Instruction *visitFree(Instruction &FI);
290     Instruction *visitLoadInst(LoadInst &LI);
291     Instruction *visitStoreInst(StoreInst &SI);
292     Instruction *visitBranchInst(BranchInst &BI);
293     Instruction *visitSwitchInst(SwitchInst &SI);
294     Instruction *visitInsertElementInst(InsertElementInst &IE);
295     Instruction *visitExtractElementInst(ExtractElementInst &EI);
296     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
297     Instruction *visitExtractValueInst(ExtractValueInst &EV);
298
299     // visitInstruction - Specify what to return for unhandled instructions...
300     Instruction *visitInstruction(Instruction &I) { return 0; }
301
302   private:
303     Instruction *visitCallSite(CallSite CS);
304     bool transformConstExprCastCall(CallSite CS);
305     Instruction *transformCallThroughTrampoline(CallSite CS);
306     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
307                                    bool DoXform = true);
308     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
309     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
310
311
312   public:
313     // InsertNewInstBefore - insert an instruction New before instruction Old
314     // in the program.  Add the new instruction to the worklist.
315     //
316     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
317       assert(New && New->getParent() == 0 &&
318              "New instruction already inserted into a basic block!");
319       BasicBlock *BB = Old.getParent();
320       BB->getInstList().insert(&Old, New);  // Insert inst
321       Worklist.Add(New);
322       return New;
323     }
324         
325     // ReplaceInstUsesWith - This method is to be used when an instruction is
326     // found to be dead, replacable with another preexisting expression.  Here
327     // we add all uses of I to the worklist, replace all uses of I with the new
328     // value, then return I, so that the inst combiner will know that I was
329     // modified.
330     //
331     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
332       Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
333       
334       // If we are replacing the instruction with itself, this must be in a
335       // segment of unreachable code, so just clobber the instruction.
336       if (&I == V) 
337         V = UndefValue::get(I.getType());
338         
339       I.replaceAllUsesWith(V);
340       return &I;
341     }
342
343     // EraseInstFromFunction - When dealing with an instruction that has side
344     // effects or produces a void value, we can't rely on DCE to delete the
345     // instruction.  Instead, visit methods should return the value returned by
346     // this function.
347     Instruction *EraseInstFromFunction(Instruction &I) {
348       DEBUG(errs() << "IC: ERASE " << I << '\n');
349
350       assert(I.use_empty() && "Cannot erase instruction that is used!");
351       // Make sure that we reprocess all operands now that we reduced their
352       // use counts.
353       if (I.getNumOperands() < 8) {
354         for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
355           if (Instruction *Op = dyn_cast<Instruction>(*i))
356             Worklist.Add(Op);
357       }
358       Worklist.Remove(&I);
359       I.eraseFromParent();
360       MadeIRChange = true;
361       return 0;  // Don't do anything with FI
362     }
363         
364     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
365                            APInt &KnownOne, unsigned Depth = 0) const {
366       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
367     }
368     
369     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
370                            unsigned Depth = 0) const {
371       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
372     }
373     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
374       return llvm::ComputeNumSignBits(Op, TD, Depth);
375     }
376
377   private:
378
379     /// SimplifyCommutative - This performs a few simplifications for 
380     /// commutative operators.
381     bool SimplifyCommutative(BinaryOperator &I);
382
383     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
384     /// most-complex to least-complex order.
385     bool SimplifyCompare(CmpInst &I);
386
387     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
388     /// based on the demanded bits.
389     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
390                                    APInt& KnownZero, APInt& KnownOne,
391                                    unsigned Depth);
392     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
393                               APInt& KnownZero, APInt& KnownOne,
394                               unsigned Depth=0);
395         
396     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
397     /// SimplifyDemandedBits knows about.  See if the instruction has any
398     /// properties that allow us to simplify its operands.
399     bool SimplifyDemandedInstructionBits(Instruction &Inst);
400         
401     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
402                                       APInt& UndefElts, unsigned Depth = 0);
403       
404     // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
405     // which has a PHI node as operand #0, see if we can fold the instruction
406     // into the PHI (which is only possible if all operands to the PHI are
407     // constants).
408     //
409     // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
410     // that would normally be unprofitable because they strongly encourage jump
411     // threading.
412     Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
413
414     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
415     // operator and they all are only used by the PHI, PHI together their
416     // inputs, and do the operation once, to the result of the PHI.
417     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
418     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
419     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
420     Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
421
422     
423     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
424                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
425     
426     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
427                               bool isSub, Instruction &I);
428     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
429                                  bool isSigned, bool Inside, Instruction &IB);
430     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
431     Instruction *MatchBSwap(BinaryOperator &I);
432     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
433     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
434     Instruction *SimplifyMemSet(MemSetInst *MI);
435
436
437     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
438
439     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
440                                     unsigned CastOpc, int &NumCastsRemoved);
441     unsigned GetOrEnforceKnownAlignment(Value *V,
442                                         unsigned PrefAlign = 0);
443
444   };
445 } // end anonymous namespace
446
447 char InstCombiner::ID = 0;
448 static RegisterPass<InstCombiner>
449 X("instcombine", "Combine redundant instructions");
450
451 // getComplexity:  Assign a complexity or rank value to LLVM Values...
452 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
453 static unsigned getComplexity(Value *V) {
454   if (isa<Instruction>(V)) {
455     if (BinaryOperator::isNeg(V) ||
456         BinaryOperator::isFNeg(V) ||
457         BinaryOperator::isNot(V))
458       return 3;
459     return 4;
460   }
461   if (isa<Argument>(V)) return 3;
462   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
463 }
464
465 // isOnlyUse - Return true if this instruction will be deleted if we stop using
466 // it.
467 static bool isOnlyUse(Value *V) {
468   return V->hasOneUse() || isa<Constant>(V);
469 }
470
471 // getPromotedType - Return the specified type promoted as it would be to pass
472 // though a va_arg area...
473 static const Type *getPromotedType(const Type *Ty) {
474   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
475     if (ITy->getBitWidth() < 32)
476       return Type::getInt32Ty(Ty->getContext());
477   }
478   return Ty;
479 }
480
481 /// getBitCastOperand - If the specified operand is a CastInst, a constant
482 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
483 /// operand value, otherwise return null.
484 static Value *getBitCastOperand(Value *V) {
485   if (Operator *O = dyn_cast<Operator>(V)) {
486     if (O->getOpcode() == Instruction::BitCast)
487       return O->getOperand(0);
488     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
489       if (GEP->hasAllZeroIndices())
490         return GEP->getPointerOperand();
491   }
492   return 0;
493 }
494
495 /// This function is a wrapper around CastInst::isEliminableCastPair. It
496 /// simply extracts arguments and returns what that function returns.
497 static Instruction::CastOps 
498 isEliminableCastPair(
499   const CastInst *CI, ///< The first cast instruction
500   unsigned opcode,       ///< The opcode of the second cast instruction
501   const Type *DstTy,     ///< The target type for the second cast instruction
502   TargetData *TD         ///< The target data for pointer size
503 ) {
504
505   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
506   const Type *MidTy = CI->getType();                  // B from above
507
508   // Get the opcodes of the two Cast instructions
509   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
510   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
511
512   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
513                                                 DstTy,
514                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
515   
516   // We don't want to form an inttoptr or ptrtoint that converts to an integer
517   // type that differs from the pointer size.
518   if ((Res == Instruction::IntToPtr &&
519           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
520       (Res == Instruction::PtrToInt &&
521           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
522     Res = 0;
523   
524   return Instruction::CastOps(Res);
525 }
526
527 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
528 /// in any code being generated.  It does not require codegen if V is simple
529 /// enough or if the cast can be folded into other casts.
530 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
531                               const Type *Ty, TargetData *TD) {
532   if (V->getType() == Ty || isa<Constant>(V)) return false;
533   
534   // If this is another cast that can be eliminated, it isn't codegen either.
535   if (const CastInst *CI = dyn_cast<CastInst>(V))
536     if (isEliminableCastPair(CI, opcode, Ty, TD))
537       return false;
538   return true;
539 }
540
541 // SimplifyCommutative - This performs a few simplifications for commutative
542 // operators:
543 //
544 //  1. Order operands such that they are listed from right (least complex) to
545 //     left (most complex).  This puts constants before unary operators before
546 //     binary operators.
547 //
548 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
549 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
550 //
551 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
552   bool Changed = false;
553   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
554     Changed = !I.swapOperands();
555
556   if (!I.isAssociative()) return Changed;
557   Instruction::BinaryOps Opcode = I.getOpcode();
558   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
559     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
560       if (isa<Constant>(I.getOperand(1))) {
561         Constant *Folded = ConstantExpr::get(I.getOpcode(),
562                                              cast<Constant>(I.getOperand(1)),
563                                              cast<Constant>(Op->getOperand(1)));
564         I.setOperand(0, Op->getOperand(0));
565         I.setOperand(1, Folded);
566         return true;
567       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
568         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
569             isOnlyUse(Op) && isOnlyUse(Op1)) {
570           Constant *C1 = cast<Constant>(Op->getOperand(1));
571           Constant *C2 = cast<Constant>(Op1->getOperand(1));
572
573           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
574           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
575           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
576                                                     Op1->getOperand(0),
577                                                     Op1->getName(), &I);
578           Worklist.Add(New);
579           I.setOperand(0, New);
580           I.setOperand(1, Folded);
581           return true;
582         }
583     }
584   return Changed;
585 }
586
587 /// SimplifyCompare - For a CmpInst this function just orders the operands
588 /// so that theyare listed from right (least complex) to left (most complex).
589 /// This puts constants before unary operators before binary operators.
590 bool InstCombiner::SimplifyCompare(CmpInst &I) {
591   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
592     return false;
593   I.swapOperands();
594   // Compare instructions are not associative so there's nothing else we can do.
595   return true;
596 }
597
598 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
599 // if the LHS is a constant zero (which is the 'negate' form).
600 //
601 static inline Value *dyn_castNegVal(Value *V) {
602   if (BinaryOperator::isNeg(V))
603     return BinaryOperator::getNegArgument(V);
604
605   // Constants can be considered to be negated values if they can be folded.
606   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
607     return ConstantExpr::getNeg(C);
608
609   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
610     if (C->getType()->getElementType()->isInteger())
611       return ConstantExpr::getNeg(C);
612
613   return 0;
614 }
615
616 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
617 // instruction if the LHS is a constant negative zero (which is the 'negate'
618 // form).
619 //
620 static inline Value *dyn_castFNegVal(Value *V) {
621   if (BinaryOperator::isFNeg(V))
622     return BinaryOperator::getFNegArgument(V);
623
624   // Constants can be considered to be negated values if they can be folded.
625   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
626     return ConstantExpr::getFNeg(C);
627
628   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
629     if (C->getType()->getElementType()->isFloatingPoint())
630       return ConstantExpr::getFNeg(C);
631
632   return 0;
633 }
634
635 /// isFreeToInvert - Return true if the specified value is free to invert (apply
636 /// ~ to).  This happens in cases where the ~ can be eliminated.
637 static inline bool isFreeToInvert(Value *V) {
638   // ~(~(X)) -> X.
639   if (BinaryOperator::isNot(V))
640     return true;
641   
642   // Constants can be considered to be not'ed values.
643   if (isa<ConstantInt>(V))
644     return true;
645   
646   // Compares can be inverted if they have a single use.
647   if (CmpInst *CI = dyn_cast<CmpInst>(V))
648     return CI->hasOneUse();
649   
650   return false;
651 }
652
653 static inline Value *dyn_castNotVal(Value *V) {
654   // If this is not(not(x)) don't return that this is a not: we want the two
655   // not's to be folded first.
656   if (BinaryOperator::isNot(V)) {
657     Value *Operand = BinaryOperator::getNotArgument(V);
658     if (!isFreeToInvert(Operand))
659       return Operand;
660   }
661
662   // Constants can be considered to be not'ed values...
663   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
664     return ConstantInt::get(C->getType(), ~C->getValue());
665   return 0;
666 }
667
668
669
670 // dyn_castFoldableMul - If this value is a multiply that can be folded into
671 // other computations (because it has a constant operand), return the
672 // non-constant operand of the multiply, and set CST to point to the multiplier.
673 // Otherwise, return null.
674 //
675 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
676   if (V->hasOneUse() && V->getType()->isInteger())
677     if (Instruction *I = dyn_cast<Instruction>(V)) {
678       if (I->getOpcode() == Instruction::Mul)
679         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
680           return I->getOperand(0);
681       if (I->getOpcode() == Instruction::Shl)
682         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
683           // The multiplier is really 1 << CST.
684           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
685           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
686           CST = ConstantInt::get(V->getType()->getContext(),
687                                  APInt(BitWidth, 1).shl(CSTVal));
688           return I->getOperand(0);
689         }
690     }
691   return 0;
692 }
693
694 /// AddOne - Add one to a ConstantInt
695 static Constant *AddOne(Constant *C) {
696   return ConstantExpr::getAdd(C, 
697     ConstantInt::get(C->getType(), 1));
698 }
699 /// SubOne - Subtract one from a ConstantInt
700 static Constant *SubOne(ConstantInt *C) {
701   return ConstantExpr::getSub(C, 
702     ConstantInt::get(C->getType(), 1));
703 }
704 /// MultiplyOverflows - True if the multiply can not be expressed in an int
705 /// this size.
706 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
707   uint32_t W = C1->getBitWidth();
708   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
709   if (sign) {
710     LHSExt.sext(W * 2);
711     RHSExt.sext(W * 2);
712   } else {
713     LHSExt.zext(W * 2);
714     RHSExt.zext(W * 2);
715   }
716
717   APInt MulExt = LHSExt * RHSExt;
718
719   if (sign) {
720     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
721     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
722     return MulExt.slt(Min) || MulExt.sgt(Max);
723   } else 
724     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
725 }
726
727
728 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
729 /// specified instruction is a constant integer.  If so, check to see if there
730 /// are any bits set in the constant that are not demanded.  If so, shrink the
731 /// constant and return true.
732 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
733                                    APInt Demanded) {
734   assert(I && "No instruction?");
735   assert(OpNo < I->getNumOperands() && "Operand index too large");
736
737   // If the operand is not a constant integer, nothing to do.
738   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
739   if (!OpC) return false;
740
741   // If there are no bits set that aren't demanded, nothing to do.
742   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
743   if ((~Demanded & OpC->getValue()) == 0)
744     return false;
745
746   // This instruction is producing bits that are not demanded. Shrink the RHS.
747   Demanded &= OpC->getValue();
748   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
749   return true;
750 }
751
752 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
753 // set of known zero and one bits, compute the maximum and minimum values that
754 // could have the specified known zero and known one bits, returning them in
755 // min/max.
756 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
757                                                    const APInt& KnownOne,
758                                                    APInt& Min, APInt& Max) {
759   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
760          KnownZero.getBitWidth() == Min.getBitWidth() &&
761          KnownZero.getBitWidth() == Max.getBitWidth() &&
762          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
763   APInt UnknownBits = ~(KnownZero|KnownOne);
764
765   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
766   // bit if it is unknown.
767   Min = KnownOne;
768   Max = KnownOne|UnknownBits;
769   
770   if (UnknownBits.isNegative()) { // Sign bit is unknown
771     Min.set(Min.getBitWidth()-1);
772     Max.clear(Max.getBitWidth()-1);
773   }
774 }
775
776 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
777 // a set of known zero and one bits, compute the maximum and minimum values that
778 // could have the specified known zero and known one bits, returning them in
779 // min/max.
780 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
781                                                      const APInt &KnownOne,
782                                                      APInt &Min, APInt &Max) {
783   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
784          KnownZero.getBitWidth() == Min.getBitWidth() &&
785          KnownZero.getBitWidth() == Max.getBitWidth() &&
786          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
787   APInt UnknownBits = ~(KnownZero|KnownOne);
788   
789   // The minimum value is when the unknown bits are all zeros.
790   Min = KnownOne;
791   // The maximum value is when the unknown bits are all ones.
792   Max = KnownOne|UnknownBits;
793 }
794
795 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
796 /// SimplifyDemandedBits knows about.  See if the instruction has any
797 /// properties that allow us to simplify its operands.
798 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
799   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
800   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
801   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
802   
803   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
804                                      KnownZero, KnownOne, 0);
805   if (V == 0) return false;
806   if (V == &Inst) return true;
807   ReplaceInstUsesWith(Inst, V);
808   return true;
809 }
810
811 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
812 /// specified instruction operand if possible, updating it in place.  It returns
813 /// true if it made any change and false otherwise.
814 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
815                                         APInt &KnownZero, APInt &KnownOne,
816                                         unsigned Depth) {
817   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
818                                           KnownZero, KnownOne, Depth);
819   if (NewVal == 0) return false;
820   U = NewVal;
821   return true;
822 }
823
824
825 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
826 /// value based on the demanded bits.  When this function is called, it is known
827 /// that only the bits set in DemandedMask of the result of V are ever used
828 /// downstream. Consequently, depending on the mask and V, it may be possible
829 /// to replace V with a constant or one of its operands. In such cases, this
830 /// function does the replacement and returns true. In all other cases, it
831 /// returns false after analyzing the expression and setting KnownOne and known
832 /// to be one in the expression.  KnownZero contains all the bits that are known
833 /// to be zero in the expression. These are provided to potentially allow the
834 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
835 /// the expression. KnownOne and KnownZero always follow the invariant that 
836 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
837 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
838 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
839 /// and KnownOne must all be the same.
840 ///
841 /// This returns null if it did not change anything and it permits no
842 /// simplification.  This returns V itself if it did some simplification of V's
843 /// operands based on the information about what bits are demanded. This returns
844 /// some other non-null value if it found out that V is equal to another value
845 /// in the context where the specified bits are demanded, but not for all users.
846 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
847                                              APInt &KnownZero, APInt &KnownOne,
848                                              unsigned Depth) {
849   assert(V != 0 && "Null pointer of Value???");
850   assert(Depth <= 6 && "Limit Search Depth");
851   uint32_t BitWidth = DemandedMask.getBitWidth();
852   const Type *VTy = V->getType();
853   assert((TD || !isa<PointerType>(VTy)) &&
854          "SimplifyDemandedBits needs to know bit widths!");
855   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
856          (!VTy->isIntOrIntVector() ||
857           VTy->getScalarSizeInBits() == BitWidth) &&
858          KnownZero.getBitWidth() == BitWidth &&
859          KnownOne.getBitWidth() == BitWidth &&
860          "Value *V, DemandedMask, KnownZero and KnownOne "
861          "must have same BitWidth");
862   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
863     // We know all of the bits for a constant!
864     KnownOne = CI->getValue() & DemandedMask;
865     KnownZero = ~KnownOne & DemandedMask;
866     return 0;
867   }
868   if (isa<ConstantPointerNull>(V)) {
869     // We know all of the bits for a constant!
870     KnownOne.clear();
871     KnownZero = DemandedMask;
872     return 0;
873   }
874
875   KnownZero.clear();
876   KnownOne.clear();
877   if (DemandedMask == 0) {   // Not demanding any bits from V.
878     if (isa<UndefValue>(V))
879       return 0;
880     return UndefValue::get(VTy);
881   }
882   
883   if (Depth == 6)        // Limit search depth.
884     return 0;
885   
886   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
887   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
888
889   Instruction *I = dyn_cast<Instruction>(V);
890   if (!I) {
891     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
892     return 0;        // Only analyze instructions.
893   }
894
895   // If there are multiple uses of this value and we aren't at the root, then
896   // we can't do any simplifications of the operands, because DemandedMask
897   // only reflects the bits demanded by *one* of the users.
898   if (Depth != 0 && !I->hasOneUse()) {
899     // Despite the fact that we can't simplify this instruction in all User's
900     // context, we can at least compute the knownzero/knownone bits, and we can
901     // do simplifications that apply to *just* the one user if we know that
902     // this instruction has a simpler value in that context.
903     if (I->getOpcode() == Instruction::And) {
904       // If either the LHS or the RHS are Zero, the result is zero.
905       ComputeMaskedBits(I->getOperand(1), DemandedMask,
906                         RHSKnownZero, RHSKnownOne, Depth+1);
907       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
908                         LHSKnownZero, LHSKnownOne, Depth+1);
909       
910       // If all of the demanded bits are known 1 on one side, return the other.
911       // These bits cannot contribute to the result of the 'and' in this
912       // context.
913       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
914           (DemandedMask & ~LHSKnownZero))
915         return I->getOperand(0);
916       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
917           (DemandedMask & ~RHSKnownZero))
918         return I->getOperand(1);
919       
920       // If all of the demanded bits in the inputs are known zeros, return zero.
921       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
922         return Constant::getNullValue(VTy);
923       
924     } else if (I->getOpcode() == Instruction::Or) {
925       // We can simplify (X|Y) -> X or Y in the user's context if we know that
926       // only bits from X or Y are demanded.
927       
928       // If either the LHS or the RHS are One, the result is One.
929       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
930                         RHSKnownZero, RHSKnownOne, Depth+1);
931       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
932                         LHSKnownZero, LHSKnownOne, Depth+1);
933       
934       // If all of the demanded bits are known zero on one side, return the
935       // other.  These bits cannot contribute to the result of the 'or' in this
936       // context.
937       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
938           (DemandedMask & ~LHSKnownOne))
939         return I->getOperand(0);
940       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
941           (DemandedMask & ~RHSKnownOne))
942         return I->getOperand(1);
943       
944       // If all of the potentially set bits on one side are known to be set on
945       // the other side, just use the 'other' side.
946       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
947           (DemandedMask & (~RHSKnownZero)))
948         return I->getOperand(0);
949       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
950           (DemandedMask & (~LHSKnownZero)))
951         return I->getOperand(1);
952     }
953     
954     // Compute the KnownZero/KnownOne bits to simplify things downstream.
955     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
956     return 0;
957   }
958   
959   // If this is the root being simplified, allow it to have multiple uses,
960   // just set the DemandedMask to all bits so that we can try to simplify the
961   // operands.  This allows visitTruncInst (for example) to simplify the
962   // operand of a trunc without duplicating all the logic below.
963   if (Depth == 0 && !V->hasOneUse())
964     DemandedMask = APInt::getAllOnesValue(BitWidth);
965   
966   switch (I->getOpcode()) {
967   default:
968     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
969     break;
970   case Instruction::And:
971     // If either the LHS or the RHS are Zero, the result is zero.
972     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
973                              RHSKnownZero, RHSKnownOne, Depth+1) ||
974         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
975                              LHSKnownZero, LHSKnownOne, Depth+1))
976       return I;
977     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
978     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
979
980     // If all of the demanded bits are known 1 on one side, return the other.
981     // These bits cannot contribute to the result of the 'and'.
982     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
983         (DemandedMask & ~LHSKnownZero))
984       return I->getOperand(0);
985     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
986         (DemandedMask & ~RHSKnownZero))
987       return I->getOperand(1);
988     
989     // If all of the demanded bits in the inputs are known zeros, return zero.
990     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
991       return Constant::getNullValue(VTy);
992       
993     // If the RHS is a constant, see if we can simplify it.
994     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
995       return I;
996       
997     // Output known-1 bits are only known if set in both the LHS & RHS.
998     RHSKnownOne &= LHSKnownOne;
999     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1000     RHSKnownZero |= LHSKnownZero;
1001     break;
1002   case Instruction::Or:
1003     // If either the LHS or the RHS are One, the result is One.
1004     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1005                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1006         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
1007                              LHSKnownZero, LHSKnownOne, Depth+1))
1008       return I;
1009     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1010     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1011     
1012     // If all of the demanded bits are known zero on one side, return the other.
1013     // These bits cannot contribute to the result of the 'or'.
1014     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1015         (DemandedMask & ~LHSKnownOne))
1016       return I->getOperand(0);
1017     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1018         (DemandedMask & ~RHSKnownOne))
1019       return I->getOperand(1);
1020
1021     // If all of the potentially set bits on one side are known to be set on
1022     // the other side, just use the 'other' side.
1023     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1024         (DemandedMask & (~RHSKnownZero)))
1025       return I->getOperand(0);
1026     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1027         (DemandedMask & (~LHSKnownZero)))
1028       return I->getOperand(1);
1029         
1030     // If the RHS is a constant, see if we can simplify it.
1031     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1032       return I;
1033           
1034     // Output known-0 bits are only known if clear in both the LHS & RHS.
1035     RHSKnownZero &= LHSKnownZero;
1036     // Output known-1 are known to be set if set in either the LHS | RHS.
1037     RHSKnownOne |= LHSKnownOne;
1038     break;
1039   case Instruction::Xor: {
1040     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1041                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1042         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1043                              LHSKnownZero, LHSKnownOne, Depth+1))
1044       return I;
1045     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1046     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1047     
1048     // If all of the demanded bits are known zero on one side, return the other.
1049     // These bits cannot contribute to the result of the 'xor'.
1050     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1051       return I->getOperand(0);
1052     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1053       return I->getOperand(1);
1054     
1055     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1056     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1057                          (RHSKnownOne & LHSKnownOne);
1058     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1059     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1060                         (RHSKnownOne & LHSKnownZero);
1061     
1062     // If all of the demanded bits are known to be zero on one side or the
1063     // other, turn this into an *inclusive* or.
1064     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1065     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1066       Instruction *Or = 
1067         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1068                                  I->getName());
1069       return InsertNewInstBefore(Or, *I);
1070     }
1071     
1072     // If all of the demanded bits on one side are known, and all of the set
1073     // bits on that side are also known to be set on the other side, turn this
1074     // into an AND, as we know the bits will be cleared.
1075     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1076     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1077       // all known
1078       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1079         Constant *AndC = Constant::getIntegerValue(VTy,
1080                                                    ~RHSKnownOne & DemandedMask);
1081         Instruction *And = 
1082           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1083         return InsertNewInstBefore(And, *I);
1084       }
1085     }
1086     
1087     // If the RHS is a constant, see if we can simplify it.
1088     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1089     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1090       return I;
1091     
1092     // If our LHS is an 'and' and if it has one use, and if any of the bits we
1093     // are flipping are known to be set, then the xor is just resetting those
1094     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
1095     // simplifying both of them.
1096     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1097       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1098           isa<ConstantInt>(I->getOperand(1)) &&
1099           isa<ConstantInt>(LHSInst->getOperand(1)) &&
1100           (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1101         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1102         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1103         APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1104         
1105         Constant *AndC =
1106           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1107         Instruction *NewAnd = 
1108           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1109         InsertNewInstBefore(NewAnd, *I);
1110         
1111         Constant *XorC =
1112           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1113         Instruction *NewXor =
1114           BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1115         return InsertNewInstBefore(NewXor, *I);
1116       }
1117           
1118           
1119     RHSKnownZero = KnownZeroOut;
1120     RHSKnownOne  = KnownOneOut;
1121     break;
1122   }
1123   case Instruction::Select:
1124     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1125                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1126         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1127                              LHSKnownZero, LHSKnownOne, Depth+1))
1128       return I;
1129     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1130     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1131     
1132     // If the operands are constants, see if we can simplify them.
1133     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1134         ShrinkDemandedConstant(I, 2, DemandedMask))
1135       return I;
1136     
1137     // Only known if known in both the LHS and RHS.
1138     RHSKnownOne &= LHSKnownOne;
1139     RHSKnownZero &= LHSKnownZero;
1140     break;
1141   case Instruction::Trunc: {
1142     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1143     DemandedMask.zext(truncBf);
1144     RHSKnownZero.zext(truncBf);
1145     RHSKnownOne.zext(truncBf);
1146     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1147                              RHSKnownZero, RHSKnownOne, Depth+1))
1148       return I;
1149     DemandedMask.trunc(BitWidth);
1150     RHSKnownZero.trunc(BitWidth);
1151     RHSKnownOne.trunc(BitWidth);
1152     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1153     break;
1154   }
1155   case Instruction::BitCast:
1156     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1157       return false;  // vector->int or fp->int?
1158
1159     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1160       if (const VectorType *SrcVTy =
1161             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1162         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1163           // Don't touch a bitcast between vectors of different element counts.
1164           return false;
1165       } else
1166         // Don't touch a scalar-to-vector bitcast.
1167         return false;
1168     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1169       // Don't touch a vector-to-scalar bitcast.
1170       return false;
1171
1172     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1173                              RHSKnownZero, RHSKnownOne, Depth+1))
1174       return I;
1175     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1176     break;
1177   case Instruction::ZExt: {
1178     // Compute the bits in the result that are not present in the input.
1179     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1180     
1181     DemandedMask.trunc(SrcBitWidth);
1182     RHSKnownZero.trunc(SrcBitWidth);
1183     RHSKnownOne.trunc(SrcBitWidth);
1184     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1185                              RHSKnownZero, RHSKnownOne, Depth+1))
1186       return I;
1187     DemandedMask.zext(BitWidth);
1188     RHSKnownZero.zext(BitWidth);
1189     RHSKnownOne.zext(BitWidth);
1190     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1191     // The top bits are known to be zero.
1192     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1193     break;
1194   }
1195   case Instruction::SExt: {
1196     // Compute the bits in the result that are not present in the input.
1197     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1198     
1199     APInt InputDemandedBits = DemandedMask & 
1200                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1201
1202     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1203     // If any of the sign extended bits are demanded, we know that the sign
1204     // bit is demanded.
1205     if ((NewBits & DemandedMask) != 0)
1206       InputDemandedBits.set(SrcBitWidth-1);
1207       
1208     InputDemandedBits.trunc(SrcBitWidth);
1209     RHSKnownZero.trunc(SrcBitWidth);
1210     RHSKnownOne.trunc(SrcBitWidth);
1211     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1212                              RHSKnownZero, RHSKnownOne, Depth+1))
1213       return I;
1214     InputDemandedBits.zext(BitWidth);
1215     RHSKnownZero.zext(BitWidth);
1216     RHSKnownOne.zext(BitWidth);
1217     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1218       
1219     // If the sign bit of the input is known set or clear, then we know the
1220     // top bits of the result.
1221
1222     // If the input sign bit is known zero, or if the NewBits are not demanded
1223     // convert this into a zero extension.
1224     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1225       // Convert to ZExt cast
1226       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1227       return InsertNewInstBefore(NewCast, *I);
1228     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1229       RHSKnownOne |= NewBits;
1230     }
1231     break;
1232   }
1233   case Instruction::Add: {
1234     // Figure out what the input bits are.  If the top bits of the and result
1235     // are not demanded, then the add doesn't demand them from its input
1236     // either.
1237     unsigned NLZ = DemandedMask.countLeadingZeros();
1238       
1239     // If there is a constant on the RHS, there are a variety of xformations
1240     // we can do.
1241     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1242       // If null, this should be simplified elsewhere.  Some of the xforms here
1243       // won't work if the RHS is zero.
1244       if (RHS->isZero())
1245         break;
1246       
1247       // If the top bit of the output is demanded, demand everything from the
1248       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1249       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1250
1251       // Find information about known zero/one bits in the input.
1252       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1253                                LHSKnownZero, LHSKnownOne, Depth+1))
1254         return I;
1255
1256       // If the RHS of the add has bits set that can't affect the input, reduce
1257       // the constant.
1258       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1259         return I;
1260       
1261       // Avoid excess work.
1262       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1263         break;
1264       
1265       // Turn it into OR if input bits are zero.
1266       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1267         Instruction *Or =
1268           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1269                                    I->getName());
1270         return InsertNewInstBefore(Or, *I);
1271       }
1272       
1273       // We can say something about the output known-zero and known-one bits,
1274       // depending on potential carries from the input constant and the
1275       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1276       // bits set and the RHS constant is 0x01001, then we know we have a known
1277       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1278       
1279       // To compute this, we first compute the potential carry bits.  These are
1280       // the bits which may be modified.  I'm not aware of a better way to do
1281       // this scan.
1282       const APInt &RHSVal = RHS->getValue();
1283       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1284       
1285       // Now that we know which bits have carries, compute the known-1/0 sets.
1286       
1287       // Bits are known one if they are known zero in one operand and one in the
1288       // other, and there is no input carry.
1289       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1290                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1291       
1292       // Bits are known zero if they are known zero in both operands and there
1293       // is no input carry.
1294       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1295     } else {
1296       // If the high-bits of this ADD are not demanded, then it does not demand
1297       // the high bits of its LHS or RHS.
1298       if (DemandedMask[BitWidth-1] == 0) {
1299         // Right fill the mask of bits for this ADD to demand the most
1300         // significant bit and all those below it.
1301         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1302         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1303                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1304             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1305                                  LHSKnownZero, LHSKnownOne, Depth+1))
1306           return I;
1307       }
1308     }
1309     break;
1310   }
1311   case Instruction::Sub:
1312     // If the high-bits of this SUB are not demanded, then it does not demand
1313     // the high bits of its LHS or RHS.
1314     if (DemandedMask[BitWidth-1] == 0) {
1315       // Right fill the mask of bits for this SUB to demand the most
1316       // significant bit and all those below it.
1317       uint32_t NLZ = DemandedMask.countLeadingZeros();
1318       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1319       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1320                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1321           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1322                                LHSKnownZero, LHSKnownOne, Depth+1))
1323         return I;
1324     }
1325     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1326     // the known zeros and ones.
1327     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1328     break;
1329   case Instruction::Shl:
1330     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1331       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1332       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1333       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1334                                RHSKnownZero, RHSKnownOne, Depth+1))
1335         return I;
1336       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1337       RHSKnownZero <<= ShiftAmt;
1338       RHSKnownOne  <<= ShiftAmt;
1339       // low bits known zero.
1340       if (ShiftAmt)
1341         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1342     }
1343     break;
1344   case Instruction::LShr:
1345     // For a logical shift right
1346     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1347       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1348       
1349       // Unsigned shift right.
1350       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1351       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1352                                RHSKnownZero, RHSKnownOne, Depth+1))
1353         return I;
1354       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1355       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1356       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1357       if (ShiftAmt) {
1358         // Compute the new bits that are at the top now.
1359         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1360         RHSKnownZero |= HighBits;  // high bits known zero.
1361       }
1362     }
1363     break;
1364   case Instruction::AShr:
1365     // If this is an arithmetic shift right and only the low-bit is set, we can
1366     // always convert this into a logical shr, even if the shift amount is
1367     // variable.  The low bit of the shift cannot be an input sign bit unless
1368     // the shift amount is >= the size of the datatype, which is undefined.
1369     if (DemandedMask == 1) {
1370       // Perform the logical shift right.
1371       Instruction *NewVal = BinaryOperator::CreateLShr(
1372                         I->getOperand(0), I->getOperand(1), I->getName());
1373       return InsertNewInstBefore(NewVal, *I);
1374     }    
1375
1376     // If the sign bit is the only bit demanded by this ashr, then there is no
1377     // need to do it, the shift doesn't change the high bit.
1378     if (DemandedMask.isSignBit())
1379       return I->getOperand(0);
1380     
1381     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1382       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1383       
1384       // Signed shift right.
1385       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1386       // If any of the "high bits" are demanded, we should set the sign bit as
1387       // demanded.
1388       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1389         DemandedMaskIn.set(BitWidth-1);
1390       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1391                                RHSKnownZero, RHSKnownOne, Depth+1))
1392         return I;
1393       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1394       // Compute the new bits that are at the top now.
1395       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1396       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1397       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1398         
1399       // Handle the sign bits.
1400       APInt SignBit(APInt::getSignBit(BitWidth));
1401       // Adjust to where it is now in the mask.
1402       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1403         
1404       // If the input sign bit is known to be zero, or if none of the top bits
1405       // are demanded, turn this into an unsigned shift right.
1406       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1407           (HighBits & ~DemandedMask) == HighBits) {
1408         // Perform the logical shift right.
1409         Instruction *NewVal = BinaryOperator::CreateLShr(
1410                           I->getOperand(0), SA, I->getName());
1411         return InsertNewInstBefore(NewVal, *I);
1412       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1413         RHSKnownOne |= HighBits;
1414       }
1415     }
1416     break;
1417   case Instruction::SRem:
1418     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1419       APInt RA = Rem->getValue().abs();
1420       if (RA.isPowerOf2()) {
1421         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1422           return I->getOperand(0);
1423
1424         APInt LowBits = RA - 1;
1425         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1426         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1427                                  LHSKnownZero, LHSKnownOne, Depth+1))
1428           return I;
1429
1430         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1431           LHSKnownZero |= ~LowBits;
1432
1433         KnownZero |= LHSKnownZero & DemandedMask;
1434
1435         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1436       }
1437     }
1438     break;
1439   case Instruction::URem: {
1440     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1441     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1442     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1443                              KnownZero2, KnownOne2, Depth+1) ||
1444         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1445                              KnownZero2, KnownOne2, Depth+1))
1446       return I;
1447
1448     unsigned Leaders = KnownZero2.countLeadingOnes();
1449     Leaders = std::max(Leaders,
1450                        KnownZero2.countLeadingOnes());
1451     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1452     break;
1453   }
1454   case Instruction::Call:
1455     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1456       switch (II->getIntrinsicID()) {
1457       default: break;
1458       case Intrinsic::bswap: {
1459         // If the only bits demanded come from one byte of the bswap result,
1460         // just shift the input byte into position to eliminate the bswap.
1461         unsigned NLZ = DemandedMask.countLeadingZeros();
1462         unsigned NTZ = DemandedMask.countTrailingZeros();
1463           
1464         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1465         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1466         // have 14 leading zeros, round to 8.
1467         NLZ &= ~7;
1468         NTZ &= ~7;
1469         // If we need exactly one byte, we can do this transformation.
1470         if (BitWidth-NLZ-NTZ == 8) {
1471           unsigned ResultBit = NTZ;
1472           unsigned InputBit = BitWidth-NTZ-8;
1473           
1474           // Replace this with either a left or right shift to get the byte into
1475           // the right place.
1476           Instruction *NewVal;
1477           if (InputBit > ResultBit)
1478             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1479                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1480           else
1481             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1482                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1483           NewVal->takeName(I);
1484           return InsertNewInstBefore(NewVal, *I);
1485         }
1486           
1487         // TODO: Could compute known zero/one bits based on the input.
1488         break;
1489       }
1490       }
1491     }
1492     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1493     break;
1494   }
1495   
1496   // If the client is only demanding bits that we know, return the known
1497   // constant.
1498   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1499     return Constant::getIntegerValue(VTy, RHSKnownOne);
1500   return false;
1501 }
1502
1503
1504 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1505 /// any number of elements. DemandedElts contains the set of elements that are
1506 /// actually used by the caller.  This method analyzes which elements of the
1507 /// operand are undef and returns that information in UndefElts.
1508 ///
1509 /// If the information about demanded elements can be used to simplify the
1510 /// operation, the operation is simplified, then the resultant value is
1511 /// returned.  This returns null if no change was made.
1512 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1513                                                 APInt& UndefElts,
1514                                                 unsigned Depth) {
1515   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1516   APInt EltMask(APInt::getAllOnesValue(VWidth));
1517   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1518
1519   if (isa<UndefValue>(V)) {
1520     // If the entire vector is undefined, just return this info.
1521     UndefElts = EltMask;
1522     return 0;
1523   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1524     UndefElts = EltMask;
1525     return UndefValue::get(V->getType());
1526   }
1527
1528   UndefElts = 0;
1529   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1530     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1531     Constant *Undef = UndefValue::get(EltTy);
1532
1533     std::vector<Constant*> Elts;
1534     for (unsigned i = 0; i != VWidth; ++i)
1535       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1536         Elts.push_back(Undef);
1537         UndefElts.set(i);
1538       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1539         Elts.push_back(Undef);
1540         UndefElts.set(i);
1541       } else {                               // Otherwise, defined.
1542         Elts.push_back(CP->getOperand(i));
1543       }
1544
1545     // If we changed the constant, return it.
1546     Constant *NewCP = ConstantVector::get(Elts);
1547     return NewCP != CP ? NewCP : 0;
1548   } else if (isa<ConstantAggregateZero>(V)) {
1549     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1550     // set to undef.
1551     
1552     // Check if this is identity. If so, return 0 since we are not simplifying
1553     // anything.
1554     if (DemandedElts == ((1ULL << VWidth) -1))
1555       return 0;
1556     
1557     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1558     Constant *Zero = Constant::getNullValue(EltTy);
1559     Constant *Undef = UndefValue::get(EltTy);
1560     std::vector<Constant*> Elts;
1561     for (unsigned i = 0; i != VWidth; ++i) {
1562       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1563       Elts.push_back(Elt);
1564     }
1565     UndefElts = DemandedElts ^ EltMask;
1566     return ConstantVector::get(Elts);
1567   }
1568   
1569   // Limit search depth.
1570   if (Depth == 10)
1571     return 0;
1572
1573   // If multiple users are using the root value, procede with
1574   // simplification conservatively assuming that all elements
1575   // are needed.
1576   if (!V->hasOneUse()) {
1577     // Quit if we find multiple users of a non-root value though.
1578     // They'll be handled when it's their turn to be visited by
1579     // the main instcombine process.
1580     if (Depth != 0)
1581       // TODO: Just compute the UndefElts information recursively.
1582       return 0;
1583
1584     // Conservatively assume that all elements are needed.
1585     DemandedElts = EltMask;
1586   }
1587   
1588   Instruction *I = dyn_cast<Instruction>(V);
1589   if (!I) return 0;        // Only analyze instructions.
1590   
1591   bool MadeChange = false;
1592   APInt UndefElts2(VWidth, 0);
1593   Value *TmpV;
1594   switch (I->getOpcode()) {
1595   default: break;
1596     
1597   case Instruction::InsertElement: {
1598     // If this is a variable index, we don't know which element it overwrites.
1599     // demand exactly the same input as we produce.
1600     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1601     if (Idx == 0) {
1602       // Note that we can't propagate undef elt info, because we don't know
1603       // which elt is getting updated.
1604       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1605                                         UndefElts2, Depth+1);
1606       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1607       break;
1608     }
1609     
1610     // If this is inserting an element that isn't demanded, remove this
1611     // insertelement.
1612     unsigned IdxNo = Idx->getZExtValue();
1613     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1614       Worklist.Add(I);
1615       return I->getOperand(0);
1616     }
1617     
1618     // Otherwise, the element inserted overwrites whatever was there, so the
1619     // input demanded set is simpler than the output set.
1620     APInt DemandedElts2 = DemandedElts;
1621     DemandedElts2.clear(IdxNo);
1622     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1623                                       UndefElts, Depth+1);
1624     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1625
1626     // The inserted element is defined.
1627     UndefElts.clear(IdxNo);
1628     break;
1629   }
1630   case Instruction::ShuffleVector: {
1631     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1632     uint64_t LHSVWidth =
1633       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1634     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1635     for (unsigned i = 0; i < VWidth; i++) {
1636       if (DemandedElts[i]) {
1637         unsigned MaskVal = Shuffle->getMaskValue(i);
1638         if (MaskVal != -1u) {
1639           assert(MaskVal < LHSVWidth * 2 &&
1640                  "shufflevector mask index out of range!");
1641           if (MaskVal < LHSVWidth)
1642             LeftDemanded.set(MaskVal);
1643           else
1644             RightDemanded.set(MaskVal - LHSVWidth);
1645         }
1646       }
1647     }
1648
1649     APInt UndefElts4(LHSVWidth, 0);
1650     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1651                                       UndefElts4, Depth+1);
1652     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1653
1654     APInt UndefElts3(LHSVWidth, 0);
1655     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1656                                       UndefElts3, Depth+1);
1657     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1658
1659     bool NewUndefElts = false;
1660     for (unsigned i = 0; i < VWidth; i++) {
1661       unsigned MaskVal = Shuffle->getMaskValue(i);
1662       if (MaskVal == -1u) {
1663         UndefElts.set(i);
1664       } else if (MaskVal < LHSVWidth) {
1665         if (UndefElts4[MaskVal]) {
1666           NewUndefElts = true;
1667           UndefElts.set(i);
1668         }
1669       } else {
1670         if (UndefElts3[MaskVal - LHSVWidth]) {
1671           NewUndefElts = true;
1672           UndefElts.set(i);
1673         }
1674       }
1675     }
1676
1677     if (NewUndefElts) {
1678       // Add additional discovered undefs.
1679       std::vector<Constant*> Elts;
1680       for (unsigned i = 0; i < VWidth; ++i) {
1681         if (UndefElts[i])
1682           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1683         else
1684           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1685                                           Shuffle->getMaskValue(i)));
1686       }
1687       I->setOperand(2, ConstantVector::get(Elts));
1688       MadeChange = true;
1689     }
1690     break;
1691   }
1692   case Instruction::BitCast: {
1693     // Vector->vector casts only.
1694     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1695     if (!VTy) break;
1696     unsigned InVWidth = VTy->getNumElements();
1697     APInt InputDemandedElts(InVWidth, 0);
1698     unsigned Ratio;
1699
1700     if (VWidth == InVWidth) {
1701       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1702       // elements as are demanded of us.
1703       Ratio = 1;
1704       InputDemandedElts = DemandedElts;
1705     } else if (VWidth > InVWidth) {
1706       // Untested so far.
1707       break;
1708       
1709       // If there are more elements in the result than there are in the source,
1710       // then an input element is live if any of the corresponding output
1711       // elements are live.
1712       Ratio = VWidth/InVWidth;
1713       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1714         if (DemandedElts[OutIdx])
1715           InputDemandedElts.set(OutIdx/Ratio);
1716       }
1717     } else {
1718       // Untested so far.
1719       break;
1720       
1721       // If there are more elements in the source than there are in the result,
1722       // then an input element is live if the corresponding output element is
1723       // live.
1724       Ratio = InVWidth/VWidth;
1725       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1726         if (DemandedElts[InIdx/Ratio])
1727           InputDemandedElts.set(InIdx);
1728     }
1729     
1730     // div/rem demand all inputs, because they don't want divide by zero.
1731     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1732                                       UndefElts2, Depth+1);
1733     if (TmpV) {
1734       I->setOperand(0, TmpV);
1735       MadeChange = true;
1736     }
1737     
1738     UndefElts = UndefElts2;
1739     if (VWidth > InVWidth) {
1740       llvm_unreachable("Unimp");
1741       // If there are more elements in the result than there are in the source,
1742       // then an output element is undef if the corresponding input element is
1743       // undef.
1744       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1745         if (UndefElts2[OutIdx/Ratio])
1746           UndefElts.set(OutIdx);
1747     } else if (VWidth < InVWidth) {
1748       llvm_unreachable("Unimp");
1749       // If there are more elements in the source than there are in the result,
1750       // then a result element is undef if all of the corresponding input
1751       // elements are undef.
1752       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1753       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1754         if (!UndefElts2[InIdx])            // Not undef?
1755           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1756     }
1757     break;
1758   }
1759   case Instruction::And:
1760   case Instruction::Or:
1761   case Instruction::Xor:
1762   case Instruction::Add:
1763   case Instruction::Sub:
1764   case Instruction::Mul:
1765     // div/rem demand all inputs, because they don't want divide by zero.
1766     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1767                                       UndefElts, Depth+1);
1768     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1769     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1770                                       UndefElts2, Depth+1);
1771     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1772       
1773     // Output elements are undefined if both are undefined.  Consider things
1774     // like undef&0.  The result is known zero, not undef.
1775     UndefElts &= UndefElts2;
1776     break;
1777     
1778   case Instruction::Call: {
1779     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1780     if (!II) break;
1781     switch (II->getIntrinsicID()) {
1782     default: break;
1783       
1784     // Binary vector operations that work column-wise.  A dest element is a
1785     // function of the corresponding input elements from the two inputs.
1786     case Intrinsic::x86_sse_sub_ss:
1787     case Intrinsic::x86_sse_mul_ss:
1788     case Intrinsic::x86_sse_min_ss:
1789     case Intrinsic::x86_sse_max_ss:
1790     case Intrinsic::x86_sse2_sub_sd:
1791     case Intrinsic::x86_sse2_mul_sd:
1792     case Intrinsic::x86_sse2_min_sd:
1793     case Intrinsic::x86_sse2_max_sd:
1794       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1795                                         UndefElts, Depth+1);
1796       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1797       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1798                                         UndefElts2, Depth+1);
1799       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1800
1801       // If only the low elt is demanded and this is a scalarizable intrinsic,
1802       // scalarize it now.
1803       if (DemandedElts == 1) {
1804         switch (II->getIntrinsicID()) {
1805         default: break;
1806         case Intrinsic::x86_sse_sub_ss:
1807         case Intrinsic::x86_sse_mul_ss:
1808         case Intrinsic::x86_sse2_sub_sd:
1809         case Intrinsic::x86_sse2_mul_sd:
1810           // TODO: Lower MIN/MAX/ABS/etc
1811           Value *LHS = II->getOperand(1);
1812           Value *RHS = II->getOperand(2);
1813           // Extract the element as scalars.
1814           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1815             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1816           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1817             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1818           
1819           switch (II->getIntrinsicID()) {
1820           default: llvm_unreachable("Case stmts out of sync!");
1821           case Intrinsic::x86_sse_sub_ss:
1822           case Intrinsic::x86_sse2_sub_sd:
1823             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1824                                                         II->getName()), *II);
1825             break;
1826           case Intrinsic::x86_sse_mul_ss:
1827           case Intrinsic::x86_sse2_mul_sd:
1828             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1829                                                          II->getName()), *II);
1830             break;
1831           }
1832           
1833           Instruction *New =
1834             InsertElementInst::Create(
1835               UndefValue::get(II->getType()), TmpV,
1836               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1837           InsertNewInstBefore(New, *II);
1838           return New;
1839         }            
1840       }
1841         
1842       // Output elements are undefined if both are undefined.  Consider things
1843       // like undef&0.  The result is known zero, not undef.
1844       UndefElts &= UndefElts2;
1845       break;
1846     }
1847     break;
1848   }
1849   }
1850   return MadeChange ? I : 0;
1851 }
1852
1853
1854 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1855 /// function is designed to check a chain of associative operators for a
1856 /// potential to apply a certain optimization.  Since the optimization may be
1857 /// applicable if the expression was reassociated, this checks the chain, then
1858 /// reassociates the expression as necessary to expose the optimization
1859 /// opportunity.  This makes use of a special Functor, which must define
1860 /// 'shouldApply' and 'apply' methods.
1861 ///
1862 template<typename Functor>
1863 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1864   unsigned Opcode = Root.getOpcode();
1865   Value *LHS = Root.getOperand(0);
1866
1867   // Quick check, see if the immediate LHS matches...
1868   if (F.shouldApply(LHS))
1869     return F.apply(Root);
1870
1871   // Otherwise, if the LHS is not of the same opcode as the root, return.
1872   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1873   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1874     // Should we apply this transform to the RHS?
1875     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1876
1877     // If not to the RHS, check to see if we should apply to the LHS...
1878     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1879       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1880       ShouldApply = true;
1881     }
1882
1883     // If the functor wants to apply the optimization to the RHS of LHSI,
1884     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1885     if (ShouldApply) {
1886       // Now all of the instructions are in the current basic block, go ahead
1887       // and perform the reassociation.
1888       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1889
1890       // First move the selected RHS to the LHS of the root...
1891       Root.setOperand(0, LHSI->getOperand(1));
1892
1893       // Make what used to be the LHS of the root be the user of the root...
1894       Value *ExtraOperand = TmpLHSI->getOperand(1);
1895       if (&Root == TmpLHSI) {
1896         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1897         return 0;
1898       }
1899       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1900       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1901       BasicBlock::iterator ARI = &Root; ++ARI;
1902       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1903       ARI = Root;
1904
1905       // Now propagate the ExtraOperand down the chain of instructions until we
1906       // get to LHSI.
1907       while (TmpLHSI != LHSI) {
1908         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1909         // Move the instruction to immediately before the chain we are
1910         // constructing to avoid breaking dominance properties.
1911         NextLHSI->moveBefore(ARI);
1912         ARI = NextLHSI;
1913
1914         Value *NextOp = NextLHSI->getOperand(1);
1915         NextLHSI->setOperand(1, ExtraOperand);
1916         TmpLHSI = NextLHSI;
1917         ExtraOperand = NextOp;
1918       }
1919
1920       // Now that the instructions are reassociated, have the functor perform
1921       // the transformation...
1922       return F.apply(Root);
1923     }
1924
1925     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1926   }
1927   return 0;
1928 }
1929
1930 namespace {
1931
1932 // AddRHS - Implements: X + X --> X << 1
1933 struct AddRHS {
1934   Value *RHS;
1935   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1936   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1937   Instruction *apply(BinaryOperator &Add) const {
1938     return BinaryOperator::CreateShl(Add.getOperand(0),
1939                                      ConstantInt::get(Add.getType(), 1));
1940   }
1941 };
1942
1943 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1944 //                 iff C1&C2 == 0
1945 struct AddMaskingAnd {
1946   Constant *C2;
1947   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1948   bool shouldApply(Value *LHS) const {
1949     ConstantInt *C1;
1950     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1951            ConstantExpr::getAnd(C1, C2)->isNullValue();
1952   }
1953   Instruction *apply(BinaryOperator &Add) const {
1954     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1955   }
1956 };
1957
1958 }
1959
1960 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1961                                              InstCombiner *IC) {
1962   if (CastInst *CI = dyn_cast<CastInst>(&I))
1963     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1964
1965   // Figure out if the constant is the left or the right argument.
1966   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1967   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1968
1969   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1970     if (ConstIsRHS)
1971       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1972     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1973   }
1974
1975   Value *Op0 = SO, *Op1 = ConstOperand;
1976   if (!ConstIsRHS)
1977     std::swap(Op0, Op1);
1978   
1979   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1980     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1981                                     SO->getName()+".op");
1982   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1983     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1984                                    SO->getName()+".cmp");
1985   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1986     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1987                                    SO->getName()+".cmp");
1988   llvm_unreachable("Unknown binary instruction type!");
1989 }
1990
1991 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1992 // constant as the other operand, try to fold the binary operator into the
1993 // select arguments.  This also works for Cast instructions, which obviously do
1994 // not have a second operand.
1995 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1996                                      InstCombiner *IC) {
1997   // Don't modify shared select instructions
1998   if (!SI->hasOneUse()) return 0;
1999   Value *TV = SI->getOperand(1);
2000   Value *FV = SI->getOperand(2);
2001
2002   if (isa<Constant>(TV) || isa<Constant>(FV)) {
2003     // Bool selects with constant operands can be folded to logical ops.
2004     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
2005
2006     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2007     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2008
2009     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2010                               SelectFalseVal);
2011   }
2012   return 0;
2013 }
2014
2015
2016 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2017 /// has a PHI node as operand #0, see if we can fold the instruction into the
2018 /// PHI (which is only possible if all operands to the PHI are constants).
2019 ///
2020 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2021 /// that would normally be unprofitable because they strongly encourage jump
2022 /// threading.
2023 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2024                                          bool AllowAggressive) {
2025   AllowAggressive = false;
2026   PHINode *PN = cast<PHINode>(I.getOperand(0));
2027   unsigned NumPHIValues = PN->getNumIncomingValues();
2028   if (NumPHIValues == 0 ||
2029       // We normally only transform phis with a single use, unless we're trying
2030       // hard to make jump threading happen.
2031       (!PN->hasOneUse() && !AllowAggressive))
2032     return 0;
2033   
2034   
2035   // Check to see if all of the operands of the PHI are simple constants
2036   // (constantint/constantfp/undef).  If there is one non-constant value,
2037   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
2038   // bail out.  We don't do arbitrary constant expressions here because moving
2039   // their computation can be expensive without a cost model.
2040   BasicBlock *NonConstBB = 0;
2041   for (unsigned i = 0; i != NumPHIValues; ++i)
2042     if (!isa<Constant>(PN->getIncomingValue(i)) ||
2043         isa<ConstantExpr>(PN->getIncomingValue(i))) {
2044       if (NonConstBB) return 0;  // More than one non-const value.
2045       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2046       NonConstBB = PN->getIncomingBlock(i);
2047       
2048       // If the incoming non-constant value is in I's block, we have an infinite
2049       // loop.
2050       if (NonConstBB == I.getParent())
2051         return 0;
2052     }
2053   
2054   // If there is exactly one non-constant value, we can insert a copy of the
2055   // operation in that block.  However, if this is a critical edge, we would be
2056   // inserting the computation one some other paths (e.g. inside a loop).  Only
2057   // do this if the pred block is unconditionally branching into the phi block.
2058   if (NonConstBB != 0 && !AllowAggressive) {
2059     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2060     if (!BI || !BI->isUnconditional()) return 0;
2061   }
2062
2063   // Okay, we can do the transformation: create the new PHI node.
2064   PHINode *NewPN = PHINode::Create(I.getType(), "");
2065   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2066   InsertNewInstBefore(NewPN, *PN);
2067   NewPN->takeName(PN);
2068
2069   // Next, add all of the operands to the PHI.
2070   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2071     // We only currently try to fold the condition of a select when it is a phi,
2072     // not the true/false values.
2073     Value *TrueV = SI->getTrueValue();
2074     Value *FalseV = SI->getFalseValue();
2075     BasicBlock *PhiTransBB = PN->getParent();
2076     for (unsigned i = 0; i != NumPHIValues; ++i) {
2077       BasicBlock *ThisBB = PN->getIncomingBlock(i);
2078       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2079       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
2080       Value *InV = 0;
2081       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2082         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2083       } else {
2084         assert(PN->getIncomingBlock(i) == NonConstBB);
2085         InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2086                                  FalseVInPred,
2087                                  "phitmp", NonConstBB->getTerminator());
2088         Worklist.Add(cast<Instruction>(InV));
2089       }
2090       NewPN->addIncoming(InV, ThisBB);
2091     }
2092   } else if (I.getNumOperands() == 2) {
2093     Constant *C = cast<Constant>(I.getOperand(1));
2094     for (unsigned i = 0; i != NumPHIValues; ++i) {
2095       Value *InV = 0;
2096       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2097         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2098           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2099         else
2100           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2101       } else {
2102         assert(PN->getIncomingBlock(i) == NonConstBB);
2103         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2104           InV = BinaryOperator::Create(BO->getOpcode(),
2105                                        PN->getIncomingValue(i), C, "phitmp",
2106                                        NonConstBB->getTerminator());
2107         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2108           InV = CmpInst::Create(CI->getOpcode(),
2109                                 CI->getPredicate(),
2110                                 PN->getIncomingValue(i), C, "phitmp",
2111                                 NonConstBB->getTerminator());
2112         else
2113           llvm_unreachable("Unknown binop!");
2114         
2115         Worklist.Add(cast<Instruction>(InV));
2116       }
2117       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2118     }
2119   } else { 
2120     CastInst *CI = cast<CastInst>(&I);
2121     const Type *RetTy = CI->getType();
2122     for (unsigned i = 0; i != NumPHIValues; ++i) {
2123       Value *InV;
2124       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2125         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2126       } else {
2127         assert(PN->getIncomingBlock(i) == NonConstBB);
2128         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2129                                I.getType(), "phitmp", 
2130                                NonConstBB->getTerminator());
2131         Worklist.Add(cast<Instruction>(InV));
2132       }
2133       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2134     }
2135   }
2136   return ReplaceInstUsesWith(I, NewPN);
2137 }
2138
2139
2140 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2141 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2142 /// This basically requires proving that the add in the original type would not
2143 /// overflow to change the sign bit or have a carry out.
2144 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2145   // There are different heuristics we can use for this.  Here are some simple
2146   // ones.
2147   
2148   // Add has the property that adding any two 2's complement numbers can only 
2149   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2150   // have at least two sign bits, we know that the addition of the two values will
2151   // sign extend fine.
2152   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2153     return true;
2154   
2155   
2156   // If one of the operands only has one non-zero bit, and if the other operand
2157   // has a known-zero bit in a more significant place than it (not including the
2158   // sign bit) the ripple may go up to and fill the zero, but won't change the
2159   // sign.  For example, (X & ~4) + 1.
2160   
2161   // TODO: Implement.
2162   
2163   return false;
2164 }
2165
2166
2167 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2168   bool Changed = SimplifyCommutative(I);
2169   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2170
2171   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2172     // X + undef -> undef
2173     if (isa<UndefValue>(RHS))
2174       return ReplaceInstUsesWith(I, RHS);
2175
2176     // X + 0 --> X
2177     if (RHSC->isNullValue())
2178       return ReplaceInstUsesWith(I, LHS);
2179
2180     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2181       // X + (signbit) --> X ^ signbit
2182       const APInt& Val = CI->getValue();
2183       uint32_t BitWidth = Val.getBitWidth();
2184       if (Val == APInt::getSignBit(BitWidth))
2185         return BinaryOperator::CreateXor(LHS, RHS);
2186       
2187       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2188       // (X & 254)+1 -> (X&254)|1
2189       if (SimplifyDemandedInstructionBits(I))
2190         return &I;
2191
2192       // zext(bool) + C -> bool ? C + 1 : C
2193       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2194         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2195           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2196     }
2197
2198     if (isa<PHINode>(LHS))
2199       if (Instruction *NV = FoldOpIntoPhi(I))
2200         return NV;
2201     
2202     ConstantInt *XorRHS = 0;
2203     Value *XorLHS = 0;
2204     if (isa<ConstantInt>(RHSC) &&
2205         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2206       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2207       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2208       
2209       uint32_t Size = TySizeBits / 2;
2210       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2211       APInt CFF80Val(-C0080Val);
2212       do {
2213         if (TySizeBits > Size) {
2214           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2215           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2216           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2217               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2218             // This is a sign extend if the top bits are known zero.
2219             if (!MaskedValueIsZero(XorLHS, 
2220                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2221               Size = 0;  // Not a sign ext, but can't be any others either.
2222             break;
2223           }
2224         }
2225         Size >>= 1;
2226         C0080Val = APIntOps::lshr(C0080Val, Size);
2227         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2228       } while (Size >= 1);
2229       
2230       // FIXME: This shouldn't be necessary. When the backends can handle types
2231       // with funny bit widths then this switch statement should be removed. It
2232       // is just here to get the size of the "middle" type back up to something
2233       // that the back ends can handle.
2234       const Type *MiddleType = 0;
2235       switch (Size) {
2236         default: break;
2237         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2238         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2239         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2240       }
2241       if (MiddleType) {
2242         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2243         return new SExtInst(NewTrunc, I.getType(), I.getName());
2244       }
2245     }
2246   }
2247
2248   if (I.getType() == Type::getInt1Ty(*Context))
2249     return BinaryOperator::CreateXor(LHS, RHS);
2250
2251   // X + X --> X << 1
2252   if (I.getType()->isInteger()) {
2253     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2254       return Result;
2255
2256     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2257       if (RHSI->getOpcode() == Instruction::Sub)
2258         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2259           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2260     }
2261     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2262       if (LHSI->getOpcode() == Instruction::Sub)
2263         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2264           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2265     }
2266   }
2267
2268   // -A + B  -->  B - A
2269   // -A + -B  -->  -(A + B)
2270   if (Value *LHSV = dyn_castNegVal(LHS)) {
2271     if (LHS->getType()->isIntOrIntVector()) {
2272       if (Value *RHSV = dyn_castNegVal(RHS)) {
2273         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2274         return BinaryOperator::CreateNeg(NewAdd);
2275       }
2276     }
2277     
2278     return BinaryOperator::CreateSub(RHS, LHSV);
2279   }
2280
2281   // A + -B  -->  A - B
2282   if (!isa<Constant>(RHS))
2283     if (Value *V = dyn_castNegVal(RHS))
2284       return BinaryOperator::CreateSub(LHS, V);
2285
2286
2287   ConstantInt *C2;
2288   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2289     if (X == RHS)   // X*C + X --> X * (C+1)
2290       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2291
2292     // X*C1 + X*C2 --> X * (C1+C2)
2293     ConstantInt *C1;
2294     if (X == dyn_castFoldableMul(RHS, C1))
2295       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2296   }
2297
2298   // X + X*C --> X * (C+1)
2299   if (dyn_castFoldableMul(RHS, C2) == LHS)
2300     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2301
2302   // X + ~X --> -1   since   ~X = -X-1
2303   if (dyn_castNotVal(LHS) == RHS ||
2304       dyn_castNotVal(RHS) == LHS)
2305     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2306   
2307
2308   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2309   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2310     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2311       return R;
2312   
2313   // A+B --> A|B iff A and B have no bits set in common.
2314   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2315     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2316     APInt LHSKnownOne(IT->getBitWidth(), 0);
2317     APInt LHSKnownZero(IT->getBitWidth(), 0);
2318     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2319     if (LHSKnownZero != 0) {
2320       APInt RHSKnownOne(IT->getBitWidth(), 0);
2321       APInt RHSKnownZero(IT->getBitWidth(), 0);
2322       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2323       
2324       // No bits in common -> bitwise or.
2325       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2326         return BinaryOperator::CreateOr(LHS, RHS);
2327     }
2328   }
2329
2330   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2331   if (I.getType()->isIntOrIntVector()) {
2332     Value *W, *X, *Y, *Z;
2333     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2334         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2335       if (W != Y) {
2336         if (W == Z) {
2337           std::swap(Y, Z);
2338         } else if (Y == X) {
2339           std::swap(W, X);
2340         } else if (X == Z) {
2341           std::swap(Y, Z);
2342           std::swap(W, X);
2343         }
2344       }
2345
2346       if (W == Y) {
2347         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2348         return BinaryOperator::CreateMul(W, NewAdd);
2349       }
2350     }
2351   }
2352
2353   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2354     Value *X = 0;
2355     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2356       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2357
2358     // (X & FF00) + xx00  -> (X+xx00) & FF00
2359     if (LHS->hasOneUse() &&
2360         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2361       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2362       if (Anded == CRHS) {
2363         // See if all bits from the first bit set in the Add RHS up are included
2364         // in the mask.  First, get the rightmost bit.
2365         const APInt& AddRHSV = CRHS->getValue();
2366
2367         // Form a mask of all bits from the lowest bit added through the top.
2368         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2369
2370         // See if the and mask includes all of these bits.
2371         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2372
2373         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2374           // Okay, the xform is safe.  Insert the new add pronto.
2375           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2376           return BinaryOperator::CreateAnd(NewAdd, C2);
2377         }
2378       }
2379     }
2380
2381     // Try to fold constant add into select arguments.
2382     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2383       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2384         return R;
2385   }
2386
2387   // add (select X 0 (sub n A)) A  -->  select X A n
2388   {
2389     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2390     Value *A = RHS;
2391     if (!SI) {
2392       SI = dyn_cast<SelectInst>(RHS);
2393       A = LHS;
2394     }
2395     if (SI && SI->hasOneUse()) {
2396       Value *TV = SI->getTrueValue();
2397       Value *FV = SI->getFalseValue();
2398       Value *N;
2399
2400       // Can we fold the add into the argument of the select?
2401       // We check both true and false select arguments for a matching subtract.
2402       if (match(FV, m_Zero()) &&
2403           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2404         // Fold the add into the true select value.
2405         return SelectInst::Create(SI->getCondition(), N, A);
2406       if (match(TV, m_Zero()) &&
2407           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2408         // Fold the add into the false select value.
2409         return SelectInst::Create(SI->getCondition(), A, N);
2410     }
2411   }
2412
2413   // Check for (add (sext x), y), see if we can merge this into an
2414   // integer add followed by a sext.
2415   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2416     // (add (sext x), cst) --> (sext (add x, cst'))
2417     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2418       Constant *CI = 
2419         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2420       if (LHSConv->hasOneUse() &&
2421           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2422           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2423         // Insert the new, smaller add.
2424         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2425                                               CI, "addconv");
2426         return new SExtInst(NewAdd, I.getType());
2427       }
2428     }
2429     
2430     // (add (sext x), (sext y)) --> (sext (add int x, y))
2431     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2432       // Only do this if x/y have the same type, if at last one of them has a
2433       // single use (so we don't increase the number of sexts), and if the
2434       // integer add will not overflow.
2435       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2436           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2437           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2438                                    RHSConv->getOperand(0))) {
2439         // Insert the new integer add.
2440         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2441                                               RHSConv->getOperand(0), "addconv");
2442         return new SExtInst(NewAdd, I.getType());
2443       }
2444     }
2445   }
2446
2447   return Changed ? &I : 0;
2448 }
2449
2450 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2451   bool Changed = SimplifyCommutative(I);
2452   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2453
2454   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2455     // X + 0 --> X
2456     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2457       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2458                               (I.getType())->getValueAPF()))
2459         return ReplaceInstUsesWith(I, LHS);
2460     }
2461
2462     if (isa<PHINode>(LHS))
2463       if (Instruction *NV = FoldOpIntoPhi(I))
2464         return NV;
2465   }
2466
2467   // -A + B  -->  B - A
2468   // -A + -B  -->  -(A + B)
2469   if (Value *LHSV = dyn_castFNegVal(LHS))
2470     return BinaryOperator::CreateFSub(RHS, LHSV);
2471
2472   // A + -B  -->  A - B
2473   if (!isa<Constant>(RHS))
2474     if (Value *V = dyn_castFNegVal(RHS))
2475       return BinaryOperator::CreateFSub(LHS, V);
2476
2477   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2478   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2479     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2480       return ReplaceInstUsesWith(I, LHS);
2481
2482   // Check for (add double (sitofp x), y), see if we can merge this into an
2483   // integer add followed by a promotion.
2484   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2485     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2486     // ... if the constant fits in the integer value.  This is useful for things
2487     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2488     // requires a constant pool load, and generally allows the add to be better
2489     // instcombined.
2490     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2491       Constant *CI = 
2492       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2493       if (LHSConv->hasOneUse() &&
2494           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2495           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2496         // Insert the new integer add.
2497         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2498                                               CI, "addconv");
2499         return new SIToFPInst(NewAdd, I.getType());
2500       }
2501     }
2502     
2503     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2504     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2505       // Only do this if x/y have the same type, if at last one of them has a
2506       // single use (so we don't increase the number of int->fp conversions),
2507       // and if the integer add will not overflow.
2508       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2509           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2510           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2511                                    RHSConv->getOperand(0))) {
2512         // Insert the new integer add.
2513         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2514                                               RHSConv->getOperand(0),"addconv");
2515         return new SIToFPInst(NewAdd, I.getType());
2516       }
2517     }
2518   }
2519   
2520   return Changed ? &I : 0;
2521 }
2522
2523
2524 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2525 /// code necessary to compute the offset from the base pointer (without adding
2526 /// in the base pointer).  Return the result as a signed integer of intptr size.
2527 static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2528   TargetData &TD = *IC.getTargetData();
2529   gep_type_iterator GTI = gep_type_begin(GEP);
2530   const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2531   Value *Result = Constant::getNullValue(IntPtrTy);
2532
2533   // Build a mask for high order bits.
2534   unsigned IntPtrWidth = TD.getPointerSizeInBits();
2535   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2536
2537   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2538        ++i, ++GTI) {
2539     Value *Op = *i;
2540     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2541     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2542       if (OpC->isZero()) continue;
2543       
2544       // Handle a struct index, which adds its field offset to the pointer.
2545       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2546         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2547         
2548         Result = IC.Builder->CreateAdd(Result,
2549                                        ConstantInt::get(IntPtrTy, Size),
2550                                        GEP->getName()+".offs");
2551         continue;
2552       }
2553       
2554       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2555       Constant *OC =
2556               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2557       Scale = ConstantExpr::getMul(OC, Scale);
2558       // Emit an add instruction.
2559       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2560       continue;
2561     }
2562     // Convert to correct type.
2563     if (Op->getType() != IntPtrTy)
2564       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2565     if (Size != 1) {
2566       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2567       // We'll let instcombine(mul) convert this to a shl if possible.
2568       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2569     }
2570
2571     // Emit an add instruction.
2572     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2573   }
2574   return Result;
2575 }
2576
2577
2578 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2579 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
2580 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
2581 /// be complex, and scales are involved.  The above expression would also be
2582 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2583 /// This later form is less amenable to optimization though, and we are allowed
2584 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
2585 ///
2586 /// If we can't emit an optimized form for this expression, this returns null.
2587 /// 
2588 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2589                                           InstCombiner &IC) {
2590   TargetData &TD = *IC.getTargetData();
2591   gep_type_iterator GTI = gep_type_begin(GEP);
2592
2593   // Check to see if this gep only has a single variable index.  If so, and if
2594   // any constant indices are a multiple of its scale, then we can compute this
2595   // in terms of the scale of the variable index.  For example, if the GEP
2596   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2597   // because the expression will cross zero at the same point.
2598   unsigned i, e = GEP->getNumOperands();
2599   int64_t Offset = 0;
2600   for (i = 1; i != e; ++i, ++GTI) {
2601     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2602       // Compute the aggregate offset of constant indices.
2603       if (CI->isZero()) continue;
2604
2605       // Handle a struct index, which adds its field offset to the pointer.
2606       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2607         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2608       } else {
2609         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2610         Offset += Size*CI->getSExtValue();
2611       }
2612     } else {
2613       // Found our variable index.
2614       break;
2615     }
2616   }
2617   
2618   // If there are no variable indices, we must have a constant offset, just
2619   // evaluate it the general way.
2620   if (i == e) return 0;
2621   
2622   Value *VariableIdx = GEP->getOperand(i);
2623   // Determine the scale factor of the variable element.  For example, this is
2624   // 4 if the variable index is into an array of i32.
2625   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2626   
2627   // Verify that there are no other variable indices.  If so, emit the hard way.
2628   for (++i, ++GTI; i != e; ++i, ++GTI) {
2629     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2630     if (!CI) return 0;
2631    
2632     // Compute the aggregate offset of constant indices.
2633     if (CI->isZero()) continue;
2634     
2635     // Handle a struct index, which adds its field offset to the pointer.
2636     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2637       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2638     } else {
2639       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2640       Offset += Size*CI->getSExtValue();
2641     }
2642   }
2643   
2644   // Okay, we know we have a single variable index, which must be a
2645   // pointer/array/vector index.  If there is no offset, life is simple, return
2646   // the index.
2647   unsigned IntPtrWidth = TD.getPointerSizeInBits();
2648   if (Offset == 0) {
2649     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
2650     // we don't need to bother extending: the extension won't affect where the
2651     // computation crosses zero.
2652     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2653       VariableIdx = new TruncInst(VariableIdx, 
2654                                   TD.getIntPtrType(VariableIdx->getContext()),
2655                                   VariableIdx->getName(), &I);
2656     return VariableIdx;
2657   }
2658   
2659   // Otherwise, there is an index.  The computation we will do will be modulo
2660   // the pointer size, so get it.
2661   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2662   
2663   Offset &= PtrSizeMask;
2664   VariableScale &= PtrSizeMask;
2665
2666   // To do this transformation, any constant index must be a multiple of the
2667   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
2668   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
2669   // multiple of the variable scale.
2670   int64_t NewOffs = Offset / (int64_t)VariableScale;
2671   if (Offset != NewOffs*(int64_t)VariableScale)
2672     return 0;
2673
2674   // Okay, we can do this evaluation.  Start by converting the index to intptr.
2675   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2676   if (VariableIdx->getType() != IntPtrTy)
2677     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2678                                               true /*SExt*/, 
2679                                               VariableIdx->getName(), &I);
2680   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2681   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2682 }
2683
2684
2685 /// Optimize pointer differences into the same array into a size.  Consider:
2686 ///  &A[10] - &A[0]: we should compile this to "10".  LHS/RHS are the pointer
2687 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2688 ///
2689 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2690                                                const Type *Ty) {
2691   assert(TD && "Must have target data info for this");
2692   
2693   // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2694   // this.
2695   bool Swapped;
2696   GetElementPtrInst *GEP;
2697   
2698   if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2699       GEP->getOperand(0) == RHS)
2700     Swapped = false;
2701   else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2702            GEP->getOperand(0) == LHS)
2703     Swapped = true;
2704   else
2705     return 0;
2706   
2707   // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2708   
2709   // Emit the offset of the GEP and an intptr_t.
2710   Value *Result = EmitGEPOffset(GEP, *this);
2711
2712   // If we have p - gep(p, ...)  then we have to negate the result.
2713   if (Swapped)
2714     Result = Builder->CreateNeg(Result, "diff.neg");
2715
2716   return Builder->CreateIntCast(Result, Ty, true);
2717 }
2718
2719
2720 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2721   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2722
2723   if (Op0 == Op1)                        // sub X, X  -> 0
2724     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2725
2726   // If this is a 'B = x-(-A)', change to B = x+A.
2727   if (Value *V = dyn_castNegVal(Op1))
2728     return BinaryOperator::CreateAdd(Op0, V);
2729
2730   if (isa<UndefValue>(Op0))
2731     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2732   if (isa<UndefValue>(Op1))
2733     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2734   if (I.getType() == Type::getInt1Ty(*Context))
2735     return BinaryOperator::CreateXor(Op0, Op1);
2736   
2737   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2738     // Replace (-1 - A) with (~A).
2739     if (C->isAllOnesValue())
2740       return BinaryOperator::CreateNot(Op1);
2741
2742     // C - ~X == X + (1+C)
2743     Value *X = 0;
2744     if (match(Op1, m_Not(m_Value(X))))
2745       return BinaryOperator::CreateAdd(X, AddOne(C));
2746
2747     // -(X >>u 31) -> (X >>s 31)
2748     // -(X >>s 31) -> (X >>u 31)
2749     if (C->isZero()) {
2750       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2751         if (SI->getOpcode() == Instruction::LShr) {
2752           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2753             // Check to see if we are shifting out everything but the sign bit.
2754             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2755                 SI->getType()->getPrimitiveSizeInBits()-1) {
2756               // Ok, the transformation is safe.  Insert AShr.
2757               return BinaryOperator::Create(Instruction::AShr, 
2758                                           SI->getOperand(0), CU, SI->getName());
2759             }
2760           }
2761         } else if (SI->getOpcode() == Instruction::AShr) {
2762           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2763             // Check to see if we are shifting out everything but the sign bit.
2764             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2765                 SI->getType()->getPrimitiveSizeInBits()-1) {
2766               // Ok, the transformation is safe.  Insert LShr. 
2767               return BinaryOperator::CreateLShr(
2768                                           SI->getOperand(0), CU, SI->getName());
2769             }
2770           }
2771         }
2772       }
2773     }
2774
2775     // Try to fold constant sub into select arguments.
2776     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2777       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2778         return R;
2779
2780     // C - zext(bool) -> bool ? C - 1 : C
2781     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2782       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2783         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2784   }
2785
2786   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2787     if (Op1I->getOpcode() == Instruction::Add) {
2788       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2789         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2790                                          I.getName());
2791       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2792         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2793                                          I.getName());
2794       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2795         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2796           // C1-(X+C2) --> (C1-C2)-X
2797           return BinaryOperator::CreateSub(
2798             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2799       }
2800     }
2801
2802     if (Op1I->hasOneUse()) {
2803       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2804       // is not used by anyone else...
2805       //
2806       if (Op1I->getOpcode() == Instruction::Sub) {
2807         // Swap the two operands of the subexpr...
2808         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2809         Op1I->setOperand(0, IIOp1);
2810         Op1I->setOperand(1, IIOp0);
2811
2812         // Create the new top level add instruction...
2813         return BinaryOperator::CreateAdd(Op0, Op1);
2814       }
2815
2816       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2817       //
2818       if (Op1I->getOpcode() == Instruction::And &&
2819           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2820         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2821
2822         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2823         return BinaryOperator::CreateAnd(Op0, NewNot);
2824       }
2825
2826       // 0 - (X sdiv C)  -> (X sdiv -C)
2827       if (Op1I->getOpcode() == Instruction::SDiv)
2828         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2829           if (CSI->isZero())
2830             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2831               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2832                                           ConstantExpr::getNeg(DivRHS));
2833
2834       // X - X*C --> X * (1-C)
2835       ConstantInt *C2 = 0;
2836       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2837         Constant *CP1 = 
2838           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2839                                              C2);
2840         return BinaryOperator::CreateMul(Op0, CP1);
2841       }
2842     }
2843   }
2844
2845   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2846     if (Op0I->getOpcode() == Instruction::Add) {
2847       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2848         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2849       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2850         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2851     } else if (Op0I->getOpcode() == Instruction::Sub) {
2852       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2853         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2854                                          I.getName());
2855     }
2856   }
2857
2858   ConstantInt *C1;
2859   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2860     if (X == Op1)  // X*C - X --> X * (C-1)
2861       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2862
2863     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2864     if (X == dyn_castFoldableMul(Op1, C2))
2865       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2866   }
2867   
2868   // Optimize pointer differences into the same array into a size.  Consider:
2869   //  &A[10] - &A[0]: we should compile this to "10".
2870   if (TD) {
2871     if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(Op0))
2872       if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(Op1))
2873         if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2874                                                    RHS->getOperand(0),
2875                                                    I.getType()))
2876           return ReplaceInstUsesWith(I, Res);
2877     
2878     // trunc(p)-trunc(q) -> trunc(p-q)
2879     if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2880       if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2881         if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2882           if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2883             if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2884                                                        RHS->getOperand(0),
2885                                                        I.getType()))
2886               return ReplaceInstUsesWith(I, Res);
2887   }
2888   
2889   return 0;
2890 }
2891
2892 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2893   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2894
2895   // If this is a 'B = x-(-A)', change to B = x+A...
2896   if (Value *V = dyn_castFNegVal(Op1))
2897     return BinaryOperator::CreateFAdd(Op0, V);
2898
2899   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2900     if (Op1I->getOpcode() == Instruction::FAdd) {
2901       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2902         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2903                                           I.getName());
2904       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2905         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2906                                           I.getName());
2907     }
2908   }
2909
2910   return 0;
2911 }
2912
2913 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2914 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2915 /// TrueIfSigned if the result of the comparison is true when the input value is
2916 /// signed.
2917 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2918                            bool &TrueIfSigned) {
2919   switch (pred) {
2920   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2921     TrueIfSigned = true;
2922     return RHS->isZero();
2923   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2924     TrueIfSigned = true;
2925     return RHS->isAllOnesValue();
2926   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2927     TrueIfSigned = false;
2928     return RHS->isAllOnesValue();
2929   case ICmpInst::ICMP_UGT:
2930     // True if LHS u> RHS and RHS == high-bit-mask - 1
2931     TrueIfSigned = true;
2932     return RHS->getValue() ==
2933       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2934   case ICmpInst::ICMP_UGE: 
2935     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2936     TrueIfSigned = true;
2937     return RHS->getValue().isSignBit();
2938   default:
2939     return false;
2940   }
2941 }
2942
2943 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2944   bool Changed = SimplifyCommutative(I);
2945   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2946
2947   if (isa<UndefValue>(Op1))              // undef * X -> 0
2948     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2949
2950   // Simplify mul instructions with a constant RHS.
2951   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2952     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
2953
2954       // ((X << C1)*C2) == (X * (C2 << C1))
2955       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2956         if (SI->getOpcode() == Instruction::Shl)
2957           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2958             return BinaryOperator::CreateMul(SI->getOperand(0),
2959                                         ConstantExpr::getShl(CI, ShOp));
2960
2961       if (CI->isZero())
2962         return ReplaceInstUsesWith(I, Op1C);  // X * 0  == 0
2963       if (CI->equalsInt(1))                  // X * 1  == X
2964         return ReplaceInstUsesWith(I, Op0);
2965       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2966         return BinaryOperator::CreateNeg(Op0, I.getName());
2967
2968       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2969       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2970         return BinaryOperator::CreateShl(Op0,
2971                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2972       }
2973     } else if (isa<VectorType>(Op1C->getType())) {
2974       if (Op1C->isNullValue())
2975         return ReplaceInstUsesWith(I, Op1C);
2976
2977       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2978         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2979           return BinaryOperator::CreateNeg(Op0, I.getName());
2980
2981         // As above, vector X*splat(1.0) -> X in all defined cases.
2982         if (Constant *Splat = Op1V->getSplatValue()) {
2983           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2984             if (CI->equalsInt(1))
2985               return ReplaceInstUsesWith(I, Op0);
2986         }
2987       }
2988     }
2989     
2990     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2991       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2992           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
2993         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2994         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2995         Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
2996         return BinaryOperator::CreateAdd(Add, C1C2);
2997         
2998       }
2999
3000     // Try to fold constant mul into select arguments.
3001     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3002       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3003         return R;
3004
3005     if (isa<PHINode>(Op0))
3006       if (Instruction *NV = FoldOpIntoPhi(I))
3007         return NV;
3008   }
3009
3010   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
3011     if (Value *Op1v = dyn_castNegVal(Op1))
3012       return BinaryOperator::CreateMul(Op0v, Op1v);
3013
3014   // (X / Y) *  Y = X - (X % Y)
3015   // (X / Y) * -Y = (X % Y) - X
3016   {
3017     Value *Op1C = Op1;
3018     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3019     if (!BO ||
3020         (BO->getOpcode() != Instruction::UDiv && 
3021          BO->getOpcode() != Instruction::SDiv)) {
3022       Op1C = Op0;
3023       BO = dyn_cast<BinaryOperator>(Op1);
3024     }
3025     Value *Neg = dyn_castNegVal(Op1C);
3026     if (BO && BO->hasOneUse() &&
3027         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
3028         (BO->getOpcode() == Instruction::UDiv ||
3029          BO->getOpcode() == Instruction::SDiv)) {
3030       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3031
3032       // If the division is exact, X % Y is zero.
3033       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3034         if (SDiv->isExact()) {
3035           if (Op1BO == Op1C)
3036             return ReplaceInstUsesWith(I, Op0BO);
3037           return BinaryOperator::CreateNeg(Op0BO);
3038         }
3039
3040       Value *Rem;
3041       if (BO->getOpcode() == Instruction::UDiv)
3042         Rem = Builder->CreateURem(Op0BO, Op1BO);
3043       else
3044         Rem = Builder->CreateSRem(Op0BO, Op1BO);
3045       Rem->takeName(BO);
3046
3047       if (Op1BO == Op1C)
3048         return BinaryOperator::CreateSub(Op0BO, Rem);
3049       return BinaryOperator::CreateSub(Rem, Op0BO);
3050     }
3051   }
3052
3053   /// i1 mul -> i1 and.
3054   if (I.getType() == Type::getInt1Ty(*Context))
3055     return BinaryOperator::CreateAnd(Op0, Op1);
3056
3057   // X*(1 << Y) --> X << Y
3058   // (1 << Y)*X --> X << Y
3059   {
3060     Value *Y;
3061     if (match(Op0, m_Shl(m_One(), m_Value(Y))))
3062       return BinaryOperator::CreateShl(Op1, Y);
3063     if (match(Op1, m_Shl(m_One(), m_Value(Y))))
3064       return BinaryOperator::CreateShl(Op0, Y);
3065   }
3066   
3067   // If one of the operands of the multiply is a cast from a boolean value, then
3068   // we know the bool is either zero or one, so this is a 'masking' multiply.
3069   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
3070   if (!isa<VectorType>(I.getType())) {
3071     // -2 is "-1 << 1" so it is all bits set except the low one.
3072     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
3073     
3074     Value *BoolCast = 0, *OtherOp = 0;
3075     if (MaskedValueIsZero(Op0, Negative2))
3076       BoolCast = Op0, OtherOp = Op1;
3077     else if (MaskedValueIsZero(Op1, Negative2))
3078       BoolCast = Op1, OtherOp = Op0;
3079
3080     if (BoolCast) {
3081       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3082                                     BoolCast, "tmp");
3083       return BinaryOperator::CreateAnd(V, OtherOp);
3084     }
3085   }
3086
3087   return Changed ? &I : 0;
3088 }
3089
3090 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3091   bool Changed = SimplifyCommutative(I);
3092   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3093
3094   // Simplify mul instructions with a constant RHS...
3095   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3096     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
3097       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
3098       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3099       if (Op1F->isExactlyValue(1.0))
3100         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
3101     } else if (isa<VectorType>(Op1C->getType())) {
3102       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
3103         // As above, vector X*splat(1.0) -> X in all defined cases.
3104         if (Constant *Splat = Op1V->getSplatValue()) {
3105           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3106             if (F->isExactlyValue(1.0))
3107               return ReplaceInstUsesWith(I, Op0);
3108         }
3109       }
3110     }
3111
3112     // Try to fold constant mul into select arguments.
3113     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3114       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3115         return R;
3116
3117     if (isa<PHINode>(Op0))
3118       if (Instruction *NV = FoldOpIntoPhi(I))
3119         return NV;
3120   }
3121
3122   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
3123     if (Value *Op1v = dyn_castFNegVal(Op1))
3124       return BinaryOperator::CreateFMul(Op0v, Op1v);
3125
3126   return Changed ? &I : 0;
3127 }
3128
3129 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3130 /// instruction.
3131 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3132   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3133   
3134   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3135   int NonNullOperand = -1;
3136   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3137     if (ST->isNullValue())
3138       NonNullOperand = 2;
3139   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3140   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3141     if (ST->isNullValue())
3142       NonNullOperand = 1;
3143   
3144   if (NonNullOperand == -1)
3145     return false;
3146   
3147   Value *SelectCond = SI->getOperand(0);
3148   
3149   // Change the div/rem to use 'Y' instead of the select.
3150   I.setOperand(1, SI->getOperand(NonNullOperand));
3151   
3152   // Okay, we know we replace the operand of the div/rem with 'Y' with no
3153   // problem.  However, the select, or the condition of the select may have
3154   // multiple uses.  Based on our knowledge that the operand must be non-zero,
3155   // propagate the known value for the select into other uses of it, and
3156   // propagate a known value of the condition into its other users.
3157   
3158   // If the select and condition only have a single use, don't bother with this,
3159   // early exit.
3160   if (SI->use_empty() && SelectCond->hasOneUse())
3161     return true;
3162   
3163   // Scan the current block backward, looking for other uses of SI.
3164   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3165   
3166   while (BBI != BBFront) {
3167     --BBI;
3168     // If we found a call to a function, we can't assume it will return, so
3169     // information from below it cannot be propagated above it.
3170     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3171       break;
3172     
3173     // Replace uses of the select or its condition with the known values.
3174     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3175          I != E; ++I) {
3176       if (*I == SI) {
3177         *I = SI->getOperand(NonNullOperand);
3178         Worklist.Add(BBI);
3179       } else if (*I == SelectCond) {
3180         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3181                                    ConstantInt::getFalse(*Context);
3182         Worklist.Add(BBI);
3183       }
3184     }
3185     
3186     // If we past the instruction, quit looking for it.
3187     if (&*BBI == SI)
3188       SI = 0;
3189     if (&*BBI == SelectCond)
3190       SelectCond = 0;
3191     
3192     // If we ran out of things to eliminate, break out of the loop.
3193     if (SelectCond == 0 && SI == 0)
3194       break;
3195     
3196   }
3197   return true;
3198 }
3199
3200
3201 /// This function implements the transforms on div instructions that work
3202 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3203 /// used by the visitors to those instructions.
3204 /// @brief Transforms common to all three div instructions
3205 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3206   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3207
3208   // undef / X -> 0        for integer.
3209   // undef / X -> undef    for FP (the undef could be a snan).
3210   if (isa<UndefValue>(Op0)) {
3211     if (Op0->getType()->isFPOrFPVector())
3212       return ReplaceInstUsesWith(I, Op0);
3213     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3214   }
3215
3216   // X / undef -> undef
3217   if (isa<UndefValue>(Op1))
3218     return ReplaceInstUsesWith(I, Op1);
3219
3220   return 0;
3221 }
3222
3223 /// This function implements the transforms common to both integer division
3224 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3225 /// division instructions.
3226 /// @brief Common integer divide transforms
3227 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3228   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3229
3230   // (sdiv X, X) --> 1     (udiv X, X) --> 1
3231   if (Op0 == Op1) {
3232     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3233       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
3234       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3235       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3236     }
3237
3238     Constant *CI = ConstantInt::get(I.getType(), 1);
3239     return ReplaceInstUsesWith(I, CI);
3240   }
3241   
3242   if (Instruction *Common = commonDivTransforms(I))
3243     return Common;
3244   
3245   // Handle cases involving: [su]div X, (select Cond, Y, Z)
3246   // This does not apply for fdiv.
3247   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3248     return &I;
3249
3250   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3251     // div X, 1 == X
3252     if (RHS->equalsInt(1))
3253       return ReplaceInstUsesWith(I, Op0);
3254
3255     // (X / C1) / C2  -> X / (C1*C2)
3256     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3257       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3258         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3259           if (MultiplyOverflows(RHS, LHSRHS,
3260                                 I.getOpcode()==Instruction::SDiv))
3261             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3262           else 
3263             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3264                                       ConstantExpr::getMul(RHS, LHSRHS));
3265         }
3266
3267     if (!RHS->isZero()) { // avoid X udiv 0
3268       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3269         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3270           return R;
3271       if (isa<PHINode>(Op0))
3272         if (Instruction *NV = FoldOpIntoPhi(I))
3273           return NV;
3274     }
3275   }
3276
3277   // 0 / X == 0, we don't need to preserve faults!
3278   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3279     if (LHS->equalsInt(0))
3280       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3281
3282   // It can't be division by zero, hence it must be division by one.
3283   if (I.getType() == Type::getInt1Ty(*Context))
3284     return ReplaceInstUsesWith(I, Op0);
3285
3286   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3287     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3288       // div X, 1 == X
3289       if (X->isOne())
3290         return ReplaceInstUsesWith(I, Op0);
3291   }
3292
3293   return 0;
3294 }
3295
3296 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3297   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3298
3299   // Handle the integer div common cases
3300   if (Instruction *Common = commonIDivTransforms(I))
3301     return Common;
3302
3303   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3304     // X udiv C^2 -> X >> C
3305     // Check to see if this is an unsigned division with an exact power of 2,
3306     // if so, convert to a right shift.
3307     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3308       return BinaryOperator::CreateLShr(Op0, 
3309             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3310
3311     // X udiv C, where C >= signbit
3312     if (C->getValue().isNegative()) {
3313       Value *IC = Builder->CreateICmpULT( Op0, C);
3314       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3315                                 ConstantInt::get(I.getType(), 1));
3316     }
3317   }
3318
3319   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3320   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3321     if (RHSI->getOpcode() == Instruction::Shl &&
3322         isa<ConstantInt>(RHSI->getOperand(0))) {
3323       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3324       if (C1.isPowerOf2()) {
3325         Value *N = RHSI->getOperand(1);
3326         const Type *NTy = N->getType();
3327         if (uint32_t C2 = C1.logBase2())
3328           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3329         return BinaryOperator::CreateLShr(Op0, N);
3330       }
3331     }
3332   }
3333   
3334   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3335   // where C1&C2 are powers of two.
3336   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3337     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3338       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3339         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3340         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3341           // Compute the shift amounts
3342           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3343           // Construct the "on true" case of the select
3344           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3345           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3346   
3347           // Construct the "on false" case of the select
3348           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3349           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3350
3351           // construct the select instruction and return it.
3352           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3353         }
3354       }
3355   return 0;
3356 }
3357
3358 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3359   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3360
3361   // Handle the integer div common cases
3362   if (Instruction *Common = commonIDivTransforms(I))
3363     return Common;
3364
3365   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3366     // sdiv X, -1 == -X
3367     if (RHS->isAllOnesValue())
3368       return BinaryOperator::CreateNeg(Op0);
3369
3370     // sdiv X, C  -->  ashr X, log2(C)
3371     if (cast<SDivOperator>(&I)->isExact() &&
3372         RHS->getValue().isNonNegative() &&
3373         RHS->getValue().isPowerOf2()) {
3374       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3375                                             RHS->getValue().exactLogBase2());
3376       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3377     }
3378
3379     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3380     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3381       if (isa<Constant>(Sub->getOperand(0)) &&
3382           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3383           Sub->hasNoSignedWrap())
3384         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3385                                           ConstantExpr::getNeg(RHS));
3386   }
3387
3388   // If the sign bits of both operands are zero (i.e. we can prove they are
3389   // unsigned inputs), turn this into a udiv.
3390   if (I.getType()->isInteger()) {
3391     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3392     if (MaskedValueIsZero(Op0, Mask)) {
3393       if (MaskedValueIsZero(Op1, Mask)) {
3394         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3395         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3396       }
3397       ConstantInt *ShiftedInt;
3398       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3399           ShiftedInt->getValue().isPowerOf2()) {
3400         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3401         // Safe because the only negative value (1 << Y) can take on is
3402         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3403         // the sign bit set.
3404         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3405       }
3406     }
3407   }
3408   
3409   return 0;
3410 }
3411
3412 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3413   return commonDivTransforms(I);
3414 }
3415
3416 /// This function implements the transforms on rem instructions that work
3417 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3418 /// is used by the visitors to those instructions.
3419 /// @brief Transforms common to all three rem instructions
3420 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3421   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3422
3423   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3424     if (I.getType()->isFPOrFPVector())
3425       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3426     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3427   }
3428   if (isa<UndefValue>(Op1))
3429     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3430
3431   // Handle cases involving: rem X, (select Cond, Y, Z)
3432   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3433     return &I;
3434
3435   return 0;
3436 }
3437
3438 /// This function implements the transforms common to both integer remainder
3439 /// instructions (urem and srem). It is called by the visitors to those integer
3440 /// remainder instructions.
3441 /// @brief Common integer remainder transforms
3442 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3443   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3444
3445   if (Instruction *common = commonRemTransforms(I))
3446     return common;
3447
3448   // 0 % X == 0 for integer, we don't need to preserve faults!
3449   if (Constant *LHS = dyn_cast<Constant>(Op0))
3450     if (LHS->isNullValue())
3451       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3452
3453   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3454     // X % 0 == undef, we don't need to preserve faults!
3455     if (RHS->equalsInt(0))
3456       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3457     
3458     if (RHS->equalsInt(1))  // X % 1 == 0
3459       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3460
3461     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3462       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3463         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3464           return R;
3465       } else if (isa<PHINode>(Op0I)) {
3466         if (Instruction *NV = FoldOpIntoPhi(I))
3467           return NV;
3468       }
3469
3470       // See if we can fold away this rem instruction.
3471       if (SimplifyDemandedInstructionBits(I))
3472         return &I;
3473     }
3474   }
3475
3476   return 0;
3477 }
3478
3479 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3480   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3481
3482   if (Instruction *common = commonIRemTransforms(I))
3483     return common;
3484   
3485   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3486     // X urem C^2 -> X and C
3487     // Check to see if this is an unsigned remainder with an exact power of 2,
3488     // if so, convert to a bitwise and.
3489     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3490       if (C->getValue().isPowerOf2())
3491         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3492   }
3493
3494   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3495     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3496     if (RHSI->getOpcode() == Instruction::Shl &&
3497         isa<ConstantInt>(RHSI->getOperand(0))) {
3498       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3499         Constant *N1 = Constant::getAllOnesValue(I.getType());
3500         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3501         return BinaryOperator::CreateAnd(Op0, Add);
3502       }
3503     }
3504   }
3505
3506   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3507   // where C1&C2 are powers of two.
3508   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3509     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3510       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3511         // STO == 0 and SFO == 0 handled above.
3512         if ((STO->getValue().isPowerOf2()) && 
3513             (SFO->getValue().isPowerOf2())) {
3514           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3515                                               SI->getName()+".t");
3516           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3517                                                SI->getName()+".f");
3518           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3519         }
3520       }
3521   }
3522   
3523   return 0;
3524 }
3525
3526 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3527   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3528
3529   // Handle the integer rem common cases
3530   if (Instruction *Common = commonIRemTransforms(I))
3531     return Common;
3532   
3533   if (Value *RHSNeg = dyn_castNegVal(Op1))
3534     if (!isa<Constant>(RHSNeg) ||
3535         (isa<ConstantInt>(RHSNeg) &&
3536          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3537       // X % -Y -> X % Y
3538       Worklist.AddValue(I.getOperand(1));
3539       I.setOperand(1, RHSNeg);
3540       return &I;
3541     }
3542
3543   // If the sign bits of both operands are zero (i.e. we can prove they are
3544   // unsigned inputs), turn this into a urem.
3545   if (I.getType()->isInteger()) {
3546     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3547     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3548       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3549       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3550     }
3551   }
3552
3553   // If it's a constant vector, flip any negative values positive.
3554   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3555     unsigned VWidth = RHSV->getNumOperands();
3556
3557     bool hasNegative = false;
3558     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3559       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3560         if (RHS->getValue().isNegative())
3561           hasNegative = true;
3562
3563     if (hasNegative) {
3564       std::vector<Constant *> Elts(VWidth);
3565       for (unsigned i = 0; i != VWidth; ++i) {
3566         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3567           if (RHS->getValue().isNegative())
3568             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3569           else
3570             Elts[i] = RHS;
3571         }
3572       }
3573
3574       Constant *NewRHSV = ConstantVector::get(Elts);
3575       if (NewRHSV != RHSV) {
3576         Worklist.AddValue(I.getOperand(1));
3577         I.setOperand(1, NewRHSV);
3578         return &I;
3579       }
3580     }
3581   }
3582
3583   return 0;
3584 }
3585
3586 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3587   return commonRemTransforms(I);
3588 }
3589
3590 // isOneBitSet - Return true if there is exactly one bit set in the specified
3591 // constant.
3592 static bool isOneBitSet(const ConstantInt *CI) {
3593   return CI->getValue().isPowerOf2();
3594 }
3595
3596 // isHighOnes - Return true if the constant is of the form 1+0+.
3597 // This is the same as lowones(~X).
3598 static bool isHighOnes(const ConstantInt *CI) {
3599   return (~CI->getValue() + 1).isPowerOf2();
3600 }
3601
3602 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3603 /// are carefully arranged to allow folding of expressions such as:
3604 ///
3605 ///      (A < B) | (A > B) --> (A != B)
3606 ///
3607 /// Note that this is only valid if the first and second predicates have the
3608 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3609 ///
3610 /// Three bits are used to represent the condition, as follows:
3611 ///   0  A > B
3612 ///   1  A == B
3613 ///   2  A < B
3614 ///
3615 /// <=>  Value  Definition
3616 /// 000     0   Always false
3617 /// 001     1   A >  B
3618 /// 010     2   A == B
3619 /// 011     3   A >= B
3620 /// 100     4   A <  B
3621 /// 101     5   A != B
3622 /// 110     6   A <= B
3623 /// 111     7   Always true
3624 ///  
3625 static unsigned getICmpCode(const ICmpInst *ICI) {
3626   switch (ICI->getPredicate()) {
3627     // False -> 0
3628   case ICmpInst::ICMP_UGT: return 1;  // 001
3629   case ICmpInst::ICMP_SGT: return 1;  // 001
3630   case ICmpInst::ICMP_EQ:  return 2;  // 010
3631   case ICmpInst::ICMP_UGE: return 3;  // 011
3632   case ICmpInst::ICMP_SGE: return 3;  // 011
3633   case ICmpInst::ICMP_ULT: return 4;  // 100
3634   case ICmpInst::ICMP_SLT: return 4;  // 100
3635   case ICmpInst::ICMP_NE:  return 5;  // 101
3636   case ICmpInst::ICMP_ULE: return 6;  // 110
3637   case ICmpInst::ICMP_SLE: return 6;  // 110
3638     // True -> 7
3639   default:
3640     llvm_unreachable("Invalid ICmp predicate!");
3641     return 0;
3642   }
3643 }
3644
3645 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3646 /// predicate into a three bit mask. It also returns whether it is an ordered
3647 /// predicate by reference.
3648 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3649   isOrdered = false;
3650   switch (CC) {
3651   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3652   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3653   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3654   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3655   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3656   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3657   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3658   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3659   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3660   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3661   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3662   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3663   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3664   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3665     // True -> 7
3666   default:
3667     // Not expecting FCMP_FALSE and FCMP_TRUE;
3668     llvm_unreachable("Unexpected FCmp predicate!");
3669     return 0;
3670   }
3671 }
3672
3673 /// getICmpValue - This is the complement of getICmpCode, which turns an
3674 /// opcode and two operands into either a constant true or false, or a brand 
3675 /// new ICmp instruction. The sign is passed in to determine which kind
3676 /// of predicate to use in the new icmp instruction.
3677 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3678                            LLVMContext *Context) {
3679   switch (code) {
3680   default: llvm_unreachable("Illegal ICmp code!");
3681   case  0: return ConstantInt::getFalse(*Context);
3682   case  1: 
3683     if (sign)
3684       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3685     else
3686       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3687   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3688   case  3: 
3689     if (sign)
3690       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3691     else
3692       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3693   case  4: 
3694     if (sign)
3695       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3696     else
3697       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3698   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3699   case  6: 
3700     if (sign)
3701       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3702     else
3703       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3704   case  7: return ConstantInt::getTrue(*Context);
3705   }
3706 }
3707
3708 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3709 /// opcode and two operands into either a FCmp instruction. isordered is passed
3710 /// in to determine which kind of predicate to use in the new fcmp instruction.
3711 static Value *getFCmpValue(bool isordered, unsigned code,
3712                            Value *LHS, Value *RHS, LLVMContext *Context) {
3713   switch (code) {
3714   default: llvm_unreachable("Illegal FCmp code!");
3715   case  0:
3716     if (isordered)
3717       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3718     else
3719       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3720   case  1: 
3721     if (isordered)
3722       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3723     else
3724       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3725   case  2: 
3726     if (isordered)
3727       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3728     else
3729       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3730   case  3: 
3731     if (isordered)
3732       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3733     else
3734       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3735   case  4: 
3736     if (isordered)
3737       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3738     else
3739       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3740   case  5: 
3741     if (isordered)
3742       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3743     else
3744       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3745   case  6: 
3746     if (isordered)
3747       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3748     else
3749       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3750   case  7: return ConstantInt::getTrue(*Context);
3751   }
3752 }
3753
3754 /// PredicatesFoldable - Return true if both predicates match sign or if at
3755 /// least one of them is an equality comparison (which is signless).
3756 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3757   return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3758          (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3759          (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
3760 }
3761
3762 namespace { 
3763 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3764 struct FoldICmpLogical {
3765   InstCombiner &IC;
3766   Value *LHS, *RHS;
3767   ICmpInst::Predicate pred;
3768   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3769     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3770       pred(ICI->getPredicate()) {}
3771   bool shouldApply(Value *V) const {
3772     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3773       if (PredicatesFoldable(pred, ICI->getPredicate()))
3774         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3775                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3776     return false;
3777   }
3778   Instruction *apply(Instruction &Log) const {
3779     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3780     if (ICI->getOperand(0) != LHS) {
3781       assert(ICI->getOperand(1) == LHS);
3782       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3783     }
3784
3785     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3786     unsigned LHSCode = getICmpCode(ICI);
3787     unsigned RHSCode = getICmpCode(RHSICI);
3788     unsigned Code;
3789     switch (Log.getOpcode()) {
3790     case Instruction::And: Code = LHSCode & RHSCode; break;
3791     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3792     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3793     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3794     }
3795
3796     bool isSigned = RHSICI->isSigned() || ICI->isSigned();
3797     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3798     if (Instruction *I = dyn_cast<Instruction>(RV))
3799       return I;
3800     // Otherwise, it's a constant boolean value...
3801     return IC.ReplaceInstUsesWith(Log, RV);
3802   }
3803 };
3804 } // end anonymous namespace
3805
3806 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3807 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3808 // guaranteed to be a binary operator.
3809 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3810                                     ConstantInt *OpRHS,
3811                                     ConstantInt *AndRHS,
3812                                     BinaryOperator &TheAnd) {
3813   Value *X = Op->getOperand(0);
3814   Constant *Together = 0;
3815   if (!Op->isShift())
3816     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3817
3818   switch (Op->getOpcode()) {
3819   case Instruction::Xor:
3820     if (Op->hasOneUse()) {
3821       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3822       Value *And = Builder->CreateAnd(X, AndRHS);
3823       And->takeName(Op);
3824       return BinaryOperator::CreateXor(And, Together);
3825     }
3826     break;
3827   case Instruction::Or:
3828     if (Together == AndRHS) // (X | C) & C --> C
3829       return ReplaceInstUsesWith(TheAnd, AndRHS);
3830
3831     if (Op->hasOneUse() && Together != OpRHS) {
3832       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3833       Value *Or = Builder->CreateOr(X, Together);
3834       Or->takeName(Op);
3835       return BinaryOperator::CreateAnd(Or, AndRHS);
3836     }
3837     break;
3838   case Instruction::Add:
3839     if (Op->hasOneUse()) {
3840       // Adding a one to a single bit bit-field should be turned into an XOR
3841       // of the bit.  First thing to check is to see if this AND is with a
3842       // single bit constant.
3843       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3844
3845       // If there is only one bit set...
3846       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3847         // Ok, at this point, we know that we are masking the result of the
3848         // ADD down to exactly one bit.  If the constant we are adding has
3849         // no bits set below this bit, then we can eliminate the ADD.
3850         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3851
3852         // Check to see if any bits below the one bit set in AndRHSV are set.
3853         if ((AddRHS & (AndRHSV-1)) == 0) {
3854           // If not, the only thing that can effect the output of the AND is
3855           // the bit specified by AndRHSV.  If that bit is set, the effect of
3856           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3857           // no effect.
3858           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3859             TheAnd.setOperand(0, X);
3860             return &TheAnd;
3861           } else {
3862             // Pull the XOR out of the AND.
3863             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3864             NewAnd->takeName(Op);
3865             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3866           }
3867         }
3868       }
3869     }
3870     break;
3871
3872   case Instruction::Shl: {
3873     // We know that the AND will not produce any of the bits shifted in, so if
3874     // the anded constant includes them, clear them now!
3875     //
3876     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3877     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3878     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3879     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3880
3881     if (CI->getValue() == ShlMask) { 
3882     // Masking out bits that the shift already masks
3883       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3884     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3885       TheAnd.setOperand(1, CI);
3886       return &TheAnd;
3887     }
3888     break;
3889   }
3890   case Instruction::LShr:
3891   {
3892     // We know that the AND will not produce any of the bits shifted in, so if
3893     // the anded constant includes them, clear them now!  This only applies to
3894     // unsigned shifts, because a signed shr may bring in set bits!
3895     //
3896     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3897     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3898     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3899     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3900
3901     if (CI->getValue() == ShrMask) {   
3902     // Masking out bits that the shift already masks.
3903       return ReplaceInstUsesWith(TheAnd, Op);
3904     } else if (CI != AndRHS) {
3905       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3906       return &TheAnd;
3907     }
3908     break;
3909   }
3910   case Instruction::AShr:
3911     // Signed shr.
3912     // See if this is shifting in some sign extension, then masking it out
3913     // with an and.
3914     if (Op->hasOneUse()) {
3915       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3916       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3917       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3918       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3919       if (C == AndRHS) {          // Masking out bits shifted in.
3920         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3921         // Make the argument unsigned.
3922         Value *ShVal = Op->getOperand(0);
3923         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3924         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3925       }
3926     }
3927     break;
3928   }
3929   return 0;
3930 }
3931
3932
3933 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3934 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3935 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3936 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3937 /// insert new instructions.
3938 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3939                                            bool isSigned, bool Inside, 
3940                                            Instruction &IB) {
3941   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3942             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3943          "Lo is not <= Hi in range emission code!");
3944     
3945   if (Inside) {
3946     if (Lo == Hi)  // Trivially false.
3947       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3948
3949     // V >= Min && V < Hi --> V < Hi
3950     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3951       ICmpInst::Predicate pred = (isSigned ? 
3952         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3953       return new ICmpInst(pred, V, Hi);
3954     }
3955
3956     // Emit V-Lo <u Hi-Lo
3957     Constant *NegLo = ConstantExpr::getNeg(Lo);
3958     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3959     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3960     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3961   }
3962
3963   if (Lo == Hi)  // Trivially true.
3964     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3965
3966   // V < Min || V >= Hi -> V > Hi-1
3967   Hi = SubOne(cast<ConstantInt>(Hi));
3968   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3969     ICmpInst::Predicate pred = (isSigned ? 
3970         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3971     return new ICmpInst(pred, V, Hi);
3972   }
3973
3974   // Emit V-Lo >u Hi-1-Lo
3975   // Note that Hi has already had one subtracted from it, above.
3976   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3977   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3978   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3979   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3980 }
3981
3982 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3983 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3984 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3985 // not, since all 1s are not contiguous.
3986 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3987   const APInt& V = Val->getValue();
3988   uint32_t BitWidth = Val->getType()->getBitWidth();
3989   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3990
3991   // look for the first zero bit after the run of ones
3992   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3993   // look for the first non-zero bit
3994   ME = V.getActiveBits(); 
3995   return true;
3996 }
3997
3998 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3999 /// where isSub determines whether the operator is a sub.  If we can fold one of
4000 /// the following xforms:
4001 /// 
4002 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4003 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4004 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4005 ///
4006 /// return (A +/- B).
4007 ///
4008 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
4009                                         ConstantInt *Mask, bool isSub,
4010                                         Instruction &I) {
4011   Instruction *LHSI = dyn_cast<Instruction>(LHS);
4012   if (!LHSI || LHSI->getNumOperands() != 2 ||
4013       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4014
4015   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4016
4017   switch (LHSI->getOpcode()) {
4018   default: return 0;
4019   case Instruction::And:
4020     if (ConstantExpr::getAnd(N, Mask) == Mask) {
4021       // If the AndRHS is a power of two minus one (0+1+), this is simple.
4022       if ((Mask->getValue().countLeadingZeros() + 
4023            Mask->getValue().countPopulation()) == 
4024           Mask->getValue().getBitWidth())
4025         break;
4026
4027       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4028       // part, we don't need any explicit masks to take them out of A.  If that
4029       // is all N is, ignore it.
4030       uint32_t MB = 0, ME = 0;
4031       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
4032         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
4033         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4034         if (MaskedValueIsZero(RHS, Mask))
4035           break;
4036       }
4037     }
4038     return 0;
4039   case Instruction::Or:
4040   case Instruction::Xor:
4041     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4042     if ((Mask->getValue().countLeadingZeros() + 
4043          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
4044         && ConstantExpr::getAnd(N, Mask)->isNullValue())
4045       break;
4046     return 0;
4047   }
4048   
4049   if (isSub)
4050     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4051   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
4052 }
4053
4054 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4055 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4056                                           ICmpInst *LHS, ICmpInst *RHS) {
4057   Value *Val, *Val2;
4058   ConstantInt *LHSCst, *RHSCst;
4059   ICmpInst::Predicate LHSCC, RHSCC;
4060   
4061   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
4062   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4063                          m_ConstantInt(LHSCst))) ||
4064       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4065                          m_ConstantInt(RHSCst))))
4066     return 0;
4067   
4068   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4069   // where C is a power of 2
4070   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
4071       LHSCst->getValue().isPowerOf2()) {
4072     Value *NewOr = Builder->CreateOr(Val, Val2);
4073     return new ICmpInst(LHSCC, NewOr, LHSCst);
4074   }
4075   
4076   // From here on, we only handle:
4077   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4078   if (Val != Val2) return 0;
4079   
4080   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4081   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4082       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4083       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4084       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4085     return 0;
4086   
4087   // We can't fold (ugt x, C) & (sgt x, C2).
4088   if (!PredicatesFoldable(LHSCC, RHSCC))
4089     return 0;
4090     
4091   // Ensure that the larger constant is on the RHS.
4092   bool ShouldSwap;
4093   if (CmpInst::isSigned(LHSCC) ||
4094       (ICmpInst::isEquality(LHSCC) && 
4095        CmpInst::isSigned(RHSCC)))
4096     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4097   else
4098     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4099     
4100   if (ShouldSwap) {
4101     std::swap(LHS, RHS);
4102     std::swap(LHSCst, RHSCst);
4103     std::swap(LHSCC, RHSCC);
4104   }
4105
4106   // At this point, we know we have have two icmp instructions
4107   // comparing a value against two constants and and'ing the result
4108   // together.  Because of the above check, we know that we only have
4109   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
4110   // (from the FoldICmpLogical check above), that the two constants 
4111   // are not equal and that the larger constant is on the RHS
4112   assert(LHSCst != RHSCst && "Compares not folded above?");
4113
4114   switch (LHSCC) {
4115   default: llvm_unreachable("Unknown integer condition code!");
4116   case ICmpInst::ICMP_EQ:
4117     switch (RHSCC) {
4118     default: llvm_unreachable("Unknown integer condition code!");
4119     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
4120     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
4121     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
4122       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4123     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
4124     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
4125     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
4126       return ReplaceInstUsesWith(I, LHS);
4127     }
4128   case ICmpInst::ICMP_NE:
4129     switch (RHSCC) {
4130     default: llvm_unreachable("Unknown integer condition code!");
4131     case ICmpInst::ICMP_ULT:
4132       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4133         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
4134       break;                        // (X != 13 & X u< 15) -> no change
4135     case ICmpInst::ICMP_SLT:
4136       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4137         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
4138       break;                        // (X != 13 & X s< 15) -> no change
4139     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
4140     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
4141     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
4142       return ReplaceInstUsesWith(I, RHS);
4143     case ICmpInst::ICMP_NE:
4144       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4145         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4146         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4147         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4148                             ConstantInt::get(Add->getType(), 1));
4149       }
4150       break;                        // (X != 13 & X != 15) -> no change
4151     }
4152     break;
4153   case ICmpInst::ICMP_ULT:
4154     switch (RHSCC) {
4155     default: llvm_unreachable("Unknown integer condition code!");
4156     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
4157     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
4158       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4159     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
4160       break;
4161     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
4162     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
4163       return ReplaceInstUsesWith(I, LHS);
4164     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
4165       break;
4166     }
4167     break;
4168   case ICmpInst::ICMP_SLT:
4169     switch (RHSCC) {
4170     default: llvm_unreachable("Unknown integer condition code!");
4171     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
4172     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
4173       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4174     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
4175       break;
4176     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
4177     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
4178       return ReplaceInstUsesWith(I, LHS);
4179     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
4180       break;
4181     }
4182     break;
4183   case ICmpInst::ICMP_UGT:
4184     switch (RHSCC) {
4185     default: llvm_unreachable("Unknown integer condition code!");
4186     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
4187     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
4188       return ReplaceInstUsesWith(I, RHS);
4189     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
4190       break;
4191     case ICmpInst::ICMP_NE:
4192       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4193         return new ICmpInst(LHSCC, Val, RHSCst);
4194       break;                        // (X u> 13 & X != 15) -> no change
4195     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
4196       return InsertRangeTest(Val, AddOne(LHSCst),
4197                              RHSCst, false, true, I);
4198     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
4199       break;
4200     }
4201     break;
4202   case ICmpInst::ICMP_SGT:
4203     switch (RHSCC) {
4204     default: llvm_unreachable("Unknown integer condition code!");
4205     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
4206     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
4207       return ReplaceInstUsesWith(I, RHS);
4208     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
4209       break;
4210     case ICmpInst::ICMP_NE:
4211       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4212         return new ICmpInst(LHSCC, Val, RHSCst);
4213       break;                        // (X s> 13 & X != 15) -> no change
4214     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
4215       return InsertRangeTest(Val, AddOne(LHSCst),
4216                              RHSCst, true, true, I);
4217     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
4218       break;
4219     }
4220     break;
4221   }
4222  
4223   return 0;
4224 }
4225
4226 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4227                                           FCmpInst *RHS) {
4228   
4229   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4230       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4231     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4232     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4233       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4234         // If either of the constants are nans, then the whole thing returns
4235         // false.
4236         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4237           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4238         return new FCmpInst(FCmpInst::FCMP_ORD,
4239                             LHS->getOperand(0), RHS->getOperand(0));
4240       }
4241     
4242     // Handle vector zeros.  This occurs because the canonical form of
4243     // "fcmp ord x,x" is "fcmp ord x, 0".
4244     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4245         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4246       return new FCmpInst(FCmpInst::FCMP_ORD,
4247                           LHS->getOperand(0), RHS->getOperand(0));
4248     return 0;
4249   }
4250   
4251   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4252   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4253   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4254   
4255   
4256   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4257     // Swap RHS operands to match LHS.
4258     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4259     std::swap(Op1LHS, Op1RHS);
4260   }
4261   
4262   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4263     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4264     if (Op0CC == Op1CC)
4265       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4266     
4267     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
4268       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4269     if (Op0CC == FCmpInst::FCMP_TRUE)
4270       return ReplaceInstUsesWith(I, RHS);
4271     if (Op1CC == FCmpInst::FCMP_TRUE)
4272       return ReplaceInstUsesWith(I, LHS);
4273     
4274     bool Op0Ordered;
4275     bool Op1Ordered;
4276     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4277     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4278     if (Op1Pred == 0) {
4279       std::swap(LHS, RHS);
4280       std::swap(Op0Pred, Op1Pred);
4281       std::swap(Op0Ordered, Op1Ordered);
4282     }
4283     if (Op0Pred == 0) {
4284       // uno && ueq -> uno && (uno || eq) -> ueq
4285       // ord && olt -> ord && (ord && lt) -> olt
4286       if (Op0Ordered == Op1Ordered)
4287         return ReplaceInstUsesWith(I, RHS);
4288       
4289       // uno && oeq -> uno && (ord && eq) -> false
4290       // uno && ord -> false
4291       if (!Op0Ordered)
4292         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4293       // ord && ueq -> ord && (uno || eq) -> oeq
4294       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4295                                             Op0LHS, Op0RHS, Context));
4296     }
4297   }
4298
4299   return 0;
4300 }
4301
4302
4303 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4304   bool Changed = SimplifyCommutative(I);
4305   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4306
4307   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4308     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4309
4310   // and X, X = X
4311   if (Op0 == Op1)
4312     return ReplaceInstUsesWith(I, Op1);
4313
4314   // See if we can simplify any instructions used by the instruction whose sole 
4315   // purpose is to compute bits we don't care about.
4316   if (SimplifyDemandedInstructionBits(I))
4317     return &I;
4318   if (isa<VectorType>(I.getType())) {
4319     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4320       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4321         return ReplaceInstUsesWith(I, I.getOperand(0));
4322     } else if (isa<ConstantAggregateZero>(Op1)) {
4323       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4324     }
4325   }
4326
4327   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4328     const APInt &AndRHSMask = AndRHS->getValue();
4329     APInt NotAndRHS(~AndRHSMask);
4330
4331     // Optimize a variety of ((val OP C1) & C2) combinations...
4332     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4333       Value *Op0LHS = Op0I->getOperand(0);
4334       Value *Op0RHS = Op0I->getOperand(1);
4335       switch (Op0I->getOpcode()) {
4336       default: break;
4337       case Instruction::Xor:
4338       case Instruction::Or:
4339         // If the mask is only needed on one incoming arm, push it up.
4340         if (!Op0I->hasOneUse()) break;
4341           
4342         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4343           // Not masking anything out for the LHS, move to RHS.
4344           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4345                                              Op0RHS->getName()+".masked");
4346           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4347         }
4348         if (!isa<Constant>(Op0RHS) &&
4349             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4350           // Not masking anything out for the RHS, move to LHS.
4351           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4352                                              Op0LHS->getName()+".masked");
4353           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
4354         }
4355
4356         break;
4357       case Instruction::Add:
4358         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4359         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4360         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4361         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4362           return BinaryOperator::CreateAnd(V, AndRHS);
4363         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4364           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4365         break;
4366
4367       case Instruction::Sub:
4368         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4369         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4370         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4371         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4372           return BinaryOperator::CreateAnd(V, AndRHS);
4373
4374         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4375         // has 1's for all bits that the subtraction with A might affect.
4376         if (Op0I->hasOneUse()) {
4377           uint32_t BitWidth = AndRHSMask.getBitWidth();
4378           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4379           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4380
4381           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4382           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4383               MaskedValueIsZero(Op0LHS, Mask)) {
4384             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4385             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4386           }
4387         }
4388         break;
4389
4390       case Instruction::Shl:
4391       case Instruction::LShr:
4392         // (1 << x) & 1 --> zext(x == 0)
4393         // (1 >> x) & 1 --> zext(x == 0)
4394         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4395           Value *NewICmp =
4396             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4397           return new ZExtInst(NewICmp, I.getType());
4398         }
4399         break;
4400       }
4401
4402       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4403         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4404           return Res;
4405     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4406       // If this is an integer truncation or change from signed-to-unsigned, and
4407       // if the source is an and/or with immediate, transform it.  This
4408       // frequently occurs for bitfield accesses.
4409       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4410         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4411             CastOp->getNumOperands() == 2)
4412           if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
4413             if (CastOp->getOpcode() == Instruction::And) {
4414               // Change: and (cast (and X, C1) to T), C2
4415               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4416               // This will fold the two constants together, which may allow 
4417               // other simplifications.
4418               Value *NewCast = Builder->CreateTruncOrBitCast(
4419                 CastOp->getOperand(0), I.getType(), 
4420                 CastOp->getName()+".shrunk");
4421               // trunc_or_bitcast(C1)&C2
4422               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4423               C3 = ConstantExpr::getAnd(C3, AndRHS);
4424               return BinaryOperator::CreateAnd(NewCast, C3);
4425             } else if (CastOp->getOpcode() == Instruction::Or) {
4426               // Change: and (cast (or X, C1) to T), C2
4427               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4428               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4429               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4430                 // trunc(C1)&C2
4431                 return ReplaceInstUsesWith(I, AndRHS);
4432             }
4433           }
4434       }
4435     }
4436
4437     // Try to fold constant and into select arguments.
4438     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4439       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4440         return R;
4441     if (isa<PHINode>(Op0))
4442       if (Instruction *NV = FoldOpIntoPhi(I))
4443         return NV;
4444   }
4445
4446   Value *Op0NotVal = dyn_castNotVal(Op0);
4447   Value *Op1NotVal = dyn_castNotVal(Op1);
4448
4449   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4450     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4451
4452   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4453   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4454     Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4455                                   I.getName()+".demorgan");
4456     return BinaryOperator::CreateNot(Or);
4457   }
4458   
4459   {
4460     Value *A = 0, *B = 0, *C = 0, *D = 0;
4461     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4462       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4463         return ReplaceInstUsesWith(I, Op1);
4464     
4465       // (A|B) & ~(A&B) -> A^B
4466       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4467         if ((A == C && B == D) || (A == D && B == C))
4468           return BinaryOperator::CreateXor(A, B);
4469       }
4470     }
4471     
4472     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4473       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4474         return ReplaceInstUsesWith(I, Op0);
4475
4476       // ~(A&B) & (A|B) -> A^B
4477       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4478         if ((A == C && B == D) || (A == D && B == C))
4479           return BinaryOperator::CreateXor(A, B);
4480       }
4481     }
4482     
4483     if (Op0->hasOneUse() &&
4484         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4485       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4486         I.swapOperands();     // Simplify below
4487         std::swap(Op0, Op1);
4488       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4489         cast<BinaryOperator>(Op0)->swapOperands();
4490         I.swapOperands();     // Simplify below
4491         std::swap(Op0, Op1);
4492       }
4493     }
4494
4495     if (Op1->hasOneUse() &&
4496         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4497       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4498         cast<BinaryOperator>(Op1)->swapOperands();
4499         std::swap(A, B);
4500       }
4501       if (A == Op0)                                // A&(A^B) -> A & ~B
4502         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4503     }
4504
4505     // (A&((~A)|B)) -> A&B
4506     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4507         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4508       return BinaryOperator::CreateAnd(A, Op1);
4509     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4510         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4511       return BinaryOperator::CreateAnd(A, Op0);
4512   }
4513   
4514   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4515     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4516     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4517       return R;
4518
4519     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4520       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4521         return Res;
4522   }
4523
4524   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4525   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4526     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4527       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4528         const Type *SrcTy = Op0C->getOperand(0)->getType();
4529         if (SrcTy == Op1C->getOperand(0)->getType() &&
4530             SrcTy->isIntOrIntVector() &&
4531             // Only do this if the casts both really cause code to be generated.
4532             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4533                               I.getType(), TD) &&
4534             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4535                               I.getType(), TD)) {
4536           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4537                                             Op1C->getOperand(0), I.getName());
4538           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4539         }
4540       }
4541     
4542   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4543   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4544     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4545       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4546           SI0->getOperand(1) == SI1->getOperand(1) &&
4547           (SI0->hasOneUse() || SI1->hasOneUse())) {
4548         Value *NewOp =
4549           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4550                              SI0->getName());
4551         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4552                                       SI1->getOperand(1));
4553       }
4554   }
4555
4556   // If and'ing two fcmp, try combine them into one.
4557   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4558     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4559       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4560         return Res;
4561   }
4562
4563   return Changed ? &I : 0;
4564 }
4565
4566 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4567 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4568 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4569 /// the expression came from the corresponding "byte swapped" byte in some other
4570 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4571 /// we know that the expression deposits the low byte of %X into the high byte
4572 /// of the bswap result and that all other bytes are zero.  This expression is
4573 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4574 /// match.
4575 ///
4576 /// This function returns true if the match was unsuccessful and false if so.
4577 /// On entry to the function the "OverallLeftShift" is a signed integer value
4578 /// indicating the number of bytes that the subexpression is later shifted.  For
4579 /// example, if the expression is later right shifted by 16 bits, the
4580 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4581 /// byte of ByteValues is actually being set.
4582 ///
4583 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4584 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4585 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4586 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4587 /// always in the local (OverallLeftShift) coordinate space.
4588 ///
4589 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4590                               SmallVector<Value*, 8> &ByteValues) {
4591   if (Instruction *I = dyn_cast<Instruction>(V)) {
4592     // If this is an or instruction, it may be an inner node of the bswap.
4593     if (I->getOpcode() == Instruction::Or) {
4594       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4595                                ByteValues) ||
4596              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4597                                ByteValues);
4598     }
4599   
4600     // If this is a logical shift by a constant multiple of 8, recurse with
4601     // OverallLeftShift and ByteMask adjusted.
4602     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4603       unsigned ShAmt = 
4604         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4605       // Ensure the shift amount is defined and of a byte value.
4606       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4607         return true;
4608
4609       unsigned ByteShift = ShAmt >> 3;
4610       if (I->getOpcode() == Instruction::Shl) {
4611         // X << 2 -> collect(X, +2)
4612         OverallLeftShift += ByteShift;
4613         ByteMask >>= ByteShift;
4614       } else {
4615         // X >>u 2 -> collect(X, -2)
4616         OverallLeftShift -= ByteShift;
4617         ByteMask <<= ByteShift;
4618         ByteMask &= (~0U >> (32-ByteValues.size()));
4619       }
4620
4621       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4622       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4623
4624       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4625                                ByteValues);
4626     }
4627
4628     // If this is a logical 'and' with a mask that clears bytes, clear the
4629     // corresponding bytes in ByteMask.
4630     if (I->getOpcode() == Instruction::And &&
4631         isa<ConstantInt>(I->getOperand(1))) {
4632       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4633       unsigned NumBytes = ByteValues.size();
4634       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4635       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4636       
4637       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4638         // If this byte is masked out by a later operation, we don't care what
4639         // the and mask is.
4640         if ((ByteMask & (1 << i)) == 0)
4641           continue;
4642         
4643         // If the AndMask is all zeros for this byte, clear the bit.
4644         APInt MaskB = AndMask & Byte;
4645         if (MaskB == 0) {
4646           ByteMask &= ~(1U << i);
4647           continue;
4648         }
4649         
4650         // If the AndMask is not all ones for this byte, it's not a bytezap.
4651         if (MaskB != Byte)
4652           return true;
4653
4654         // Otherwise, this byte is kept.
4655       }
4656
4657       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4658                                ByteValues);
4659     }
4660   }
4661   
4662   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4663   // the input value to the bswap.  Some observations: 1) if more than one byte
4664   // is demanded from this input, then it could not be successfully assembled
4665   // into a byteswap.  At least one of the two bytes would not be aligned with
4666   // their ultimate destination.
4667   if (!isPowerOf2_32(ByteMask)) return true;
4668   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4669   
4670   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4671   // is demanded, it needs to go into byte 0 of the result.  This means that the
4672   // byte needs to be shifted until it lands in the right byte bucket.  The
4673   // shift amount depends on the position: if the byte is coming from the high
4674   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4675   // low part, it must be shifted left.
4676   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4677   if (InputByteNo < ByteValues.size()/2) {
4678     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4679       return true;
4680   } else {
4681     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4682       return true;
4683   }
4684   
4685   // If the destination byte value is already defined, the values are or'd
4686   // together, which isn't a bswap (unless it's an or of the same bits).
4687   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4688     return true;
4689   ByteValues[DestByteNo] = V;
4690   return false;
4691 }
4692
4693 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4694 /// If so, insert the new bswap intrinsic and return it.
4695 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4696   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4697   if (!ITy || ITy->getBitWidth() % 16 || 
4698       // ByteMask only allows up to 32-byte values.
4699       ITy->getBitWidth() > 32*8) 
4700     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4701   
4702   /// ByteValues - For each byte of the result, we keep track of which value
4703   /// defines each byte.
4704   SmallVector<Value*, 8> ByteValues;
4705   ByteValues.resize(ITy->getBitWidth()/8);
4706     
4707   // Try to find all the pieces corresponding to the bswap.
4708   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4709   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4710     return 0;
4711   
4712   // Check to see if all of the bytes come from the same value.
4713   Value *V = ByteValues[0];
4714   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4715   
4716   // Check to make sure that all of the bytes come from the same value.
4717   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4718     if (ByteValues[i] != V)
4719       return 0;
4720   const Type *Tys[] = { ITy };
4721   Module *M = I.getParent()->getParent()->getParent();
4722   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4723   return CallInst::Create(F, V);
4724 }
4725
4726 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4727 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4728 /// we can simplify this expression to "cond ? C : D or B".
4729 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4730                                          Value *C, Value *D,
4731                                          LLVMContext *Context) {
4732   // If A is not a select of -1/0, this cannot match.
4733   Value *Cond = 0;
4734   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4735     return 0;
4736
4737   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4738   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4739     return SelectInst::Create(Cond, C, B);
4740   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4741     return SelectInst::Create(Cond, C, B);
4742   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4743   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4744     return SelectInst::Create(Cond, C, D);
4745   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4746     return SelectInst::Create(Cond, C, D);
4747   return 0;
4748 }
4749
4750 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4751 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4752                                          ICmpInst *LHS, ICmpInst *RHS) {
4753   Value *Val, *Val2;
4754   ConstantInt *LHSCst, *RHSCst;
4755   ICmpInst::Predicate LHSCC, RHSCC;
4756   
4757   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4758   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4759              m_ConstantInt(LHSCst))) ||
4760       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4761              m_ConstantInt(RHSCst))))
4762     return 0;
4763   
4764   // From here on, we only handle:
4765   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4766   if (Val != Val2) return 0;
4767   
4768   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4769   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4770       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4771       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4772       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4773     return 0;
4774   
4775   // We can't fold (ugt x, C) | (sgt x, C2).
4776   if (!PredicatesFoldable(LHSCC, RHSCC))
4777     return 0;
4778   
4779   // Ensure that the larger constant is on the RHS.
4780   bool ShouldSwap;
4781   if (CmpInst::isSigned(LHSCC) ||
4782       (ICmpInst::isEquality(LHSCC) && 
4783        CmpInst::isSigned(RHSCC)))
4784     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4785   else
4786     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4787   
4788   if (ShouldSwap) {
4789     std::swap(LHS, RHS);
4790     std::swap(LHSCst, RHSCst);
4791     std::swap(LHSCC, RHSCC);
4792   }
4793   
4794   // At this point, we know we have have two icmp instructions
4795   // comparing a value against two constants and or'ing the result
4796   // together.  Because of the above check, we know that we only have
4797   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4798   // FoldICmpLogical check above), that the two constants are not
4799   // equal.
4800   assert(LHSCst != RHSCst && "Compares not folded above?");
4801
4802   switch (LHSCC) {
4803   default: llvm_unreachable("Unknown integer condition code!");
4804   case ICmpInst::ICMP_EQ:
4805     switch (RHSCC) {
4806     default: llvm_unreachable("Unknown integer condition code!");
4807     case ICmpInst::ICMP_EQ:
4808       if (LHSCst == SubOne(RHSCst)) {
4809         // (X == 13 | X == 14) -> X-13 <u 2
4810         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4811         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4812         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4813         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4814       }
4815       break;                         // (X == 13 | X == 15) -> no change
4816     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4817     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4818       break;
4819     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4820     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4821     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4822       return ReplaceInstUsesWith(I, RHS);
4823     }
4824     break;
4825   case ICmpInst::ICMP_NE:
4826     switch (RHSCC) {
4827     default: llvm_unreachable("Unknown integer condition code!");
4828     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4829     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4830     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4831       return ReplaceInstUsesWith(I, LHS);
4832     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4833     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4834     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4835       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4836     }
4837     break;
4838   case ICmpInst::ICMP_ULT:
4839     switch (RHSCC) {
4840     default: llvm_unreachable("Unknown integer condition code!");
4841     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4842       break;
4843     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4844       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4845       // this can cause overflow.
4846       if (RHSCst->isMaxValue(false))
4847         return ReplaceInstUsesWith(I, LHS);
4848       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4849                              false, false, I);
4850     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4851       break;
4852     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4853     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4854       return ReplaceInstUsesWith(I, RHS);
4855     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4856       break;
4857     }
4858     break;
4859   case ICmpInst::ICMP_SLT:
4860     switch (RHSCC) {
4861     default: llvm_unreachable("Unknown integer condition code!");
4862     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4863       break;
4864     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4865       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4866       // this can cause overflow.
4867       if (RHSCst->isMaxValue(true))
4868         return ReplaceInstUsesWith(I, LHS);
4869       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4870                              true, false, I);
4871     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4872       break;
4873     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4874     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4875       return ReplaceInstUsesWith(I, RHS);
4876     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4877       break;
4878     }
4879     break;
4880   case ICmpInst::ICMP_UGT:
4881     switch (RHSCC) {
4882     default: llvm_unreachable("Unknown integer condition code!");
4883     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4884     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4885       return ReplaceInstUsesWith(I, LHS);
4886     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4887       break;
4888     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4889     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4890       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4891     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4892       break;
4893     }
4894     break;
4895   case ICmpInst::ICMP_SGT:
4896     switch (RHSCC) {
4897     default: llvm_unreachable("Unknown integer condition code!");
4898     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4899     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4900       return ReplaceInstUsesWith(I, LHS);
4901     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4902       break;
4903     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4904     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4905       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4906     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4907       break;
4908     }
4909     break;
4910   }
4911   return 0;
4912 }
4913
4914 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4915                                          FCmpInst *RHS) {
4916   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4917       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4918       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4919     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4920       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4921         // If either of the constants are nans, then the whole thing returns
4922         // true.
4923         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4924           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4925         
4926         // Otherwise, no need to compare the two constants, compare the
4927         // rest.
4928         return new FCmpInst(FCmpInst::FCMP_UNO,
4929                             LHS->getOperand(0), RHS->getOperand(0));
4930       }
4931     
4932     // Handle vector zeros.  This occurs because the canonical form of
4933     // "fcmp uno x,x" is "fcmp uno x, 0".
4934     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4935         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4936       return new FCmpInst(FCmpInst::FCMP_UNO,
4937                           LHS->getOperand(0), RHS->getOperand(0));
4938     
4939     return 0;
4940   }
4941   
4942   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4943   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4944   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4945   
4946   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4947     // Swap RHS operands to match LHS.
4948     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4949     std::swap(Op1LHS, Op1RHS);
4950   }
4951   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4952     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4953     if (Op0CC == Op1CC)
4954       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4955                           Op0LHS, Op0RHS);
4956     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4957       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4958     if (Op0CC == FCmpInst::FCMP_FALSE)
4959       return ReplaceInstUsesWith(I, RHS);
4960     if (Op1CC == FCmpInst::FCMP_FALSE)
4961       return ReplaceInstUsesWith(I, LHS);
4962     bool Op0Ordered;
4963     bool Op1Ordered;
4964     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4965     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4966     if (Op0Ordered == Op1Ordered) {
4967       // If both are ordered or unordered, return a new fcmp with
4968       // or'ed predicates.
4969       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4970                                Op0LHS, Op0RHS, Context);
4971       if (Instruction *I = dyn_cast<Instruction>(RV))
4972         return I;
4973       // Otherwise, it's a constant boolean value...
4974       return ReplaceInstUsesWith(I, RV);
4975     }
4976   }
4977   return 0;
4978 }
4979
4980 /// FoldOrWithConstants - This helper function folds:
4981 ///
4982 ///     ((A | B) & C1) | (B & C2)
4983 ///
4984 /// into:
4985 /// 
4986 ///     (A & C1) | B
4987 ///
4988 /// when the XOR of the two constants is "all ones" (-1).
4989 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4990                                                Value *A, Value *B, Value *C) {
4991   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4992   if (!CI1) return 0;
4993
4994   Value *V1 = 0;
4995   ConstantInt *CI2 = 0;
4996   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4997
4998   APInt Xor = CI1->getValue() ^ CI2->getValue();
4999   if (!Xor.isAllOnesValue()) return 0;
5000
5001   if (V1 == A || V1 == B) {
5002     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
5003     return BinaryOperator::CreateOr(NewOp, V1);
5004   }
5005
5006   return 0;
5007 }
5008
5009 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
5010   bool Changed = SimplifyCommutative(I);
5011   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5012
5013   if (isa<UndefValue>(Op1))                       // X | undef -> -1
5014     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5015
5016   // or X, X = X
5017   if (Op0 == Op1)
5018     return ReplaceInstUsesWith(I, Op0);
5019
5020   // See if we can simplify any instructions used by the instruction whose sole 
5021   // purpose is to compute bits we don't care about.
5022   if (SimplifyDemandedInstructionBits(I))
5023     return &I;
5024   if (isa<VectorType>(I.getType())) {
5025     if (isa<ConstantAggregateZero>(Op1)) {
5026       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
5027     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
5028       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
5029         return ReplaceInstUsesWith(I, I.getOperand(1));
5030     }
5031   }
5032
5033   // or X, -1 == -1
5034   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5035     ConstantInt *C1 = 0; Value *X = 0;
5036     // (X & C1) | C2 --> (X | C2) & (C1|C2)
5037     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
5038         isOnlyUse(Op0)) {
5039       Value *Or = Builder->CreateOr(X, RHS);
5040       Or->takeName(Op0);
5041       return BinaryOperator::CreateAnd(Or, 
5042                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
5043     }
5044
5045     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
5046     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
5047         isOnlyUse(Op0)) {
5048       Value *Or = Builder->CreateOr(X, RHS);
5049       Or->takeName(Op0);
5050       return BinaryOperator::CreateXor(Or,
5051                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
5052     }
5053
5054     // Try to fold constant and into select arguments.
5055     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5056       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5057         return R;
5058     if (isa<PHINode>(Op0))
5059       if (Instruction *NV = FoldOpIntoPhi(I))
5060         return NV;
5061   }
5062
5063   Value *A = 0, *B = 0;
5064   ConstantInt *C1 = 0, *C2 = 0;
5065
5066   if (match(Op0, m_And(m_Value(A), m_Value(B))))
5067     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
5068       return ReplaceInstUsesWith(I, Op1);
5069   if (match(Op1, m_And(m_Value(A), m_Value(B))))
5070     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
5071       return ReplaceInstUsesWith(I, Op0);
5072
5073   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
5074   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
5075   if (match(Op0, m_Or(m_Value(), m_Value())) ||
5076       match(Op1, m_Or(m_Value(), m_Value())) ||
5077       (match(Op0, m_Shift(m_Value(), m_Value())) &&
5078        match(Op1, m_Shift(m_Value(), m_Value())))) {
5079     if (Instruction *BSwap = MatchBSwap(I))
5080       return BSwap;
5081   }
5082   
5083   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
5084   if (Op0->hasOneUse() &&
5085       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
5086       MaskedValueIsZero(Op1, C1->getValue())) {
5087     Value *NOr = Builder->CreateOr(A, Op1);
5088     NOr->takeName(Op0);
5089     return BinaryOperator::CreateXor(NOr, C1);
5090   }
5091
5092   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
5093   if (Op1->hasOneUse() &&
5094       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
5095       MaskedValueIsZero(Op0, C1->getValue())) {
5096     Value *NOr = Builder->CreateOr(A, Op0);
5097     NOr->takeName(Op0);
5098     return BinaryOperator::CreateXor(NOr, C1);
5099   }
5100
5101   // (A & C)|(B & D)
5102   Value *C = 0, *D = 0;
5103   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5104       match(Op1, m_And(m_Value(B), m_Value(D)))) {
5105     Value *V1 = 0, *V2 = 0, *V3 = 0;
5106     C1 = dyn_cast<ConstantInt>(C);
5107     C2 = dyn_cast<ConstantInt>(D);
5108     if (C1 && C2) {  // (A & C1)|(B & C2)
5109       // If we have: ((V + N) & C1) | (V & C2)
5110       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5111       // replace with V+N.
5112       if (C1->getValue() == ~C2->getValue()) {
5113         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
5114             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
5115           // Add commutes, try both ways.
5116           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5117             return ReplaceInstUsesWith(I, A);
5118           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5119             return ReplaceInstUsesWith(I, A);
5120         }
5121         // Or commutes, try both ways.
5122         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
5123             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
5124           // Add commutes, try both ways.
5125           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5126             return ReplaceInstUsesWith(I, B);
5127           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5128             return ReplaceInstUsesWith(I, B);
5129         }
5130       }
5131       V1 = 0; V2 = 0; V3 = 0;
5132     }
5133     
5134     // Check to see if we have any common things being and'ed.  If so, find the
5135     // terms for V1 & (V2|V3).
5136     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5137       if (A == B)      // (A & C)|(A & D) == A & (C|D)
5138         V1 = A, V2 = C, V3 = D;
5139       else if (A == D) // (A & C)|(B & A) == A & (B|C)
5140         V1 = A, V2 = B, V3 = C;
5141       else if (C == B) // (A & C)|(C & D) == C & (A|D)
5142         V1 = C, V2 = A, V3 = D;
5143       else if (C == D) // (A & C)|(B & C) == C & (A|B)
5144         V1 = C, V2 = A, V3 = B;
5145       
5146       if (V1) {
5147         Value *Or = Builder->CreateOr(V2, V3, "tmp");
5148         return BinaryOperator::CreateAnd(V1, Or);
5149       }
5150     }
5151
5152     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
5153     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
5154       return Match;
5155     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
5156       return Match;
5157     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
5158       return Match;
5159     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
5160       return Match;
5161
5162     // ((A&~B)|(~A&B)) -> A^B
5163     if ((match(C, m_Not(m_Specific(D))) &&
5164          match(B, m_Not(m_Specific(A)))))
5165       return BinaryOperator::CreateXor(A, D);
5166     // ((~B&A)|(~A&B)) -> A^B
5167     if ((match(A, m_Not(m_Specific(D))) &&
5168          match(B, m_Not(m_Specific(C)))))
5169       return BinaryOperator::CreateXor(C, D);
5170     // ((A&~B)|(B&~A)) -> A^B
5171     if ((match(C, m_Not(m_Specific(B))) &&
5172          match(D, m_Not(m_Specific(A)))))
5173       return BinaryOperator::CreateXor(A, B);
5174     // ((~B&A)|(B&~A)) -> A^B
5175     if ((match(A, m_Not(m_Specific(B))) &&
5176          match(D, m_Not(m_Specific(C)))))
5177       return BinaryOperator::CreateXor(C, B);
5178   }
5179   
5180   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
5181   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5182     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5183       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
5184           SI0->getOperand(1) == SI1->getOperand(1) &&
5185           (SI0->hasOneUse() || SI1->hasOneUse())) {
5186         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5187                                          SI0->getName());
5188         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
5189                                       SI1->getOperand(1));
5190       }
5191   }
5192
5193   // ((A|B)&1)|(B&-2) -> (A&1) | B
5194   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5195       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5196     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
5197     if (Ret) return Ret;
5198   }
5199   // (B&-2)|((A|B)&1) -> (A&1) | B
5200   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5201       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5202     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
5203     if (Ret) return Ret;
5204   }
5205
5206   if ((A = dyn_castNotVal(Op0))) {   // ~A | Op1
5207     if (A == Op1)   // ~A | A == -1
5208       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5209   } else {
5210     A = 0;
5211   }
5212   // Note, A is still live here!
5213   if ((B = dyn_castNotVal(Op1))) {   // Op0 | ~B
5214     if (Op0 == B)
5215       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5216
5217     // (~A | ~B) == (~(A & B)) - De Morgan's Law
5218     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
5219       Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
5220       return BinaryOperator::CreateNot(And);
5221     }
5222   }
5223
5224   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5225   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
5226     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5227       return R;
5228
5229     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5230       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5231         return Res;
5232   }
5233     
5234   // fold (or (cast A), (cast B)) -> (cast (or A, B))
5235   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5236     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5237       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
5238         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5239             !isa<ICmpInst>(Op1C->getOperand(0))) {
5240           const Type *SrcTy = Op0C->getOperand(0)->getType();
5241           if (SrcTy == Op1C->getOperand(0)->getType() &&
5242               SrcTy->isIntOrIntVector() &&
5243               // Only do this if the casts both really cause code to be
5244               // generated.
5245               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5246                                 I.getType(), TD) &&
5247               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5248                                 I.getType(), TD)) {
5249             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5250                                              Op1C->getOperand(0), I.getName());
5251             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5252           }
5253         }
5254       }
5255   }
5256   
5257     
5258   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
5259   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5260     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5261       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5262         return Res;
5263   }
5264
5265   return Changed ? &I : 0;
5266 }
5267
5268 namespace {
5269
5270 // XorSelf - Implements: X ^ X --> 0
5271 struct XorSelf {
5272   Value *RHS;
5273   XorSelf(Value *rhs) : RHS(rhs) {}
5274   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5275   Instruction *apply(BinaryOperator &Xor) const {
5276     return &Xor;
5277   }
5278 };
5279
5280 }
5281
5282 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5283   bool Changed = SimplifyCommutative(I);
5284   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5285
5286   if (isa<UndefValue>(Op1)) {
5287     if (isa<UndefValue>(Op0))
5288       // Handle undef ^ undef -> 0 special case. This is a common
5289       // idiom (misuse).
5290       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5291     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5292   }
5293
5294   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5295   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5296     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5297     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5298   }
5299   
5300   // See if we can simplify any instructions used by the instruction whose sole 
5301   // purpose is to compute bits we don't care about.
5302   if (SimplifyDemandedInstructionBits(I))
5303     return &I;
5304   if (isa<VectorType>(I.getType()))
5305     if (isa<ConstantAggregateZero>(Op1))
5306       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5307
5308   // Is this a ~ operation?
5309   if (Value *NotOp = dyn_castNotVal(&I)) {
5310     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5311       if (Op0I->getOpcode() == Instruction::And || 
5312           Op0I->getOpcode() == Instruction::Or) {
5313         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5314         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5315         if (dyn_castNotVal(Op0I->getOperand(1)))
5316           Op0I->swapOperands();
5317         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5318           Value *NotY =
5319             Builder->CreateNot(Op0I->getOperand(1),
5320                                Op0I->getOperand(1)->getName()+".not");
5321           if (Op0I->getOpcode() == Instruction::And)
5322             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5323           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5324         }
5325         
5326         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5327         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5328         if (isFreeToInvert(Op0I->getOperand(0)) && 
5329             isFreeToInvert(Op0I->getOperand(1))) {
5330           Value *NotX =
5331             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5332           Value *NotY =
5333             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5334           if (Op0I->getOpcode() == Instruction::And)
5335             return BinaryOperator::CreateOr(NotX, NotY);
5336           return BinaryOperator::CreateAnd(NotX, NotY);
5337         }
5338       }
5339     }
5340   }
5341   
5342   
5343   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5344     if (RHS->isOne() && Op0->hasOneUse()) {
5345       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5346       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5347         return new ICmpInst(ICI->getInversePredicate(),
5348                             ICI->getOperand(0), ICI->getOperand(1));
5349
5350       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5351         return new FCmpInst(FCI->getInversePredicate(),
5352                             FCI->getOperand(0), FCI->getOperand(1));
5353     }
5354
5355     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5356     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5357       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5358         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5359           Instruction::CastOps Opcode = Op0C->getOpcode();
5360           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5361               (RHS == ConstantExpr::getCast(Opcode, 
5362                                             ConstantInt::getTrue(*Context),
5363                                             Op0C->getDestTy()))) {
5364             CI->setPredicate(CI->getInversePredicate());
5365             return CastInst::Create(Opcode, CI, Op0C->getType());
5366           }
5367         }
5368       }
5369     }
5370
5371     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5372       // ~(c-X) == X-c-1 == X+(-c-1)
5373       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5374         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5375           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5376           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5377                                       ConstantInt::get(I.getType(), 1));
5378           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5379         }
5380           
5381       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5382         if (Op0I->getOpcode() == Instruction::Add) {
5383           // ~(X-c) --> (-c-1)-X
5384           if (RHS->isAllOnesValue()) {
5385             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5386             return BinaryOperator::CreateSub(
5387                            ConstantExpr::getSub(NegOp0CI,
5388                                       ConstantInt::get(I.getType(), 1)),
5389                                       Op0I->getOperand(0));
5390           } else if (RHS->getValue().isSignBit()) {
5391             // (X + C) ^ signbit -> (X + C + signbit)
5392             Constant *C = ConstantInt::get(*Context,
5393                                            RHS->getValue() + Op0CI->getValue());
5394             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5395
5396           }
5397         } else if (Op0I->getOpcode() == Instruction::Or) {
5398           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5399           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5400             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5401             // Anything in both C1 and C2 is known to be zero, remove it from
5402             // NewRHS.
5403             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5404             NewRHS = ConstantExpr::getAnd(NewRHS, 
5405                                        ConstantExpr::getNot(CommonBits));
5406             Worklist.Add(Op0I);
5407             I.setOperand(0, Op0I->getOperand(0));
5408             I.setOperand(1, NewRHS);
5409             return &I;
5410           }
5411         }
5412       }
5413     }
5414
5415     // Try to fold constant and into select arguments.
5416     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5417       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5418         return R;
5419     if (isa<PHINode>(Op0))
5420       if (Instruction *NV = FoldOpIntoPhi(I))
5421         return NV;
5422   }
5423
5424   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5425     if (X == Op1)
5426       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5427
5428   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5429     if (X == Op0)
5430       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5431
5432   
5433   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5434   if (Op1I) {
5435     Value *A, *B;
5436     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5437       if (A == Op0) {              // B^(B|A) == (A|B)^B
5438         Op1I->swapOperands();
5439         I.swapOperands();
5440         std::swap(Op0, Op1);
5441       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5442         I.swapOperands();     // Simplified below.
5443         std::swap(Op0, Op1);
5444       }
5445     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5446       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5447     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5448       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5449     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5450                Op1I->hasOneUse()){
5451       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5452         Op1I->swapOperands();
5453         std::swap(A, B);
5454       }
5455       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5456         I.swapOperands();     // Simplified below.
5457         std::swap(Op0, Op1);
5458       }
5459     }
5460   }
5461   
5462   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5463   if (Op0I) {
5464     Value *A, *B;
5465     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5466         Op0I->hasOneUse()) {
5467       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5468         std::swap(A, B);
5469       if (B == Op1)                                  // (A|B)^B == A & ~B
5470         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5471     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5472       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5473     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5474       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5475     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5476                Op0I->hasOneUse()){
5477       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5478         std::swap(A, B);
5479       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5480           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5481         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5482       }
5483     }
5484   }
5485   
5486   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5487   if (Op0I && Op1I && Op0I->isShift() && 
5488       Op0I->getOpcode() == Op1I->getOpcode() && 
5489       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5490       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5491     Value *NewOp =
5492       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5493                          Op0I->getName());
5494     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5495                                   Op1I->getOperand(1));
5496   }
5497     
5498   if (Op0I && Op1I) {
5499     Value *A, *B, *C, *D;
5500     // (A & B)^(A | B) -> A ^ B
5501     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5502         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5503       if ((A == C && B == D) || (A == D && B == C)) 
5504         return BinaryOperator::CreateXor(A, B);
5505     }
5506     // (A | B)^(A & B) -> A ^ B
5507     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5508         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5509       if ((A == C && B == D) || (A == D && B == C)) 
5510         return BinaryOperator::CreateXor(A, B);
5511     }
5512     
5513     // (A & B)^(C & D)
5514     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5515         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5516         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5517       // (X & Y)^(X & Y) -> (Y^Z) & X
5518       Value *X = 0, *Y = 0, *Z = 0;
5519       if (A == C)
5520         X = A, Y = B, Z = D;
5521       else if (A == D)
5522         X = A, Y = B, Z = C;
5523       else if (B == C)
5524         X = B, Y = A, Z = D;
5525       else if (B == D)
5526         X = B, Y = A, Z = C;
5527       
5528       if (X) {
5529         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5530         return BinaryOperator::CreateAnd(NewOp, X);
5531       }
5532     }
5533   }
5534     
5535   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5536   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5537     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5538       return R;
5539
5540   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5541   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5542     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5543       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5544         const Type *SrcTy = Op0C->getOperand(0)->getType();
5545         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5546             // Only do this if the casts both really cause code to be generated.
5547             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5548                               I.getType(), TD) &&
5549             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5550                               I.getType(), TD)) {
5551           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5552                                             Op1C->getOperand(0), I.getName());
5553           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5554         }
5555       }
5556   }
5557
5558   return Changed ? &I : 0;
5559 }
5560
5561 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5562                                    LLVMContext *Context) {
5563   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5564 }
5565
5566 static bool HasAddOverflow(ConstantInt *Result,
5567                            ConstantInt *In1, ConstantInt *In2,
5568                            bool IsSigned) {
5569   if (IsSigned)
5570     if (In2->getValue().isNegative())
5571       return Result->getValue().sgt(In1->getValue());
5572     else
5573       return Result->getValue().slt(In1->getValue());
5574   else
5575     return Result->getValue().ult(In1->getValue());
5576 }
5577
5578 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5579 /// overflowed for this type.
5580 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5581                             Constant *In2, LLVMContext *Context,
5582                             bool IsSigned = false) {
5583   Result = ConstantExpr::getAdd(In1, In2);
5584
5585   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5586     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5587       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5588       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5589                          ExtractElement(In1, Idx, Context),
5590                          ExtractElement(In2, Idx, Context),
5591                          IsSigned))
5592         return true;
5593     }
5594     return false;
5595   }
5596
5597   return HasAddOverflow(cast<ConstantInt>(Result),
5598                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5599                         IsSigned);
5600 }
5601
5602 static bool HasSubOverflow(ConstantInt *Result,
5603                            ConstantInt *In1, ConstantInt *In2,
5604                            bool IsSigned) {
5605   if (IsSigned)
5606     if (In2->getValue().isNegative())
5607       return Result->getValue().slt(In1->getValue());
5608     else
5609       return Result->getValue().sgt(In1->getValue());
5610   else
5611     return Result->getValue().ugt(In1->getValue());
5612 }
5613
5614 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5615 /// overflowed for this type.
5616 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5617                             Constant *In2, LLVMContext *Context,
5618                             bool IsSigned = false) {
5619   Result = ConstantExpr::getSub(In1, In2);
5620
5621   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5622     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5623       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5624       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5625                          ExtractElement(In1, Idx, Context),
5626                          ExtractElement(In2, Idx, Context),
5627                          IsSigned))
5628         return true;
5629     }
5630     return false;
5631   }
5632
5633   return HasSubOverflow(cast<ConstantInt>(Result),
5634                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5635                         IsSigned);
5636 }
5637
5638
5639 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5640 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5641 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5642                                        ICmpInst::Predicate Cond,
5643                                        Instruction &I) {
5644   // Look through bitcasts.
5645   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5646     RHS = BCI->getOperand(0);
5647
5648   Value *PtrBase = GEPLHS->getOperand(0);
5649   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5650     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5651     // This transformation (ignoring the base and scales) is valid because we
5652     // know pointers can't overflow since the gep is inbounds.  See if we can
5653     // output an optimized form.
5654     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5655     
5656     // If not, synthesize the offset the hard way.
5657     if (Offset == 0)
5658       Offset = EmitGEPOffset(GEPLHS, *this);
5659     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5660                         Constant::getNullValue(Offset->getType()));
5661   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5662     // If the base pointers are different, but the indices are the same, just
5663     // compare the base pointer.
5664     if (PtrBase != GEPRHS->getOperand(0)) {
5665       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5666       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5667                         GEPRHS->getOperand(0)->getType();
5668       if (IndicesTheSame)
5669         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5670           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5671             IndicesTheSame = false;
5672             break;
5673           }
5674
5675       // If all indices are the same, just compare the base pointers.
5676       if (IndicesTheSame)
5677         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5678                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5679
5680       // Otherwise, the base pointers are different and the indices are
5681       // different, bail out.
5682       return 0;
5683     }
5684
5685     // If one of the GEPs has all zero indices, recurse.
5686     bool AllZeros = true;
5687     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5688       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5689           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5690         AllZeros = false;
5691         break;
5692       }
5693     if (AllZeros)
5694       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5695                           ICmpInst::getSwappedPredicate(Cond), I);
5696
5697     // If the other GEP has all zero indices, recurse.
5698     AllZeros = true;
5699     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5700       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5701           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5702         AllZeros = false;
5703         break;
5704       }
5705     if (AllZeros)
5706       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5707
5708     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5709       // If the GEPs only differ by one index, compare it.
5710       unsigned NumDifferences = 0;  // Keep track of # differences.
5711       unsigned DiffOperand = 0;     // The operand that differs.
5712       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5713         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5714           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5715                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5716             // Irreconcilable differences.
5717             NumDifferences = 2;
5718             break;
5719           } else {
5720             if (NumDifferences++) break;
5721             DiffOperand = i;
5722           }
5723         }
5724
5725       if (NumDifferences == 0)   // SAME GEP?
5726         return ReplaceInstUsesWith(I, // No comparison is needed here.
5727                                    ConstantInt::get(Type::getInt1Ty(*Context),
5728                                              ICmpInst::isTrueWhenEqual(Cond)));
5729
5730       else if (NumDifferences == 1) {
5731         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5732         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5733         // Make sure we do a signed comparison here.
5734         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5735       }
5736     }
5737
5738     // Only lower this if the icmp is the only user of the GEP or if we expect
5739     // the result to fold to a constant!
5740     if (TD &&
5741         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5742         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5743       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5744       Value *L = EmitGEPOffset(GEPLHS, *this);
5745       Value *R = EmitGEPOffset(GEPRHS, *this);
5746       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5747     }
5748   }
5749   return 0;
5750 }
5751
5752 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5753 ///
5754 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5755                                                 Instruction *LHSI,
5756                                                 Constant *RHSC) {
5757   if (!isa<ConstantFP>(RHSC)) return 0;
5758   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5759   
5760   // Get the width of the mantissa.  We don't want to hack on conversions that
5761   // might lose information from the integer, e.g. "i64 -> float"
5762   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5763   if (MantissaWidth == -1) return 0;  // Unknown.
5764   
5765   // Check to see that the input is converted from an integer type that is small
5766   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5767   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5768   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5769   
5770   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5771   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5772   if (LHSUnsigned)
5773     ++InputSize;
5774   
5775   // If the conversion would lose info, don't hack on this.
5776   if ((int)InputSize > MantissaWidth)
5777     return 0;
5778   
5779   // Otherwise, we can potentially simplify the comparison.  We know that it
5780   // will always come through as an integer value and we know the constant is
5781   // not a NAN (it would have been previously simplified).
5782   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5783   
5784   ICmpInst::Predicate Pred;
5785   switch (I.getPredicate()) {
5786   default: llvm_unreachable("Unexpected predicate!");
5787   case FCmpInst::FCMP_UEQ:
5788   case FCmpInst::FCMP_OEQ:
5789     Pred = ICmpInst::ICMP_EQ;
5790     break;
5791   case FCmpInst::FCMP_UGT:
5792   case FCmpInst::FCMP_OGT:
5793     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5794     break;
5795   case FCmpInst::FCMP_UGE:
5796   case FCmpInst::FCMP_OGE:
5797     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5798     break;
5799   case FCmpInst::FCMP_ULT:
5800   case FCmpInst::FCMP_OLT:
5801     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5802     break;
5803   case FCmpInst::FCMP_ULE:
5804   case FCmpInst::FCMP_OLE:
5805     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5806     break;
5807   case FCmpInst::FCMP_UNE:
5808   case FCmpInst::FCMP_ONE:
5809     Pred = ICmpInst::ICMP_NE;
5810     break;
5811   case FCmpInst::FCMP_ORD:
5812     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5813   case FCmpInst::FCMP_UNO:
5814     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5815   }
5816   
5817   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5818   
5819   // Now we know that the APFloat is a normal number, zero or inf.
5820   
5821   // See if the FP constant is too large for the integer.  For example,
5822   // comparing an i8 to 300.0.
5823   unsigned IntWidth = IntTy->getScalarSizeInBits();
5824   
5825   if (!LHSUnsigned) {
5826     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5827     // and large values.
5828     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5829     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5830                           APFloat::rmNearestTiesToEven);
5831     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5832       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5833           Pred == ICmpInst::ICMP_SLE)
5834         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5835       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5836     }
5837   } else {
5838     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5839     // +INF and large values.
5840     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5841     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5842                           APFloat::rmNearestTiesToEven);
5843     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5844       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5845           Pred == ICmpInst::ICMP_ULE)
5846         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5847       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5848     }
5849   }
5850   
5851   if (!LHSUnsigned) {
5852     // See if the RHS value is < SignedMin.
5853     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5854     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5855                           APFloat::rmNearestTiesToEven);
5856     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5857       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5858           Pred == ICmpInst::ICMP_SGE)
5859         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5860       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5861     }
5862   }
5863
5864   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5865   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5866   // casting the FP value to the integer value and back, checking for equality.
5867   // Don't do this for zero, because -0.0 is not fractional.
5868   Constant *RHSInt = LHSUnsigned
5869     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5870     : ConstantExpr::getFPToSI(RHSC, IntTy);
5871   if (!RHS.isZero()) {
5872     bool Equal = LHSUnsigned
5873       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5874       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5875     if (!Equal) {
5876       // If we had a comparison against a fractional value, we have to adjust
5877       // the compare predicate and sometimes the value.  RHSC is rounded towards
5878       // zero at this point.
5879       switch (Pred) {
5880       default: llvm_unreachable("Unexpected integer comparison!");
5881       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5882         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5883       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5884         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5885       case ICmpInst::ICMP_ULE:
5886         // (float)int <= 4.4   --> int <= 4
5887         // (float)int <= -4.4  --> false
5888         if (RHS.isNegative())
5889           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5890         break;
5891       case ICmpInst::ICMP_SLE:
5892         // (float)int <= 4.4   --> int <= 4
5893         // (float)int <= -4.4  --> int < -4
5894         if (RHS.isNegative())
5895           Pred = ICmpInst::ICMP_SLT;
5896         break;
5897       case ICmpInst::ICMP_ULT:
5898         // (float)int < -4.4   --> false
5899         // (float)int < 4.4    --> int <= 4
5900         if (RHS.isNegative())
5901           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5902         Pred = ICmpInst::ICMP_ULE;
5903         break;
5904       case ICmpInst::ICMP_SLT:
5905         // (float)int < -4.4   --> int < -4
5906         // (float)int < 4.4    --> int <= 4
5907         if (!RHS.isNegative())
5908           Pred = ICmpInst::ICMP_SLE;
5909         break;
5910       case ICmpInst::ICMP_UGT:
5911         // (float)int > 4.4    --> int > 4
5912         // (float)int > -4.4   --> true
5913         if (RHS.isNegative())
5914           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5915         break;
5916       case ICmpInst::ICMP_SGT:
5917         // (float)int > 4.4    --> int > 4
5918         // (float)int > -4.4   --> int >= -4
5919         if (RHS.isNegative())
5920           Pred = ICmpInst::ICMP_SGE;
5921         break;
5922       case ICmpInst::ICMP_UGE:
5923         // (float)int >= -4.4   --> true
5924         // (float)int >= 4.4    --> int > 4
5925         if (!RHS.isNegative())
5926           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5927         Pred = ICmpInst::ICMP_UGT;
5928         break;
5929       case ICmpInst::ICMP_SGE:
5930         // (float)int >= -4.4   --> int >= -4
5931         // (float)int >= 4.4    --> int > 4
5932         if (!RHS.isNegative())
5933           Pred = ICmpInst::ICMP_SGT;
5934         break;
5935       }
5936     }
5937   }
5938
5939   // Lower this FP comparison into an appropriate integer version of the
5940   // comparison.
5941   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5942 }
5943
5944 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5945   bool Changed = SimplifyCompare(I);
5946   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5947
5948   // Fold trivial predicates.
5949   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5950     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5951   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5952     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5953   
5954   // Simplify 'fcmp pred X, X'
5955   if (Op0 == Op1) {
5956     switch (I.getPredicate()) {
5957     default: llvm_unreachable("Unknown predicate!");
5958     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5959     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5960     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5961       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5962     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5963     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5964     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5965       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5966       
5967     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5968     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5969     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5970     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5971       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5972       I.setPredicate(FCmpInst::FCMP_UNO);
5973       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5974       return &I;
5975       
5976     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5977     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5978     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5979     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5980       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5981       I.setPredicate(FCmpInst::FCMP_ORD);
5982       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5983       return &I;
5984     }
5985   }
5986     
5987   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5988     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5989
5990   // Handle fcmp with constant RHS
5991   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5992     // If the constant is a nan, see if we can fold the comparison based on it.
5993     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5994       if (CFP->getValueAPF().isNaN()) {
5995         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5996           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5997         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5998                "Comparison must be either ordered or unordered!");
5999         // True if unordered.
6000         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6001       }
6002     }
6003     
6004     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6005       switch (LHSI->getOpcode()) {
6006       case Instruction::PHI:
6007         // Only fold fcmp into the PHI if the phi and fcmp are in the same
6008         // block.  If in the same block, we're encouraging jump threading.  If
6009         // not, we are just pessimizing the code by making an i1 phi.
6010         if (LHSI->getParent() == I.getParent())
6011           if (Instruction *NV = FoldOpIntoPhi(I, true))
6012             return NV;
6013         break;
6014       case Instruction::SIToFP:
6015       case Instruction::UIToFP:
6016         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6017           return NV;
6018         break;
6019       case Instruction::Select:
6020         // If either operand of the select is a constant, we can fold the
6021         // comparison into the select arms, which will cause one to be
6022         // constant folded and the select turned into a bitwise or.
6023         Value *Op1 = 0, *Op2 = 0;
6024         if (LHSI->hasOneUse()) {
6025           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6026             // Fold the known value into the constant operand.
6027             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
6028             // Insert a new FCmp of the other select operand.
6029             Op2 = Builder->CreateFCmp(I.getPredicate(),
6030                                       LHSI->getOperand(2), RHSC, I.getName());
6031           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6032             // Fold the known value into the constant operand.
6033             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
6034             // Insert a new FCmp of the other select operand.
6035             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6036                                       RHSC, I.getName());
6037           }
6038         }
6039
6040         if (Op1)
6041           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6042         break;
6043       }
6044   }
6045
6046   return Changed ? &I : 0;
6047 }
6048
6049 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
6050   bool Changed = SimplifyCompare(I);
6051   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6052   const Type *Ty = Op0->getType();
6053
6054   // icmp X, X
6055   if (Op0 == Op1)
6056     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
6057                                                    I.isTrueWhenEqual()));
6058
6059   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
6060     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
6061   
6062   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
6063   // addresses never equal each other!  We already know that Op0 != Op1.
6064   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) || 
6065        isa<ConstantPointerNull>(Op0)) &&
6066       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) || 
6067        isa<ConstantPointerNull>(Op1)))
6068     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
6069                                                    !I.isTrueWhenEqual()));
6070
6071   // icmp's with boolean values can always be turned into bitwise operations
6072   if (Ty == Type::getInt1Ty(*Context)) {
6073     switch (I.getPredicate()) {
6074     default: llvm_unreachable("Invalid icmp instruction!");
6075     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6076       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
6077       return BinaryOperator::CreateNot(Xor);
6078     }
6079     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6080       return BinaryOperator::CreateXor(Op0, Op1);
6081
6082     case ICmpInst::ICMP_UGT:
6083       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6084       // FALL THROUGH
6085     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6086       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6087       return BinaryOperator::CreateAnd(Not, Op1);
6088     }
6089     case ICmpInst::ICMP_SGT:
6090       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6091       // FALL THROUGH
6092     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6093       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6094       return BinaryOperator::CreateAnd(Not, Op0);
6095     }
6096     case ICmpInst::ICMP_UGE:
6097       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6098       // FALL THROUGH
6099     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6100       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6101       return BinaryOperator::CreateOr(Not, Op1);
6102     }
6103     case ICmpInst::ICMP_SGE:
6104       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6105       // FALL THROUGH
6106     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6107       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6108       return BinaryOperator::CreateOr(Not, Op0);
6109     }
6110     }
6111   }
6112
6113   unsigned BitWidth = 0;
6114   if (TD)
6115     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6116   else if (Ty->isIntOrIntVector())
6117     BitWidth = Ty->getScalarSizeInBits();
6118
6119   bool isSignBit = false;
6120
6121   // See if we are doing a comparison with a constant.
6122   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6123     Value *A = 0, *B = 0;
6124     
6125     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6126     if (I.isEquality() && CI->isNullValue() &&
6127         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6128       // (icmp cond A B) if cond is equality
6129       return new ICmpInst(I.getPredicate(), A, B);
6130     }
6131     
6132     // If we have an icmp le or icmp ge instruction, turn it into the
6133     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6134     // them being folded in the code below.
6135     switch (I.getPredicate()) {
6136     default: break;
6137     case ICmpInst::ICMP_ULE:
6138       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6139         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6140       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6141                           AddOne(CI));
6142     case ICmpInst::ICMP_SLE:
6143       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6144         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6145       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6146                           AddOne(CI));
6147     case ICmpInst::ICMP_UGE:
6148       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6149         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6150       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6151                           SubOne(CI));
6152     case ICmpInst::ICMP_SGE:
6153       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6154         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6155       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6156                           SubOne(CI));
6157     }
6158     
6159     // If this comparison is a normal comparison, it demands all
6160     // bits, if it is a sign bit comparison, it only demands the sign bit.
6161     bool UnusedBit;
6162     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6163   }
6164
6165   // See if we can fold the comparison based on range information we can get
6166   // by checking whether bits are known to be zero or one in the input.
6167   if (BitWidth != 0) {
6168     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6169     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6170
6171     if (SimplifyDemandedBits(I.getOperandUse(0),
6172                              isSignBit ? APInt::getSignBit(BitWidth)
6173                                        : APInt::getAllOnesValue(BitWidth),
6174                              Op0KnownZero, Op0KnownOne, 0))
6175       return &I;
6176     if (SimplifyDemandedBits(I.getOperandUse(1),
6177                              APInt::getAllOnesValue(BitWidth),
6178                              Op1KnownZero, Op1KnownOne, 0))
6179       return &I;
6180
6181     // Given the known and unknown bits, compute a range that the LHS could be
6182     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6183     // EQ and NE we use unsigned values.
6184     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6185     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6186     if (I.isSigned()) {
6187       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6188                                              Op0Min, Op0Max);
6189       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6190                                              Op1Min, Op1Max);
6191     } else {
6192       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6193                                                Op0Min, Op0Max);
6194       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6195                                                Op1Min, Op1Max);
6196     }
6197
6198     // If Min and Max are known to be the same, then SimplifyDemandedBits
6199     // figured out that the LHS is a constant.  Just constant fold this now so
6200     // that code below can assume that Min != Max.
6201     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6202       return new ICmpInst(I.getPredicate(),
6203                           ConstantInt::get(*Context, Op0Min), Op1);
6204     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6205       return new ICmpInst(I.getPredicate(), Op0,
6206                           ConstantInt::get(*Context, Op1Min));
6207
6208     // Based on the range information we know about the LHS, see if we can
6209     // simplify this comparison.  For example, (x&4) < 8  is always true.
6210     switch (I.getPredicate()) {
6211     default: llvm_unreachable("Unknown icmp opcode!");
6212     case ICmpInst::ICMP_EQ:
6213       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6214         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6215       break;
6216     case ICmpInst::ICMP_NE:
6217       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6218         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6219       break;
6220     case ICmpInst::ICMP_ULT:
6221       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6222         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6223       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6224         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6225       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6226         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6227       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6228         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6229           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6230                               SubOne(CI));
6231
6232         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6233         if (CI->isMinValue(true))
6234           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6235                            Constant::getAllOnesValue(Op0->getType()));
6236       }
6237       break;
6238     case ICmpInst::ICMP_UGT:
6239       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6240         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6241       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6242         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6243
6244       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6245         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6246       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6247         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6248           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6249                               AddOne(CI));
6250
6251         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6252         if (CI->isMaxValue(true))
6253           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6254                               Constant::getNullValue(Op0->getType()));
6255       }
6256       break;
6257     case ICmpInst::ICMP_SLT:
6258       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6259         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6260       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6261         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6262       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6263         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6264       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6265         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6266           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6267                               SubOne(CI));
6268       }
6269       break;
6270     case ICmpInst::ICMP_SGT:
6271       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6272         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6273       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6274         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6275
6276       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6277         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6278       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6279         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6280           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6281                               AddOne(CI));
6282       }
6283       break;
6284     case ICmpInst::ICMP_SGE:
6285       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6286       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6287         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6288       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6289         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6290       break;
6291     case ICmpInst::ICMP_SLE:
6292       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6293       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6294         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6295       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6296         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6297       break;
6298     case ICmpInst::ICMP_UGE:
6299       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6300       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6301         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6302       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6303         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6304       break;
6305     case ICmpInst::ICMP_ULE:
6306       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6307       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6308         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6309       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6310         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6311       break;
6312     }
6313
6314     // Turn a signed comparison into an unsigned one if both operands
6315     // are known to have the same sign.
6316     if (I.isSigned() &&
6317         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6318          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6319       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6320   }
6321
6322   // Test if the ICmpInst instruction is used exclusively by a select as
6323   // part of a minimum or maximum operation. If so, refrain from doing
6324   // any other folding. This helps out other analyses which understand
6325   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6326   // and CodeGen. And in this case, at least one of the comparison
6327   // operands has at least one user besides the compare (the select),
6328   // which would often largely negate the benefit of folding anyway.
6329   if (I.hasOneUse())
6330     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6331       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6332           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6333         return 0;
6334
6335   // See if we are doing a comparison between a constant and an instruction that
6336   // can be folded into the comparison.
6337   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6338     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6339     // instruction, see if that instruction also has constants so that the 
6340     // instruction can be folded into the icmp 
6341     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6342       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6343         return Res;
6344   }
6345
6346   // Handle icmp with constant (but not simple integer constant) RHS
6347   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6348     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6349       switch (LHSI->getOpcode()) {
6350       case Instruction::GetElementPtr:
6351         if (RHSC->isNullValue()) {
6352           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6353           bool isAllZeros = true;
6354           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6355             if (!isa<Constant>(LHSI->getOperand(i)) ||
6356                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6357               isAllZeros = false;
6358               break;
6359             }
6360           if (isAllZeros)
6361             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6362                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6363         }
6364         break;
6365
6366       case Instruction::PHI:
6367         // Only fold icmp into the PHI if the phi and icmp are in the same
6368         // block.  If in the same block, we're encouraging jump threading.  If
6369         // not, we are just pessimizing the code by making an i1 phi.
6370         if (LHSI->getParent() == I.getParent())
6371           if (Instruction *NV = FoldOpIntoPhi(I, true))
6372             return NV;
6373         break;
6374       case Instruction::Select: {
6375         // If either operand of the select is a constant, we can fold the
6376         // comparison into the select arms, which will cause one to be
6377         // constant folded and the select turned into a bitwise or.
6378         Value *Op1 = 0, *Op2 = 0;
6379         if (LHSI->hasOneUse()) {
6380           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6381             // Fold the known value into the constant operand.
6382             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6383             // Insert a new ICmp of the other select operand.
6384             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6385                                       RHSC, I.getName());
6386           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6387             // Fold the known value into the constant operand.
6388             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6389             // Insert a new ICmp of the other select operand.
6390             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6391                                       RHSC, I.getName());
6392           }
6393         }
6394
6395         if (Op1)
6396           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6397         break;
6398       }
6399       case Instruction::Call:
6400         // If we have (malloc != null), and if the malloc has a single use, we
6401         // can assume it is successful and remove the malloc.
6402         if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6403             isa<ConstantPointerNull>(RHSC)) {
6404           // Need to explicitly erase malloc call here, instead of adding it to
6405           // Worklist, because it won't get DCE'd from the Worklist since
6406           // isInstructionTriviallyDead() returns false for function calls.
6407           // It is OK to replace LHSI/MallocCall with Undef because the 
6408           // instruction that uses it will be erased via Worklist.
6409           if (extractMallocCall(LHSI)) {
6410             LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6411             EraseInstFromFunction(*LHSI);
6412             return ReplaceInstUsesWith(I,
6413                                      ConstantInt::get(Type::getInt1Ty(*Context),
6414                                                       !I.isTrueWhenEqual()));
6415           }
6416           if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6417             if (MallocCall->hasOneUse()) {
6418               MallocCall->replaceAllUsesWith(
6419                                         UndefValue::get(MallocCall->getType()));
6420               EraseInstFromFunction(*MallocCall);
6421               Worklist.Add(LHSI); // The malloc's bitcast use.
6422               return ReplaceInstUsesWith(I,
6423                                      ConstantInt::get(Type::getInt1Ty(*Context),
6424                                                       !I.isTrueWhenEqual()));
6425             }
6426         }
6427         break;
6428       }
6429   }
6430
6431   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6432   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6433     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6434       return NI;
6435   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6436     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6437                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6438       return NI;
6439
6440   // Test to see if the operands of the icmp are casted versions of other
6441   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6442   // now.
6443   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6444     if (isa<PointerType>(Op0->getType()) && 
6445         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6446       // We keep moving the cast from the left operand over to the right
6447       // operand, where it can often be eliminated completely.
6448       Op0 = CI->getOperand(0);
6449
6450       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6451       // so eliminate it as well.
6452       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6453         Op1 = CI2->getOperand(0);
6454
6455       // If Op1 is a constant, we can fold the cast into the constant.
6456       if (Op0->getType() != Op1->getType()) {
6457         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6458           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6459         } else {
6460           // Otherwise, cast the RHS right before the icmp
6461           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6462         }
6463       }
6464       return new ICmpInst(I.getPredicate(), Op0, Op1);
6465     }
6466   }
6467   
6468   if (isa<CastInst>(Op0)) {
6469     // Handle the special case of: icmp (cast bool to X), <cst>
6470     // This comes up when you have code like
6471     //   int X = A < B;
6472     //   if (X) ...
6473     // For generality, we handle any zero-extension of any operand comparison
6474     // with a constant or another cast from the same type.
6475     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6476       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6477         return R;
6478   }
6479   
6480   // See if it's the same type of instruction on the left and right.
6481   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6482     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6483       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6484           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6485         switch (Op0I->getOpcode()) {
6486         default: break;
6487         case Instruction::Add:
6488         case Instruction::Sub:
6489         case Instruction::Xor:
6490           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6491             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6492                                 Op1I->getOperand(0));
6493           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6494           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6495             if (CI->getValue().isSignBit()) {
6496               ICmpInst::Predicate Pred = I.isSigned()
6497                                              ? I.getUnsignedPredicate()
6498                                              : I.getSignedPredicate();
6499               return new ICmpInst(Pred, Op0I->getOperand(0),
6500                                   Op1I->getOperand(0));
6501             }
6502             
6503             if (CI->getValue().isMaxSignedValue()) {
6504               ICmpInst::Predicate Pred = I.isSigned()
6505                                              ? I.getUnsignedPredicate()
6506                                              : I.getSignedPredicate();
6507               Pred = I.getSwappedPredicate(Pred);
6508               return new ICmpInst(Pred, Op0I->getOperand(0),
6509                                   Op1I->getOperand(0));
6510             }
6511           }
6512           break;
6513         case Instruction::Mul:
6514           if (!I.isEquality())
6515             break;
6516
6517           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6518             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6519             // Mask = -1 >> count-trailing-zeros(Cst).
6520             if (!CI->isZero() && !CI->isOne()) {
6521               const APInt &AP = CI->getValue();
6522               ConstantInt *Mask = ConstantInt::get(*Context, 
6523                                       APInt::getLowBitsSet(AP.getBitWidth(),
6524                                                            AP.getBitWidth() -
6525                                                       AP.countTrailingZeros()));
6526               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6527               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6528               return new ICmpInst(I.getPredicate(), And1, And2);
6529             }
6530           }
6531           break;
6532         }
6533       }
6534     }
6535   }
6536   
6537   // ~x < ~y --> y < x
6538   { Value *A, *B;
6539     if (match(Op0, m_Not(m_Value(A))) &&
6540         match(Op1, m_Not(m_Value(B))))
6541       return new ICmpInst(I.getPredicate(), B, A);
6542   }
6543   
6544   if (I.isEquality()) {
6545     Value *A, *B, *C, *D;
6546     
6547     // -x == -y --> x == y
6548     if (match(Op0, m_Neg(m_Value(A))) &&
6549         match(Op1, m_Neg(m_Value(B))))
6550       return new ICmpInst(I.getPredicate(), A, B);
6551     
6552     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6553       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6554         Value *OtherVal = A == Op1 ? B : A;
6555         return new ICmpInst(I.getPredicate(), OtherVal,
6556                             Constant::getNullValue(A->getType()));
6557       }
6558
6559       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6560         // A^c1 == C^c2 --> A == C^(c1^c2)
6561         ConstantInt *C1, *C2;
6562         if (match(B, m_ConstantInt(C1)) &&
6563             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6564           Constant *NC = 
6565                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6566           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6567           return new ICmpInst(I.getPredicate(), A, Xor);
6568         }
6569         
6570         // A^B == A^D -> B == D
6571         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6572         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6573         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6574         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6575       }
6576     }
6577     
6578     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6579         (A == Op0 || B == Op0)) {
6580       // A == (A^B)  ->  B == 0
6581       Value *OtherVal = A == Op0 ? B : A;
6582       return new ICmpInst(I.getPredicate(), OtherVal,
6583                           Constant::getNullValue(A->getType()));
6584     }
6585
6586     // (A-B) == A  ->  B == 0
6587     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6588       return new ICmpInst(I.getPredicate(), B, 
6589                           Constant::getNullValue(B->getType()));
6590
6591     // A == (A-B)  ->  B == 0
6592     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6593       return new ICmpInst(I.getPredicate(), B,
6594                           Constant::getNullValue(B->getType()));
6595     
6596     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6597     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6598         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6599         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6600       Value *X = 0, *Y = 0, *Z = 0;
6601       
6602       if (A == C) {
6603         X = B; Y = D; Z = A;
6604       } else if (A == D) {
6605         X = B; Y = C; Z = A;
6606       } else if (B == C) {
6607         X = A; Y = D; Z = B;
6608       } else if (B == D) {
6609         X = A; Y = C; Z = B;
6610       }
6611       
6612       if (X) {   // Build (X^Y) & Z
6613         Op1 = Builder->CreateXor(X, Y, "tmp");
6614         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6615         I.setOperand(0, Op1);
6616         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6617         return &I;
6618       }
6619     }
6620   }
6621   return Changed ? &I : 0;
6622 }
6623
6624
6625 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6626 /// and CmpRHS are both known to be integer constants.
6627 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6628                                           ConstantInt *DivRHS) {
6629   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6630   const APInt &CmpRHSV = CmpRHS->getValue();
6631   
6632   // FIXME: If the operand types don't match the type of the divide 
6633   // then don't attempt this transform. The code below doesn't have the
6634   // logic to deal with a signed divide and an unsigned compare (and
6635   // vice versa). This is because (x /s C1) <s C2  produces different 
6636   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6637   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6638   // work. :(  The if statement below tests that condition and bails 
6639   // if it finds it. 
6640   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6641   if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
6642     return 0;
6643   if (DivRHS->isZero())
6644     return 0; // The ProdOV computation fails on divide by zero.
6645   if (DivIsSigned && DivRHS->isAllOnesValue())
6646     return 0; // The overflow computation also screws up here
6647   if (DivRHS->isOne())
6648     return 0; // Not worth bothering, and eliminates some funny cases
6649               // with INT_MIN.
6650
6651   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6652   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6653   // C2 (CI). By solving for X we can turn this into a range check 
6654   // instead of computing a divide. 
6655   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6656
6657   // Determine if the product overflows by seeing if the product is
6658   // not equal to the divide. Make sure we do the same kind of divide
6659   // as in the LHS instruction that we're folding. 
6660   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6661                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6662
6663   // Get the ICmp opcode
6664   ICmpInst::Predicate Pred = ICI.getPredicate();
6665
6666   // Figure out the interval that is being checked.  For example, a comparison
6667   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6668   // Compute this interval based on the constants involved and the signedness of
6669   // the compare/divide.  This computes a half-open interval, keeping track of
6670   // whether either value in the interval overflows.  After analysis each
6671   // overflow variable is set to 0 if it's corresponding bound variable is valid
6672   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6673   int LoOverflow = 0, HiOverflow = 0;
6674   Constant *LoBound = 0, *HiBound = 0;
6675   
6676   if (!DivIsSigned) {  // udiv
6677     // e.g. X/5 op 3  --> [15, 20)
6678     LoBound = Prod;
6679     HiOverflow = LoOverflow = ProdOV;
6680     if (!HiOverflow)
6681       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6682   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6683     if (CmpRHSV == 0) {       // (X / pos) op 0
6684       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6685       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6686       HiBound = DivRHS;
6687     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6688       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6689       HiOverflow = LoOverflow = ProdOV;
6690       if (!HiOverflow)
6691         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6692     } else {                       // (X / pos) op neg
6693       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6694       HiBound = AddOne(Prod);
6695       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6696       if (!LoOverflow) {
6697         ConstantInt* DivNeg =
6698                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6699         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6700                                      true) ? -1 : 0;
6701        }
6702     }
6703   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6704     if (CmpRHSV == 0) {       // (X / neg) op 0
6705       // e.g. X/-5 op 0  --> [-4, 5)
6706       LoBound = AddOne(DivRHS);
6707       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6708       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6709         HiOverflow = 1;            // [INTMIN+1, overflow)
6710         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6711       }
6712     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6713       // e.g. X/-5 op 3  --> [-19, -14)
6714       HiBound = AddOne(Prod);
6715       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6716       if (!LoOverflow)
6717         LoOverflow = AddWithOverflow(LoBound, HiBound,
6718                                      DivRHS, Context, true) ? -1 : 0;
6719     } else {                       // (X / neg) op neg
6720       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6721       LoOverflow = HiOverflow = ProdOV;
6722       if (!HiOverflow)
6723         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6724     }
6725     
6726     // Dividing by a negative swaps the condition.  LT <-> GT
6727     Pred = ICmpInst::getSwappedPredicate(Pred);
6728   }
6729
6730   Value *X = DivI->getOperand(0);
6731   switch (Pred) {
6732   default: llvm_unreachable("Unhandled icmp opcode!");
6733   case ICmpInst::ICMP_EQ:
6734     if (LoOverflow && HiOverflow)
6735       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6736     else if (HiOverflow)
6737       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6738                           ICmpInst::ICMP_UGE, X, LoBound);
6739     else if (LoOverflow)
6740       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6741                           ICmpInst::ICMP_ULT, X, HiBound);
6742     else
6743       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6744   case ICmpInst::ICMP_NE:
6745     if (LoOverflow && HiOverflow)
6746       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6747     else if (HiOverflow)
6748       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6749                           ICmpInst::ICMP_ULT, X, LoBound);
6750     else if (LoOverflow)
6751       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6752                           ICmpInst::ICMP_UGE, X, HiBound);
6753     else
6754       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6755   case ICmpInst::ICMP_ULT:
6756   case ICmpInst::ICMP_SLT:
6757     if (LoOverflow == +1)   // Low bound is greater than input range.
6758       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6759     if (LoOverflow == -1)   // Low bound is less than input range.
6760       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6761     return new ICmpInst(Pred, X, LoBound);
6762   case ICmpInst::ICMP_UGT:
6763   case ICmpInst::ICMP_SGT:
6764     if (HiOverflow == +1)       // High bound greater than input range.
6765       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6766     else if (HiOverflow == -1)  // High bound less than input range.
6767       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6768     if (Pred == ICmpInst::ICMP_UGT)
6769       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6770     else
6771       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6772   }
6773 }
6774
6775
6776 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6777 ///
6778 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6779                                                           Instruction *LHSI,
6780                                                           ConstantInt *RHS) {
6781   const APInt &RHSV = RHS->getValue();
6782   
6783   switch (LHSI->getOpcode()) {
6784   case Instruction::Trunc:
6785     if (ICI.isEquality() && LHSI->hasOneUse()) {
6786       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6787       // of the high bits truncated out of x are known.
6788       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6789              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6790       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6791       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6792       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6793       
6794       // If all the high bits are known, we can do this xform.
6795       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6796         // Pull in the high bits from known-ones set.
6797         APInt NewRHS(RHS->getValue());
6798         NewRHS.zext(SrcBits);
6799         NewRHS |= KnownOne;
6800         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6801                             ConstantInt::get(*Context, NewRHS));
6802       }
6803     }
6804     break;
6805       
6806   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6807     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6808       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6809       // fold the xor.
6810       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6811           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6812         Value *CompareVal = LHSI->getOperand(0);
6813         
6814         // If the sign bit of the XorCST is not set, there is no change to
6815         // the operation, just stop using the Xor.
6816         if (!XorCST->getValue().isNegative()) {
6817           ICI.setOperand(0, CompareVal);
6818           Worklist.Add(LHSI);
6819           return &ICI;
6820         }
6821         
6822         // Was the old condition true if the operand is positive?
6823         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6824         
6825         // If so, the new one isn't.
6826         isTrueIfPositive ^= true;
6827         
6828         if (isTrueIfPositive)
6829           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6830                               SubOne(RHS));
6831         else
6832           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6833                               AddOne(RHS));
6834       }
6835
6836       if (LHSI->hasOneUse()) {
6837         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6838         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6839           const APInt &SignBit = XorCST->getValue();
6840           ICmpInst::Predicate Pred = ICI.isSigned()
6841                                          ? ICI.getUnsignedPredicate()
6842                                          : ICI.getSignedPredicate();
6843           return new ICmpInst(Pred, LHSI->getOperand(0),
6844                               ConstantInt::get(*Context, RHSV ^ SignBit));
6845         }
6846
6847         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6848         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6849           const APInt &NotSignBit = XorCST->getValue();
6850           ICmpInst::Predicate Pred = ICI.isSigned()
6851                                          ? ICI.getUnsignedPredicate()
6852                                          : ICI.getSignedPredicate();
6853           Pred = ICI.getSwappedPredicate(Pred);
6854           return new ICmpInst(Pred, LHSI->getOperand(0),
6855                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6856         }
6857       }
6858     }
6859     break;
6860   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6861     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6862         LHSI->getOperand(0)->hasOneUse()) {
6863       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6864       
6865       // If the LHS is an AND of a truncating cast, we can widen the
6866       // and/compare to be the input width without changing the value
6867       // produced, eliminating a cast.
6868       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6869         // We can do this transformation if either the AND constant does not
6870         // have its sign bit set or if it is an equality comparison. 
6871         // Extending a relational comparison when we're checking the sign
6872         // bit would not work.
6873         if (Cast->hasOneUse() &&
6874             (ICI.isEquality() ||
6875              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6876           uint32_t BitWidth = 
6877             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6878           APInt NewCST = AndCST->getValue();
6879           NewCST.zext(BitWidth);
6880           APInt NewCI = RHSV;
6881           NewCI.zext(BitWidth);
6882           Value *NewAnd = 
6883             Builder->CreateAnd(Cast->getOperand(0),
6884                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6885           return new ICmpInst(ICI.getPredicate(), NewAnd,
6886                               ConstantInt::get(*Context, NewCI));
6887         }
6888       }
6889       
6890       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6891       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6892       // happens a LOT in code produced by the C front-end, for bitfield
6893       // access.
6894       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6895       if (Shift && !Shift->isShift())
6896         Shift = 0;
6897       
6898       ConstantInt *ShAmt;
6899       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6900       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6901       const Type *AndTy = AndCST->getType();          // Type of the and.
6902       
6903       // We can fold this as long as we can't shift unknown bits
6904       // into the mask.  This can only happen with signed shift
6905       // rights, as they sign-extend.
6906       if (ShAmt) {
6907         bool CanFold = Shift->isLogicalShift();
6908         if (!CanFold) {
6909           // To test for the bad case of the signed shr, see if any
6910           // of the bits shifted in could be tested after the mask.
6911           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6912           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6913           
6914           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6915           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6916                AndCST->getValue()) == 0)
6917             CanFold = true;
6918         }
6919         
6920         if (CanFold) {
6921           Constant *NewCst;
6922           if (Shift->getOpcode() == Instruction::Shl)
6923             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6924           else
6925             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6926           
6927           // Check to see if we are shifting out any of the bits being
6928           // compared.
6929           if (ConstantExpr::get(Shift->getOpcode(),
6930                                        NewCst, ShAmt) != RHS) {
6931             // If we shifted bits out, the fold is not going to work out.
6932             // As a special case, check to see if this means that the
6933             // result is always true or false now.
6934             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6935               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6936             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6937               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6938           } else {
6939             ICI.setOperand(1, NewCst);
6940             Constant *NewAndCST;
6941             if (Shift->getOpcode() == Instruction::Shl)
6942               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6943             else
6944               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6945             LHSI->setOperand(1, NewAndCST);
6946             LHSI->setOperand(0, Shift->getOperand(0));
6947             Worklist.Add(Shift); // Shift is dead.
6948             return &ICI;
6949           }
6950         }
6951       }
6952       
6953       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6954       // preferable because it allows the C<<Y expression to be hoisted out
6955       // of a loop if Y is invariant and X is not.
6956       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6957           ICI.isEquality() && !Shift->isArithmeticShift() &&
6958           !isa<Constant>(Shift->getOperand(0))) {
6959         // Compute C << Y.
6960         Value *NS;
6961         if (Shift->getOpcode() == Instruction::LShr) {
6962           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6963         } else {
6964           // Insert a logical shift.
6965           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6966         }
6967         
6968         // Compute X & (C << Y).
6969         Value *NewAnd = 
6970           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6971         
6972         ICI.setOperand(0, NewAnd);
6973         return &ICI;
6974       }
6975     }
6976     break;
6977     
6978   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6979     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6980     if (!ShAmt) break;
6981     
6982     uint32_t TypeBits = RHSV.getBitWidth();
6983     
6984     // Check that the shift amount is in range.  If not, don't perform
6985     // undefined shifts.  When the shift is visited it will be
6986     // simplified.
6987     if (ShAmt->uge(TypeBits))
6988       break;
6989     
6990     if (ICI.isEquality()) {
6991       // If we are comparing against bits always shifted out, the
6992       // comparison cannot succeed.
6993       Constant *Comp =
6994         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6995                                                                  ShAmt);
6996       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6997         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6998         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6999         return ReplaceInstUsesWith(ICI, Cst);
7000       }
7001       
7002       if (LHSI->hasOneUse()) {
7003         // Otherwise strength reduce the shift into an and.
7004         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7005         Constant *Mask =
7006           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
7007                                                        TypeBits-ShAmtVal));
7008         
7009         Value *And =
7010           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
7011         return new ICmpInst(ICI.getPredicate(), And,
7012                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
7013       }
7014     }
7015     
7016     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7017     bool TrueIfSigned = false;
7018     if (LHSI->hasOneUse() &&
7019         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7020       // (X << 31) <s 0  --> (X&1) != 0
7021       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
7022                                            (TypeBits-ShAmt->getZExtValue()-1));
7023       Value *And =
7024         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
7025       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
7026                           And, Constant::getNullValue(And->getType()));
7027     }
7028     break;
7029   }
7030     
7031   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
7032   case Instruction::AShr: {
7033     // Only handle equality comparisons of shift-by-constant.
7034     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7035     if (!ShAmt || !ICI.isEquality()) break;
7036
7037     // Check that the shift amount is in range.  If not, don't perform
7038     // undefined shifts.  When the shift is visited it will be
7039     // simplified.
7040     uint32_t TypeBits = RHSV.getBitWidth();
7041     if (ShAmt->uge(TypeBits))
7042       break;
7043     
7044     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7045       
7046     // If we are comparing against bits always shifted out, the
7047     // comparison cannot succeed.
7048     APInt Comp = RHSV << ShAmtVal;
7049     if (LHSI->getOpcode() == Instruction::LShr)
7050       Comp = Comp.lshr(ShAmtVal);
7051     else
7052       Comp = Comp.ashr(ShAmtVal);
7053     
7054     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7055       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7056       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7057       return ReplaceInstUsesWith(ICI, Cst);
7058     }
7059     
7060     // Otherwise, check to see if the bits shifted out are known to be zero.
7061     // If so, we can compare against the unshifted value:
7062     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7063     if (LHSI->hasOneUse() &&
7064         MaskedValueIsZero(LHSI->getOperand(0), 
7065                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7066       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
7067                           ConstantExpr::getShl(RHS, ShAmt));
7068     }
7069       
7070     if (LHSI->hasOneUse()) {
7071       // Otherwise strength reduce the shift into an and.
7072       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7073       Constant *Mask = ConstantInt::get(*Context, Val);
7074       
7075       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7076                                       Mask, LHSI->getName()+".mask");
7077       return new ICmpInst(ICI.getPredicate(), And,
7078                           ConstantExpr::getShl(RHS, ShAmt));
7079     }
7080     break;
7081   }
7082     
7083   case Instruction::SDiv:
7084   case Instruction::UDiv:
7085     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7086     // Fold this div into the comparison, producing a range check. 
7087     // Determine, based on the divide type, what the range is being 
7088     // checked.  If there is an overflow on the low or high side, remember 
7089     // it, otherwise compute the range [low, hi) bounding the new value.
7090     // See: InsertRangeTest above for the kinds of replacements possible.
7091     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7092       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7093                                           DivRHS))
7094         return R;
7095     break;
7096
7097   case Instruction::Add:
7098     // Fold: icmp pred (add, X, C1), C2
7099
7100     if (!ICI.isEquality()) {
7101       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7102       if (!LHSC) break;
7103       const APInt &LHSV = LHSC->getValue();
7104
7105       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7106                             .subtract(LHSV);
7107
7108       if (ICI.isSigned()) {
7109         if (CR.getLower().isSignBit()) {
7110           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7111                               ConstantInt::get(*Context, CR.getUpper()));
7112         } else if (CR.getUpper().isSignBit()) {
7113           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7114                               ConstantInt::get(*Context, CR.getLower()));
7115         }
7116       } else {
7117         if (CR.getLower().isMinValue()) {
7118           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7119                               ConstantInt::get(*Context, CR.getUpper()));
7120         } else if (CR.getUpper().isMinValue()) {
7121           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7122                               ConstantInt::get(*Context, CR.getLower()));
7123         }
7124       }
7125     }
7126     break;
7127   }
7128   
7129   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7130   if (ICI.isEquality()) {
7131     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7132     
7133     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7134     // the second operand is a constant, simplify a bit.
7135     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7136       switch (BO->getOpcode()) {
7137       case Instruction::SRem:
7138         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7139         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7140           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7141           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7142             Value *NewRem =
7143               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7144                                   BO->getName());
7145             return new ICmpInst(ICI.getPredicate(), NewRem,
7146                                 Constant::getNullValue(BO->getType()));
7147           }
7148         }
7149         break;
7150       case Instruction::Add:
7151         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7152         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7153           if (BO->hasOneUse())
7154             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7155                                 ConstantExpr::getSub(RHS, BOp1C));
7156         } else if (RHSV == 0) {
7157           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7158           // efficiently invertible, or if the add has just this one use.
7159           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7160           
7161           if (Value *NegVal = dyn_castNegVal(BOp1))
7162             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7163           else if (Value *NegVal = dyn_castNegVal(BOp0))
7164             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7165           else if (BO->hasOneUse()) {
7166             Value *Neg = Builder->CreateNeg(BOp1);
7167             Neg->takeName(BO);
7168             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7169           }
7170         }
7171         break;
7172       case Instruction::Xor:
7173         // For the xor case, we can xor two constants together, eliminating
7174         // the explicit xor.
7175         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7176           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7177                               ConstantExpr::getXor(RHS, BOC));
7178         
7179         // FALLTHROUGH
7180       case Instruction::Sub:
7181         // Replace (([sub|xor] A, B) != 0) with (A != B)
7182         if (RHSV == 0)
7183           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7184                               BO->getOperand(1));
7185         break;
7186         
7187       case Instruction::Or:
7188         // If bits are being or'd in that are not present in the constant we
7189         // are comparing against, then the comparison could never succeed!
7190         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7191           Constant *NotCI = ConstantExpr::getNot(RHS);
7192           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7193             return ReplaceInstUsesWith(ICI,
7194                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7195                                        isICMP_NE));
7196         }
7197         break;
7198         
7199       case Instruction::And:
7200         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7201           // If bits are being compared against that are and'd out, then the
7202           // comparison can never succeed!
7203           if ((RHSV & ~BOC->getValue()) != 0)
7204             return ReplaceInstUsesWith(ICI,
7205                                        ConstantInt::get(Type::getInt1Ty(*Context),
7206                                        isICMP_NE));
7207           
7208           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7209           if (RHS == BOC && RHSV.isPowerOf2())
7210             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7211                                 ICmpInst::ICMP_NE, LHSI,
7212                                 Constant::getNullValue(RHS->getType()));
7213           
7214           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7215           if (BOC->getValue().isSignBit()) {
7216             Value *X = BO->getOperand(0);
7217             Constant *Zero = Constant::getNullValue(X->getType());
7218             ICmpInst::Predicate pred = isICMP_NE ? 
7219               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7220             return new ICmpInst(pred, X, Zero);
7221           }
7222           
7223           // ((X & ~7) == 0) --> X < 8
7224           if (RHSV == 0 && isHighOnes(BOC)) {
7225             Value *X = BO->getOperand(0);
7226             Constant *NegX = ConstantExpr::getNeg(BOC);
7227             ICmpInst::Predicate pred = isICMP_NE ? 
7228               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7229             return new ICmpInst(pred, X, NegX);
7230           }
7231         }
7232       default: break;
7233       }
7234     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7235       // Handle icmp {eq|ne} <intrinsic>, intcst.
7236       if (II->getIntrinsicID() == Intrinsic::bswap) {
7237         Worklist.Add(II);
7238         ICI.setOperand(0, II->getOperand(1));
7239         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7240         return &ICI;
7241       }
7242     }
7243   }
7244   return 0;
7245 }
7246
7247 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7248 /// We only handle extending casts so far.
7249 ///
7250 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7251   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7252   Value *LHSCIOp        = LHSCI->getOperand(0);
7253   const Type *SrcTy     = LHSCIOp->getType();
7254   const Type *DestTy    = LHSCI->getType();
7255   Value *RHSCIOp;
7256
7257   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7258   // integer type is the same size as the pointer type.
7259   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7260       TD->getPointerSizeInBits() ==
7261          cast<IntegerType>(DestTy)->getBitWidth()) {
7262     Value *RHSOp = 0;
7263     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7264       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7265     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7266       RHSOp = RHSC->getOperand(0);
7267       // If the pointer types don't match, insert a bitcast.
7268       if (LHSCIOp->getType() != RHSOp->getType())
7269         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7270     }
7271
7272     if (RHSOp)
7273       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7274   }
7275   
7276   // The code below only handles extension cast instructions, so far.
7277   // Enforce this.
7278   if (LHSCI->getOpcode() != Instruction::ZExt &&
7279       LHSCI->getOpcode() != Instruction::SExt)
7280     return 0;
7281
7282   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7283   bool isSignedCmp = ICI.isSigned();
7284
7285   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7286     // Not an extension from the same type?
7287     RHSCIOp = CI->getOperand(0);
7288     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7289       return 0;
7290     
7291     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7292     // and the other is a zext), then we can't handle this.
7293     if (CI->getOpcode() != LHSCI->getOpcode())
7294       return 0;
7295
7296     // Deal with equality cases early.
7297     if (ICI.isEquality())
7298       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7299
7300     // A signed comparison of sign extended values simplifies into a
7301     // signed comparison.
7302     if (isSignedCmp && isSignedExt)
7303       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7304
7305     // The other three cases all fold into an unsigned comparison.
7306     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7307   }
7308
7309   // If we aren't dealing with a constant on the RHS, exit early
7310   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7311   if (!CI)
7312     return 0;
7313
7314   // Compute the constant that would happen if we truncated to SrcTy then
7315   // reextended to DestTy.
7316   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7317   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7318                                                 Res1, DestTy);
7319
7320   // If the re-extended constant didn't change...
7321   if (Res2 == CI) {
7322     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7323     // For example, we might have:
7324     //    %A = sext i16 %X to i32
7325     //    %B = icmp ugt i32 %A, 1330
7326     // It is incorrect to transform this into 
7327     //    %B = icmp ugt i16 %X, 1330
7328     // because %A may have negative value. 
7329     //
7330     // However, we allow this when the compare is EQ/NE, because they are
7331     // signless.
7332     if (isSignedExt == isSignedCmp || ICI.isEquality())
7333       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7334     return 0;
7335   }
7336
7337   // The re-extended constant changed so the constant cannot be represented 
7338   // in the shorter type. Consequently, we cannot emit a simple comparison.
7339
7340   // First, handle some easy cases. We know the result cannot be equal at this
7341   // point so handle the ICI.isEquality() cases
7342   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7343     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7344   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7345     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7346
7347   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7348   // should have been folded away previously and not enter in here.
7349   Value *Result;
7350   if (isSignedCmp) {
7351     // We're performing a signed comparison.
7352     if (cast<ConstantInt>(CI)->getValue().isNegative())
7353       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7354     else
7355       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7356   } else {
7357     // We're performing an unsigned comparison.
7358     if (isSignedExt) {
7359       // We're performing an unsigned comp with a sign extended value.
7360       // This is true if the input is >= 0. [aka >s -1]
7361       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7362       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7363     } else {
7364       // Unsigned extend & unsigned compare -> always true.
7365       Result = ConstantInt::getTrue(*Context);
7366     }
7367   }
7368
7369   // Finally, return the value computed.
7370   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7371       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7372     return ReplaceInstUsesWith(ICI, Result);
7373
7374   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7375           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7376          "ICmp should be folded!");
7377   if (Constant *CI = dyn_cast<Constant>(Result))
7378     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7379   return BinaryOperator::CreateNot(Result);
7380 }
7381
7382 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7383   return commonShiftTransforms(I);
7384 }
7385
7386 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7387   return commonShiftTransforms(I);
7388 }
7389
7390 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7391   if (Instruction *R = commonShiftTransforms(I))
7392     return R;
7393   
7394   Value *Op0 = I.getOperand(0);
7395   
7396   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7397   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7398     if (CSI->isAllOnesValue())
7399       return ReplaceInstUsesWith(I, CSI);
7400
7401   // See if we can turn a signed shr into an unsigned shr.
7402   if (MaskedValueIsZero(Op0,
7403                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7404     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7405
7406   // Arithmetic shifting an all-sign-bit value is a no-op.
7407   unsigned NumSignBits = ComputeNumSignBits(Op0);
7408   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7409     return ReplaceInstUsesWith(I, Op0);
7410
7411   return 0;
7412 }
7413
7414 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7415   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7416   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7417
7418   // shl X, 0 == X and shr X, 0 == X
7419   // shl 0, X == 0 and shr 0, X == 0
7420   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7421       Op0 == Constant::getNullValue(Op0->getType()))
7422     return ReplaceInstUsesWith(I, Op0);
7423   
7424   if (isa<UndefValue>(Op0)) {            
7425     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7426       return ReplaceInstUsesWith(I, Op0);
7427     else                                    // undef << X -> 0, undef >>u X -> 0
7428       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7429   }
7430   if (isa<UndefValue>(Op1)) {
7431     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7432       return ReplaceInstUsesWith(I, Op0);          
7433     else                                     // X << undef, X >>u undef -> 0
7434       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7435   }
7436
7437   // See if we can fold away this shift.
7438   if (SimplifyDemandedInstructionBits(I))
7439     return &I;
7440
7441   // Try to fold constant and into select arguments.
7442   if (isa<Constant>(Op0))
7443     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7444       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7445         return R;
7446
7447   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7448     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7449       return Res;
7450   return 0;
7451 }
7452
7453 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7454                                                BinaryOperator &I) {
7455   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7456
7457   // See if we can simplify any instructions used by the instruction whose sole 
7458   // purpose is to compute bits we don't care about.
7459   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7460   
7461   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7462   // a signed shift.
7463   //
7464   if (Op1->uge(TypeBits)) {
7465     if (I.getOpcode() != Instruction::AShr)
7466       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7467     else {
7468       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7469       return &I;
7470     }
7471   }
7472   
7473   // ((X*C1) << C2) == (X * (C1 << C2))
7474   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7475     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7476       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7477         return BinaryOperator::CreateMul(BO->getOperand(0),
7478                                         ConstantExpr::getShl(BOOp, Op1));
7479   
7480   // Try to fold constant and into select arguments.
7481   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7482     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7483       return R;
7484   if (isa<PHINode>(Op0))
7485     if (Instruction *NV = FoldOpIntoPhi(I))
7486       return NV;
7487   
7488   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7489   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7490     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7491     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7492     // place.  Don't try to do this transformation in this case.  Also, we
7493     // require that the input operand is a shift-by-constant so that we have
7494     // confidence that the shifts will get folded together.  We could do this
7495     // xform in more cases, but it is unlikely to be profitable.
7496     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7497         isa<ConstantInt>(TrOp->getOperand(1))) {
7498       // Okay, we'll do this xform.  Make the shift of shift.
7499       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7500       // (shift2 (shift1 & 0x00FF), c2)
7501       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7502
7503       // For logical shifts, the truncation has the effect of making the high
7504       // part of the register be zeros.  Emulate this by inserting an AND to
7505       // clear the top bits as needed.  This 'and' will usually be zapped by
7506       // other xforms later if dead.
7507       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7508       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7509       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7510       
7511       // The mask we constructed says what the trunc would do if occurring
7512       // between the shifts.  We want to know the effect *after* the second
7513       // shift.  We know that it is a logical shift by a constant, so adjust the
7514       // mask as appropriate.
7515       if (I.getOpcode() == Instruction::Shl)
7516         MaskV <<= Op1->getZExtValue();
7517       else {
7518         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7519         MaskV = MaskV.lshr(Op1->getZExtValue());
7520       }
7521
7522       // shift1 & 0x00FF
7523       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7524                                       TI->getName());
7525
7526       // Return the value truncated to the interesting size.
7527       return new TruncInst(And, I.getType());
7528     }
7529   }
7530   
7531   if (Op0->hasOneUse()) {
7532     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7533       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7534       Value *V1, *V2;
7535       ConstantInt *CC;
7536       switch (Op0BO->getOpcode()) {
7537         default: break;
7538         case Instruction::Add:
7539         case Instruction::And:
7540         case Instruction::Or:
7541         case Instruction::Xor: {
7542           // These operators commute.
7543           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7544           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7545               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7546                     m_Specific(Op1)))) {
7547             Value *YS =         // (Y << C)
7548               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7549             // (X + (Y << C))
7550             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7551                                             Op0BO->getOperand(1)->getName());
7552             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7553             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7554                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7555           }
7556           
7557           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7558           Value *Op0BOOp1 = Op0BO->getOperand(1);
7559           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7560               match(Op0BOOp1, 
7561                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7562                           m_ConstantInt(CC))) &&
7563               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7564             Value *YS =   // (Y << C)
7565               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7566                                            Op0BO->getName());
7567             // X & (CC << C)
7568             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7569                                            V1->getName()+".mask");
7570             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7571           }
7572         }
7573           
7574         // FALL THROUGH.
7575         case Instruction::Sub: {
7576           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7577           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7578               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7579                     m_Specific(Op1)))) {
7580             Value *YS =  // (Y << C)
7581               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7582             // (X + (Y << C))
7583             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7584                                             Op0BO->getOperand(0)->getName());
7585             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7586             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7587                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7588           }
7589           
7590           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7591           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7592               match(Op0BO->getOperand(0),
7593                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7594                           m_ConstantInt(CC))) && V2 == Op1 &&
7595               cast<BinaryOperator>(Op0BO->getOperand(0))
7596                   ->getOperand(0)->hasOneUse()) {
7597             Value *YS = // (Y << C)
7598               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7599             // X & (CC << C)
7600             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7601                                            V1->getName()+".mask");
7602             
7603             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7604           }
7605           
7606           break;
7607         }
7608       }
7609       
7610       
7611       // If the operand is an bitwise operator with a constant RHS, and the
7612       // shift is the only use, we can pull it out of the shift.
7613       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7614         bool isValid = true;     // Valid only for And, Or, Xor
7615         bool highBitSet = false; // Transform if high bit of constant set?
7616         
7617         switch (Op0BO->getOpcode()) {
7618           default: isValid = false; break;   // Do not perform transform!
7619           case Instruction::Add:
7620             isValid = isLeftShift;
7621             break;
7622           case Instruction::Or:
7623           case Instruction::Xor:
7624             highBitSet = false;
7625             break;
7626           case Instruction::And:
7627             highBitSet = true;
7628             break;
7629         }
7630         
7631         // If this is a signed shift right, and the high bit is modified
7632         // by the logical operation, do not perform the transformation.
7633         // The highBitSet boolean indicates the value of the high bit of
7634         // the constant which would cause it to be modified for this
7635         // operation.
7636         //
7637         if (isValid && I.getOpcode() == Instruction::AShr)
7638           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7639         
7640         if (isValid) {
7641           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7642           
7643           Value *NewShift =
7644             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7645           NewShift->takeName(Op0BO);
7646           
7647           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7648                                         NewRHS);
7649         }
7650       }
7651     }
7652   }
7653   
7654   // Find out if this is a shift of a shift by a constant.
7655   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7656   if (ShiftOp && !ShiftOp->isShift())
7657     ShiftOp = 0;
7658   
7659   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7660     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7661     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7662     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7663     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7664     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7665     Value *X = ShiftOp->getOperand(0);
7666     
7667     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7668     
7669     const IntegerType *Ty = cast<IntegerType>(I.getType());
7670     
7671     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7672     if (I.getOpcode() == ShiftOp->getOpcode()) {
7673       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7674       // saturates.
7675       if (AmtSum >= TypeBits) {
7676         if (I.getOpcode() != Instruction::AShr)
7677           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7678         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7679       }
7680       
7681       return BinaryOperator::Create(I.getOpcode(), X,
7682                                     ConstantInt::get(Ty, AmtSum));
7683     }
7684     
7685     if (ShiftOp->getOpcode() == Instruction::LShr &&
7686         I.getOpcode() == Instruction::AShr) {
7687       if (AmtSum >= TypeBits)
7688         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7689       
7690       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7691       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7692     }
7693     
7694     if (ShiftOp->getOpcode() == Instruction::AShr &&
7695         I.getOpcode() == Instruction::LShr) {
7696       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7697       if (AmtSum >= TypeBits)
7698         AmtSum = TypeBits-1;
7699       
7700       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7701
7702       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7703       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7704     }
7705     
7706     // Okay, if we get here, one shift must be left, and the other shift must be
7707     // right.  See if the amounts are equal.
7708     if (ShiftAmt1 == ShiftAmt2) {
7709       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7710       if (I.getOpcode() == Instruction::Shl) {
7711         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7712         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7713       }
7714       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7715       if (I.getOpcode() == Instruction::LShr) {
7716         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7717         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7718       }
7719       // We can simplify ((X << C) >>s C) into a trunc + sext.
7720       // NOTE: we could do this for any C, but that would make 'unusual' integer
7721       // types.  For now, just stick to ones well-supported by the code
7722       // generators.
7723       const Type *SExtType = 0;
7724       switch (Ty->getBitWidth() - ShiftAmt1) {
7725       case 1  :
7726       case 8  :
7727       case 16 :
7728       case 32 :
7729       case 64 :
7730       case 128:
7731         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7732         break;
7733       default: break;
7734       }
7735       if (SExtType)
7736         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7737       // Otherwise, we can't handle it yet.
7738     } else if (ShiftAmt1 < ShiftAmt2) {
7739       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7740       
7741       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7742       if (I.getOpcode() == Instruction::Shl) {
7743         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7744                ShiftOp->getOpcode() == Instruction::AShr);
7745         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7746         
7747         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7748         return BinaryOperator::CreateAnd(Shift,
7749                                          ConstantInt::get(*Context, Mask));
7750       }
7751       
7752       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7753       if (I.getOpcode() == Instruction::LShr) {
7754         assert(ShiftOp->getOpcode() == Instruction::Shl);
7755         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7756         
7757         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7758         return BinaryOperator::CreateAnd(Shift,
7759                                          ConstantInt::get(*Context, Mask));
7760       }
7761       
7762       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7763     } else {
7764       assert(ShiftAmt2 < ShiftAmt1);
7765       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7766
7767       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7768       if (I.getOpcode() == Instruction::Shl) {
7769         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7770                ShiftOp->getOpcode() == Instruction::AShr);
7771         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7772                                             ConstantInt::get(Ty, ShiftDiff));
7773         
7774         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7775         return BinaryOperator::CreateAnd(Shift,
7776                                          ConstantInt::get(*Context, Mask));
7777       }
7778       
7779       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7780       if (I.getOpcode() == Instruction::LShr) {
7781         assert(ShiftOp->getOpcode() == Instruction::Shl);
7782         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7783         
7784         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7785         return BinaryOperator::CreateAnd(Shift,
7786                                          ConstantInt::get(*Context, Mask));
7787       }
7788       
7789       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7790     }
7791   }
7792   return 0;
7793 }
7794
7795
7796 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7797 /// expression.  If so, decompose it, returning some value X, such that Val is
7798 /// X*Scale+Offset.
7799 ///
7800 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7801                                         int &Offset, LLVMContext *Context) {
7802   assert(Val->getType() == Type::getInt32Ty(*Context) && 
7803          "Unexpected allocation size type!");
7804   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7805     Offset = CI->getZExtValue();
7806     Scale  = 0;
7807     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7808   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7809     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7810       if (I->getOpcode() == Instruction::Shl) {
7811         // This is a value scaled by '1 << the shift amt'.
7812         Scale = 1U << RHS->getZExtValue();
7813         Offset = 0;
7814         return I->getOperand(0);
7815       } else if (I->getOpcode() == Instruction::Mul) {
7816         // This value is scaled by 'RHS'.
7817         Scale = RHS->getZExtValue();
7818         Offset = 0;
7819         return I->getOperand(0);
7820       } else if (I->getOpcode() == Instruction::Add) {
7821         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7822         // where C1 is divisible by C2.
7823         unsigned SubScale;
7824         Value *SubVal = 
7825           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7826                                     Offset, Context);
7827         Offset += RHS->getZExtValue();
7828         Scale = SubScale;
7829         return SubVal;
7830       }
7831     }
7832   }
7833
7834   // Otherwise, we can't look past this.
7835   Scale = 1;
7836   Offset = 0;
7837   return Val;
7838 }
7839
7840
7841 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7842 /// try to eliminate the cast by moving the type information into the alloc.
7843 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7844                                                    AllocaInst &AI) {
7845   const PointerType *PTy = cast<PointerType>(CI.getType());
7846   
7847   BuilderTy AllocaBuilder(*Builder);
7848   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7849   
7850   // Remove any uses of AI that are dead.
7851   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7852   
7853   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7854     Instruction *User = cast<Instruction>(*UI++);
7855     if (isInstructionTriviallyDead(User)) {
7856       while (UI != E && *UI == User)
7857         ++UI; // If this instruction uses AI more than once, don't break UI.
7858       
7859       ++NumDeadInst;
7860       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7861       EraseInstFromFunction(*User);
7862     }
7863   }
7864
7865   // This requires TargetData to get the alloca alignment and size information.
7866   if (!TD) return 0;
7867
7868   // Get the type really allocated and the type casted to.
7869   const Type *AllocElTy = AI.getAllocatedType();
7870   const Type *CastElTy = PTy->getElementType();
7871   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7872
7873   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7874   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7875   if (CastElTyAlign < AllocElTyAlign) return 0;
7876
7877   // If the allocation has multiple uses, only promote it if we are strictly
7878   // increasing the alignment of the resultant allocation.  If we keep it the
7879   // same, we open the door to infinite loops of various kinds.  (A reference
7880   // from a dbg.declare doesn't count as a use for this purpose.)
7881   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7882       CastElTyAlign == AllocElTyAlign) return 0;
7883
7884   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7885   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7886   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7887
7888   // See if we can satisfy the modulus by pulling a scale out of the array
7889   // size argument.
7890   unsigned ArraySizeScale;
7891   int ArrayOffset;
7892   Value *NumElements = // See if the array size is a decomposable linear expr.
7893     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7894                               ArrayOffset, Context);
7895  
7896   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7897   // do the xform.
7898   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7899       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7900
7901   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7902   Value *Amt = 0;
7903   if (Scale == 1) {
7904     Amt = NumElements;
7905   } else {
7906     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7907     // Insert before the alloca, not before the cast.
7908     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7909   }
7910   
7911   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7912     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7913     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7914   }
7915   
7916   AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7917   New->setAlignment(AI.getAlignment());
7918   New->takeName(&AI);
7919   
7920   // If the allocation has one real use plus a dbg.declare, just remove the
7921   // declare.
7922   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7923     EraseInstFromFunction(*DI);
7924   }
7925   // If the allocation has multiple real uses, insert a cast and change all
7926   // things that used it to use the new cast.  This will also hack on CI, but it
7927   // will die soon.
7928   else if (!AI.hasOneUse()) {
7929     // New is the allocation instruction, pointer typed. AI is the original
7930     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7931     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7932     AI.replaceAllUsesWith(NewCast);
7933   }
7934   return ReplaceInstUsesWith(CI, New);
7935 }
7936
7937 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7938 /// and return it as type Ty without inserting any new casts and without
7939 /// changing the computed value.  This is used by code that tries to decide
7940 /// whether promoting or shrinking integer operations to wider or smaller types
7941 /// will allow us to eliminate a truncate or extend.
7942 ///
7943 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7944 /// extension operation if Ty is larger.
7945 ///
7946 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7947 /// should return true if trunc(V) can be computed by computing V in the smaller
7948 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7949 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7950 /// efficiently truncated.
7951 ///
7952 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7953 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7954 /// the final result.
7955 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7956                                               unsigned CastOpc,
7957                                               int &NumCastsRemoved){
7958   // We can always evaluate constants in another type.
7959   if (isa<Constant>(V))
7960     return true;
7961   
7962   Instruction *I = dyn_cast<Instruction>(V);
7963   if (!I) return false;
7964   
7965   const Type *OrigTy = V->getType();
7966   
7967   // If this is an extension or truncate, we can often eliminate it.
7968   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7969     // If this is a cast from the destination type, we can trivially eliminate
7970     // it, and this will remove a cast overall.
7971     if (I->getOperand(0)->getType() == Ty) {
7972       // If the first operand is itself a cast, and is eliminable, do not count
7973       // this as an eliminable cast.  We would prefer to eliminate those two
7974       // casts first.
7975       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7976         ++NumCastsRemoved;
7977       return true;
7978     }
7979   }
7980
7981   // We can't extend or shrink something that has multiple uses: doing so would
7982   // require duplicating the instruction in general, which isn't profitable.
7983   if (!I->hasOneUse()) return false;
7984
7985   unsigned Opc = I->getOpcode();
7986   switch (Opc) {
7987   case Instruction::Add:
7988   case Instruction::Sub:
7989   case Instruction::Mul:
7990   case Instruction::And:
7991   case Instruction::Or:
7992   case Instruction::Xor:
7993     // These operators can all arbitrarily be extended or truncated.
7994     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7995                                       NumCastsRemoved) &&
7996            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7997                                       NumCastsRemoved);
7998
7999   case Instruction::UDiv:
8000   case Instruction::URem: {
8001     // UDiv and URem can be truncated if all the truncated bits are zero.
8002     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8003     uint32_t BitWidth = Ty->getScalarSizeInBits();
8004     if (BitWidth < OrigBitWidth) {
8005       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8006       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8007           MaskedValueIsZero(I->getOperand(1), Mask)) {
8008         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8009                                           NumCastsRemoved) &&
8010                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8011                                           NumCastsRemoved);
8012       }
8013     }
8014     break;
8015   }
8016   case Instruction::Shl:
8017     // If we are truncating the result of this SHL, and if it's a shift of a
8018     // constant amount, we can always perform a SHL in a smaller type.
8019     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8020       uint32_t BitWidth = Ty->getScalarSizeInBits();
8021       if (BitWidth < OrigTy->getScalarSizeInBits() &&
8022           CI->getLimitedValue(BitWidth) < BitWidth)
8023         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8024                                           NumCastsRemoved);
8025     }
8026     break;
8027   case Instruction::LShr:
8028     // If this is a truncate of a logical shr, we can truncate it to a smaller
8029     // lshr iff we know that the bits we would otherwise be shifting in are
8030     // already zeros.
8031     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8032       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8033       uint32_t BitWidth = Ty->getScalarSizeInBits();
8034       if (BitWidth < OrigBitWidth &&
8035           MaskedValueIsZero(I->getOperand(0),
8036             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8037           CI->getLimitedValue(BitWidth) < BitWidth) {
8038         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8039                                           NumCastsRemoved);
8040       }
8041     }
8042     break;
8043   case Instruction::ZExt:
8044   case Instruction::SExt:
8045   case Instruction::Trunc:
8046     // If this is the same kind of case as our original (e.g. zext+zext), we
8047     // can safely replace it.  Note that replacing it does not reduce the number
8048     // of casts in the input.
8049     if (Opc == CastOpc)
8050       return true;
8051
8052     // sext (zext ty1), ty2 -> zext ty2
8053     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8054       return true;
8055     break;
8056   case Instruction::Select: {
8057     SelectInst *SI = cast<SelectInst>(I);
8058     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8059                                       NumCastsRemoved) &&
8060            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8061                                       NumCastsRemoved);
8062   }
8063   case Instruction::PHI: {
8064     // We can change a phi if we can change all operands.
8065     PHINode *PN = cast<PHINode>(I);
8066     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8067       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8068                                       NumCastsRemoved))
8069         return false;
8070     return true;
8071   }
8072   default:
8073     // TODO: Can handle more cases here.
8074     break;
8075   }
8076   
8077   return false;
8078 }
8079
8080 /// EvaluateInDifferentType - Given an expression that 
8081 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8082 /// evaluate the expression.
8083 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8084                                              bool isSigned) {
8085   if (Constant *C = dyn_cast<Constant>(V))
8086     return ConstantExpr::getIntegerCast(C, Ty,
8087                                                isSigned /*Sext or ZExt*/);
8088
8089   // Otherwise, it must be an instruction.
8090   Instruction *I = cast<Instruction>(V);
8091   Instruction *Res = 0;
8092   unsigned Opc = I->getOpcode();
8093   switch (Opc) {
8094   case Instruction::Add:
8095   case Instruction::Sub:
8096   case Instruction::Mul:
8097   case Instruction::And:
8098   case Instruction::Or:
8099   case Instruction::Xor:
8100   case Instruction::AShr:
8101   case Instruction::LShr:
8102   case Instruction::Shl:
8103   case Instruction::UDiv:
8104   case Instruction::URem: {
8105     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8106     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8107     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8108     break;
8109   }    
8110   case Instruction::Trunc:
8111   case Instruction::ZExt:
8112   case Instruction::SExt:
8113     // If the source type of the cast is the type we're trying for then we can
8114     // just return the source.  There's no need to insert it because it is not
8115     // new.
8116     if (I->getOperand(0)->getType() == Ty)
8117       return I->getOperand(0);
8118     
8119     // Otherwise, must be the same type of cast, so just reinsert a new one.
8120     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8121                            Ty);
8122     break;
8123   case Instruction::Select: {
8124     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8125     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8126     Res = SelectInst::Create(I->getOperand(0), True, False);
8127     break;
8128   }
8129   case Instruction::PHI: {
8130     PHINode *OPN = cast<PHINode>(I);
8131     PHINode *NPN = PHINode::Create(Ty);
8132     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8133       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8134       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8135     }
8136     Res = NPN;
8137     break;
8138   }
8139   default: 
8140     // TODO: Can handle more cases here.
8141     llvm_unreachable("Unreachable!");
8142     break;
8143   }
8144   
8145   Res->takeName(I);
8146   return InsertNewInstBefore(Res, *I);
8147 }
8148
8149 /// @brief Implement the transforms common to all CastInst visitors.
8150 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8151   Value *Src = CI.getOperand(0);
8152
8153   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8154   // eliminate it now.
8155   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8156     if (Instruction::CastOps opc = 
8157         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8158       // The first cast (CSrc) is eliminable so we need to fix up or replace
8159       // the second cast (CI). CSrc will then have a good chance of being dead.
8160       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8161     }
8162   }
8163
8164   // If we are casting a select then fold the cast into the select
8165   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8166     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8167       return NV;
8168
8169   // If we are casting a PHI then fold the cast into the PHI
8170   if (isa<PHINode>(Src))
8171     if (Instruction *NV = FoldOpIntoPhi(CI))
8172       return NV;
8173   
8174   return 0;
8175 }
8176
8177 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8178 /// or not there is a sequence of GEP indices into the type that will land us at
8179 /// the specified offset.  If so, fill them into NewIndices and return the
8180 /// resultant element type, otherwise return null.
8181 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8182                                        SmallVectorImpl<Value*> &NewIndices,
8183                                        const TargetData *TD,
8184                                        LLVMContext *Context) {
8185   if (!TD) return 0;
8186   if (!Ty->isSized()) return 0;
8187   
8188   // Start with the index over the outer type.  Note that the type size
8189   // might be zero (even if the offset isn't zero) if the indexed type
8190   // is something like [0 x {int, int}]
8191   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8192   int64_t FirstIdx = 0;
8193   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8194     FirstIdx = Offset/TySize;
8195     Offset -= FirstIdx*TySize;
8196     
8197     // Handle hosts where % returns negative instead of values [0..TySize).
8198     if (Offset < 0) {
8199       --FirstIdx;
8200       Offset += TySize;
8201       assert(Offset >= 0);
8202     }
8203     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8204   }
8205   
8206   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8207     
8208   // Index into the types.  If we fail, set OrigBase to null.
8209   while (Offset) {
8210     // Indexing into tail padding between struct/array elements.
8211     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8212       return 0;
8213     
8214     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8215       const StructLayout *SL = TD->getStructLayout(STy);
8216       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8217              "Offset must stay within the indexed type");
8218       
8219       unsigned Elt = SL->getElementContainingOffset(Offset);
8220       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8221       
8222       Offset -= SL->getElementOffset(Elt);
8223       Ty = STy->getElementType(Elt);
8224     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8225       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8226       assert(EltSize && "Cannot index into a zero-sized array");
8227       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8228       Offset %= EltSize;
8229       Ty = AT->getElementType();
8230     } else {
8231       // Otherwise, we can't index into the middle of this atomic type, bail.
8232       return 0;
8233     }
8234   }
8235   
8236   return Ty;
8237 }
8238
8239 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8240 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8241   Value *Src = CI.getOperand(0);
8242   
8243   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8244     // If casting the result of a getelementptr instruction with no offset, turn
8245     // this into a cast of the original pointer!
8246     if (GEP->hasAllZeroIndices()) {
8247       // Changing the cast operand is usually not a good idea but it is safe
8248       // here because the pointer operand is being replaced with another 
8249       // pointer operand so the opcode doesn't need to change.
8250       Worklist.Add(GEP);
8251       CI.setOperand(0, GEP->getOperand(0));
8252       return &CI;
8253     }
8254     
8255     // If the GEP has a single use, and the base pointer is a bitcast, and the
8256     // GEP computes a constant offset, see if we can convert these three
8257     // instructions into fewer.  This typically happens with unions and other
8258     // non-type-safe code.
8259     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8260       if (GEP->hasAllConstantIndices()) {
8261         // We are guaranteed to get a constant from EmitGEPOffset.
8262         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
8263         int64_t Offset = OffsetV->getSExtValue();
8264         
8265         // Get the base pointer input of the bitcast, and the type it points to.
8266         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8267         const Type *GEPIdxTy =
8268           cast<PointerType>(OrigBase->getType())->getElementType();
8269         SmallVector<Value*, 8> NewIndices;
8270         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8271           // If we were able to index down into an element, create the GEP
8272           // and bitcast the result.  This eliminates one bitcast, potentially
8273           // two.
8274           Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8275             Builder->CreateInBoundsGEP(OrigBase,
8276                                        NewIndices.begin(), NewIndices.end()) :
8277             Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8278           NGEP->takeName(GEP);
8279           
8280           if (isa<BitCastInst>(CI))
8281             return new BitCastInst(NGEP, CI.getType());
8282           assert(isa<PtrToIntInst>(CI));
8283           return new PtrToIntInst(NGEP, CI.getType());
8284         }
8285       }      
8286     }
8287   }
8288     
8289   return commonCastTransforms(CI);
8290 }
8291
8292 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8293 /// type like i42.  We don't want to introduce operations on random non-legal
8294 /// integer types where they don't already exist in the code.  In the future,
8295 /// we should consider making this based off target-data, so that 32-bit targets
8296 /// won't get i64 operations etc.
8297 static bool isSafeIntegerType(const Type *Ty) {
8298   switch (Ty->getPrimitiveSizeInBits()) {
8299   case 8:
8300   case 16:
8301   case 32:
8302   case 64:
8303     return true;
8304   default: 
8305     return false;
8306   }
8307 }
8308
8309 /// commonIntCastTransforms - This function implements the common transforms
8310 /// for trunc, zext, and sext.
8311 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8312   if (Instruction *Result = commonCastTransforms(CI))
8313     return Result;
8314
8315   Value *Src = CI.getOperand(0);
8316   const Type *SrcTy = Src->getType();
8317   const Type *DestTy = CI.getType();
8318   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8319   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8320
8321   // See if we can simplify any instructions used by the LHS whose sole 
8322   // purpose is to compute bits we don't care about.
8323   if (SimplifyDemandedInstructionBits(CI))
8324     return &CI;
8325
8326   // If the source isn't an instruction or has more than one use then we
8327   // can't do anything more. 
8328   Instruction *SrcI = dyn_cast<Instruction>(Src);
8329   if (!SrcI || !Src->hasOneUse())
8330     return 0;
8331
8332   // Attempt to propagate the cast into the instruction for int->int casts.
8333   int NumCastsRemoved = 0;
8334   // Only do this if the dest type is a simple type, don't convert the
8335   // expression tree to something weird like i93 unless the source is also
8336   // strange.
8337   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8338        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8339       CanEvaluateInDifferentType(SrcI, DestTy,
8340                                  CI.getOpcode(), NumCastsRemoved)) {
8341     // If this cast is a truncate, evaluting in a different type always
8342     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8343     // we need to do an AND to maintain the clear top-part of the computation,
8344     // so we require that the input have eliminated at least one cast.  If this
8345     // is a sign extension, we insert two new casts (to do the extension) so we
8346     // require that two casts have been eliminated.
8347     bool DoXForm = false;
8348     bool JustReplace = false;
8349     switch (CI.getOpcode()) {
8350     default:
8351       // All the others use floating point so we shouldn't actually 
8352       // get here because of the check above.
8353       llvm_unreachable("Unknown cast type");
8354     case Instruction::Trunc:
8355       DoXForm = true;
8356       break;
8357     case Instruction::ZExt: {
8358       DoXForm = NumCastsRemoved >= 1;
8359       if (!DoXForm && 0) {
8360         // If it's unnecessary to issue an AND to clear the high bits, it's
8361         // always profitable to do this xform.
8362         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8363         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8364         if (MaskedValueIsZero(TryRes, Mask))
8365           return ReplaceInstUsesWith(CI, TryRes);
8366         
8367         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8368           if (TryI->use_empty())
8369             EraseInstFromFunction(*TryI);
8370       }
8371       break;
8372     }
8373     case Instruction::SExt: {
8374       DoXForm = NumCastsRemoved >= 2;
8375       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8376         // If we do not have to emit the truncate + sext pair, then it's always
8377         // profitable to do this xform.
8378         //
8379         // It's not safe to eliminate the trunc + sext pair if one of the
8380         // eliminated cast is a truncate. e.g.
8381         // t2 = trunc i32 t1 to i16
8382         // t3 = sext i16 t2 to i32
8383         // !=
8384         // i32 t1
8385         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8386         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8387         if (NumSignBits > (DestBitSize - SrcBitSize))
8388           return ReplaceInstUsesWith(CI, TryRes);
8389         
8390         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8391           if (TryI->use_empty())
8392             EraseInstFromFunction(*TryI);
8393       }
8394       break;
8395     }
8396     }
8397     
8398     if (DoXForm) {
8399       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8400             " to avoid cast: " << CI);
8401       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8402                                            CI.getOpcode() == Instruction::SExt);
8403       if (JustReplace)
8404         // Just replace this cast with the result.
8405         return ReplaceInstUsesWith(CI, Res);
8406
8407       assert(Res->getType() == DestTy);
8408       switch (CI.getOpcode()) {
8409       default: llvm_unreachable("Unknown cast type!");
8410       case Instruction::Trunc:
8411         // Just replace this cast with the result.
8412         return ReplaceInstUsesWith(CI, Res);
8413       case Instruction::ZExt: {
8414         assert(SrcBitSize < DestBitSize && "Not a zext?");
8415
8416         // If the high bits are already zero, just replace this cast with the
8417         // result.
8418         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8419         if (MaskedValueIsZero(Res, Mask))
8420           return ReplaceInstUsesWith(CI, Res);
8421
8422         // We need to emit an AND to clear the high bits.
8423         Constant *C = ConstantInt::get(*Context, 
8424                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8425         return BinaryOperator::CreateAnd(Res, C);
8426       }
8427       case Instruction::SExt: {
8428         // If the high bits are already filled with sign bit, just replace this
8429         // cast with the result.
8430         unsigned NumSignBits = ComputeNumSignBits(Res);
8431         if (NumSignBits > (DestBitSize - SrcBitSize))
8432           return ReplaceInstUsesWith(CI, Res);
8433
8434         // We need to emit a cast to truncate, then a cast to sext.
8435         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8436       }
8437       }
8438     }
8439   }
8440   
8441   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8442   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8443
8444   switch (SrcI->getOpcode()) {
8445   case Instruction::Add:
8446   case Instruction::Mul:
8447   case Instruction::And:
8448   case Instruction::Or:
8449   case Instruction::Xor:
8450     // If we are discarding information, rewrite.
8451     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8452       // Don't insert two casts unless at least one can be eliminated.
8453       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8454           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8455         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8456         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8457         return BinaryOperator::Create(
8458             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8459       }
8460     }
8461
8462     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8463     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8464         SrcI->getOpcode() == Instruction::Xor &&
8465         Op1 == ConstantInt::getTrue(*Context) &&
8466         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8467       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8468       return BinaryOperator::CreateXor(New,
8469                                       ConstantInt::get(CI.getType(), 1));
8470     }
8471     break;
8472
8473   case Instruction::Shl: {
8474     // Canonicalize trunc inside shl, if we can.
8475     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8476     if (CI && DestBitSize < SrcBitSize &&
8477         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8478       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8479       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8480       return BinaryOperator::CreateShl(Op0c, Op1c);
8481     }
8482     break;
8483   }
8484   }
8485   return 0;
8486 }
8487
8488 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8489   if (Instruction *Result = commonIntCastTransforms(CI))
8490     return Result;
8491   
8492   Value *Src = CI.getOperand(0);
8493   const Type *Ty = CI.getType();
8494   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8495   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8496
8497   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8498   if (DestBitWidth == 1) {
8499     Constant *One = ConstantInt::get(Src->getType(), 1);
8500     Src = Builder->CreateAnd(Src, One, "tmp");
8501     Value *Zero = Constant::getNullValue(Src->getType());
8502     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8503   }
8504
8505   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8506   ConstantInt *ShAmtV = 0;
8507   Value *ShiftOp = 0;
8508   if (Src->hasOneUse() &&
8509       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8510     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8511     
8512     // Get a mask for the bits shifting in.
8513     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8514     if (MaskedValueIsZero(ShiftOp, Mask)) {
8515       if (ShAmt >= DestBitWidth)        // All zeros.
8516         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8517       
8518       // Okay, we can shrink this.  Truncate the input, then return a new
8519       // shift.
8520       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8521       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8522       return BinaryOperator::CreateLShr(V1, V2);
8523     }
8524   }
8525   
8526   return 0;
8527 }
8528
8529 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8530 /// in order to eliminate the icmp.
8531 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8532                                              bool DoXform) {
8533   // If we are just checking for a icmp eq of a single bit and zext'ing it
8534   // to an integer, then shift the bit to the appropriate place and then
8535   // cast to integer to avoid the comparison.
8536   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8537     const APInt &Op1CV = Op1C->getValue();
8538       
8539     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8540     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8541     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8542         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8543       if (!DoXform) return ICI;
8544
8545       Value *In = ICI->getOperand(0);
8546       Value *Sh = ConstantInt::get(In->getType(),
8547                                    In->getType()->getScalarSizeInBits()-1);
8548       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8549       if (In->getType() != CI.getType())
8550         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8551
8552       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8553         Constant *One = ConstantInt::get(In->getType(), 1);
8554         In = Builder->CreateXor(In, One, In->getName()+".not");
8555       }
8556
8557       return ReplaceInstUsesWith(CI, In);
8558     }
8559       
8560       
8561       
8562     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8563     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8564     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8565     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8566     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8567     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8568     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8569     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8570     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8571         // This only works for EQ and NE
8572         ICI->isEquality()) {
8573       // If Op1C some other power of two, convert:
8574       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8575       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8576       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8577       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8578         
8579       APInt KnownZeroMask(~KnownZero);
8580       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8581         if (!DoXform) return ICI;
8582
8583         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8584         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8585           // (X&4) == 2 --> false
8586           // (X&4) != 2 --> true
8587           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8588           Res = ConstantExpr::getZExt(Res, CI.getType());
8589           return ReplaceInstUsesWith(CI, Res);
8590         }
8591           
8592         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8593         Value *In = ICI->getOperand(0);
8594         if (ShiftAmt) {
8595           // Perform a logical shr by shiftamt.
8596           // Insert the shift to put the result in the low bit.
8597           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8598                                    In->getName()+".lobit");
8599         }
8600           
8601         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8602           Constant *One = ConstantInt::get(In->getType(), 1);
8603           In = Builder->CreateXor(In, One, "tmp");
8604         }
8605           
8606         if (CI.getType() == In->getType())
8607           return ReplaceInstUsesWith(CI, In);
8608         else
8609           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8610       }
8611     }
8612   }
8613
8614   return 0;
8615 }
8616
8617 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8618   // If one of the common conversion will work ..
8619   if (Instruction *Result = commonIntCastTransforms(CI))
8620     return Result;
8621
8622   Value *Src = CI.getOperand(0);
8623
8624   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8625   // types and if the sizes are just right we can convert this into a logical
8626   // 'and' which will be much cheaper than the pair of casts.
8627   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8628     // Get the sizes of the types involved.  We know that the intermediate type
8629     // will be smaller than A or C, but don't know the relation between A and C.
8630     Value *A = CSrc->getOperand(0);
8631     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8632     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8633     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8634     // If we're actually extending zero bits, then if
8635     // SrcSize <  DstSize: zext(a & mask)
8636     // SrcSize == DstSize: a & mask
8637     // SrcSize  > DstSize: trunc(a) & mask
8638     if (SrcSize < DstSize) {
8639       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8640       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8641       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8642       return new ZExtInst(And, CI.getType());
8643     }
8644     
8645     if (SrcSize == DstSize) {
8646       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8647       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8648                                                            AndValue));
8649     }
8650     if (SrcSize > DstSize) {
8651       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8652       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8653       return BinaryOperator::CreateAnd(Trunc, 
8654                                        ConstantInt::get(Trunc->getType(),
8655                                                                AndValue));
8656     }
8657   }
8658
8659   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8660     return transformZExtICmp(ICI, CI);
8661
8662   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8663   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8664     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8665     // of the (zext icmp) will be transformed.
8666     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8667     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8668     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8669         (transformZExtICmp(LHS, CI, false) ||
8670          transformZExtICmp(RHS, CI, false))) {
8671       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8672       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8673       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8674     }
8675   }
8676
8677   // zext(trunc(t) & C) -> (t & zext(C)).
8678   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8679     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8680       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8681         Value *TI0 = TI->getOperand(0);
8682         if (TI0->getType() == CI.getType())
8683           return
8684             BinaryOperator::CreateAnd(TI0,
8685                                 ConstantExpr::getZExt(C, CI.getType()));
8686       }
8687
8688   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8689   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8690     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8691       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8692         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8693             And->getOperand(1) == C)
8694           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8695             Value *TI0 = TI->getOperand(0);
8696             if (TI0->getType() == CI.getType()) {
8697               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8698               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8699               return BinaryOperator::CreateXor(NewAnd, ZC);
8700             }
8701           }
8702
8703   return 0;
8704 }
8705
8706 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8707   if (Instruction *I = commonIntCastTransforms(CI))
8708     return I;
8709   
8710   Value *Src = CI.getOperand(0);
8711   
8712   // Canonicalize sign-extend from i1 to a select.
8713   if (Src->getType() == Type::getInt1Ty(*Context))
8714     return SelectInst::Create(Src,
8715                               Constant::getAllOnesValue(CI.getType()),
8716                               Constant::getNullValue(CI.getType()));
8717
8718   // See if the value being truncated is already sign extended.  If so, just
8719   // eliminate the trunc/sext pair.
8720   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8721     Value *Op = cast<User>(Src)->getOperand(0);
8722     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8723     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8724     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8725     unsigned NumSignBits = ComputeNumSignBits(Op);
8726
8727     if (OpBits == DestBits) {
8728       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8729       // bits, it is already ready.
8730       if (NumSignBits > DestBits-MidBits)
8731         return ReplaceInstUsesWith(CI, Op);
8732     } else if (OpBits < DestBits) {
8733       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8734       // bits, just sext from i32.
8735       if (NumSignBits > OpBits-MidBits)
8736         return new SExtInst(Op, CI.getType(), "tmp");
8737     } else {
8738       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8739       // bits, just truncate to i32.
8740       if (NumSignBits > OpBits-MidBits)
8741         return new TruncInst(Op, CI.getType(), "tmp");
8742     }
8743   }
8744
8745   // If the input is a shl/ashr pair of a same constant, then this is a sign
8746   // extension from a smaller value.  If we could trust arbitrary bitwidth
8747   // integers, we could turn this into a truncate to the smaller bit and then
8748   // use a sext for the whole extension.  Since we don't, look deeper and check
8749   // for a truncate.  If the source and dest are the same type, eliminate the
8750   // trunc and extend and just do shifts.  For example, turn:
8751   //   %a = trunc i32 %i to i8
8752   //   %b = shl i8 %a, 6
8753   //   %c = ashr i8 %b, 6
8754   //   %d = sext i8 %c to i32
8755   // into:
8756   //   %a = shl i32 %i, 30
8757   //   %d = ashr i32 %a, 30
8758   Value *A = 0;
8759   ConstantInt *BA = 0, *CA = 0;
8760   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8761                         m_ConstantInt(CA))) &&
8762       BA == CA && isa<TruncInst>(A)) {
8763     Value *I = cast<TruncInst>(A)->getOperand(0);
8764     if (I->getType() == CI.getType()) {
8765       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8766       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8767       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8768       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8769       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8770       return BinaryOperator::CreateAShr(I, ShAmtV);
8771     }
8772   }
8773   
8774   return 0;
8775 }
8776
8777 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8778 /// in the specified FP type without changing its value.
8779 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8780                               LLVMContext *Context) {
8781   bool losesInfo;
8782   APFloat F = CFP->getValueAPF();
8783   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8784   if (!losesInfo)
8785     return ConstantFP::get(*Context, F);
8786   return 0;
8787 }
8788
8789 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8790 /// through it until we get the source value.
8791 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8792   if (Instruction *I = dyn_cast<Instruction>(V))
8793     if (I->getOpcode() == Instruction::FPExt)
8794       return LookThroughFPExtensions(I->getOperand(0), Context);
8795   
8796   // If this value is a constant, return the constant in the smallest FP type
8797   // that can accurately represent it.  This allows us to turn
8798   // (float)((double)X+2.0) into x+2.0f.
8799   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8800     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8801       return V;  // No constant folding of this.
8802     // See if the value can be truncated to float and then reextended.
8803     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8804       return V;
8805     if (CFP->getType() == Type::getDoubleTy(*Context))
8806       return V;  // Won't shrink.
8807     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8808       return V;
8809     // Don't try to shrink to various long double types.
8810   }
8811   
8812   return V;
8813 }
8814
8815 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8816   if (Instruction *I = commonCastTransforms(CI))
8817     return I;
8818   
8819   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8820   // smaller than the destination type, we can eliminate the truncate by doing
8821   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8822   // many builtins (sqrt, etc).
8823   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8824   if (OpI && OpI->hasOneUse()) {
8825     switch (OpI->getOpcode()) {
8826     default: break;
8827     case Instruction::FAdd:
8828     case Instruction::FSub:
8829     case Instruction::FMul:
8830     case Instruction::FDiv:
8831     case Instruction::FRem:
8832       const Type *SrcTy = OpI->getType();
8833       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8834       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8835       if (LHSTrunc->getType() != SrcTy && 
8836           RHSTrunc->getType() != SrcTy) {
8837         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8838         // If the source types were both smaller than the destination type of
8839         // the cast, do this xform.
8840         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8841             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8842           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8843           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8844           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8845         }
8846       }
8847       break;  
8848     }
8849   }
8850   return 0;
8851 }
8852
8853 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8854   return commonCastTransforms(CI);
8855 }
8856
8857 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8858   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8859   if (OpI == 0)
8860     return commonCastTransforms(FI);
8861
8862   // fptoui(uitofp(X)) --> X
8863   // fptoui(sitofp(X)) --> X
8864   // This is safe if the intermediate type has enough bits in its mantissa to
8865   // accurately represent all values of X.  For example, do not do this with
8866   // i64->float->i64.  This is also safe for sitofp case, because any negative
8867   // 'X' value would cause an undefined result for the fptoui. 
8868   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8869       OpI->getOperand(0)->getType() == FI.getType() &&
8870       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8871                     OpI->getType()->getFPMantissaWidth())
8872     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8873
8874   return commonCastTransforms(FI);
8875 }
8876
8877 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8878   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8879   if (OpI == 0)
8880     return commonCastTransforms(FI);
8881   
8882   // fptosi(sitofp(X)) --> X
8883   // fptosi(uitofp(X)) --> X
8884   // This is safe if the intermediate type has enough bits in its mantissa to
8885   // accurately represent all values of X.  For example, do not do this with
8886   // i64->float->i64.  This is also safe for sitofp case, because any negative
8887   // 'X' value would cause an undefined result for the fptoui. 
8888   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8889       OpI->getOperand(0)->getType() == FI.getType() &&
8890       (int)FI.getType()->getScalarSizeInBits() <=
8891                     OpI->getType()->getFPMantissaWidth())
8892     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8893   
8894   return commonCastTransforms(FI);
8895 }
8896
8897 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8898   return commonCastTransforms(CI);
8899 }
8900
8901 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8902   return commonCastTransforms(CI);
8903 }
8904
8905 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8906   // If the destination integer type is smaller than the intptr_t type for
8907   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8908   // trunc to be exposed to other transforms.  Don't do this for extending
8909   // ptrtoint's, because we don't know if the target sign or zero extends its
8910   // pointers.
8911   if (TD &&
8912       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8913     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8914                                        TD->getIntPtrType(CI.getContext()),
8915                                        "tmp");
8916     return new TruncInst(P, CI.getType());
8917   }
8918   
8919   return commonPointerCastTransforms(CI);
8920 }
8921
8922 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8923   // If the source integer type is larger than the intptr_t type for
8924   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8925   // allows the trunc to be exposed to other transforms.  Don't do this for
8926   // extending inttoptr's, because we don't know if the target sign or zero
8927   // extends to pointers.
8928   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8929       TD->getPointerSizeInBits()) {
8930     Value *P = Builder->CreateTrunc(CI.getOperand(0),
8931                                     TD->getIntPtrType(CI.getContext()), "tmp");
8932     return new IntToPtrInst(P, CI.getType());
8933   }
8934   
8935   if (Instruction *I = commonCastTransforms(CI))
8936     return I;
8937
8938   return 0;
8939 }
8940
8941 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8942   // If the operands are integer typed then apply the integer transforms,
8943   // otherwise just apply the common ones.
8944   Value *Src = CI.getOperand(0);
8945   const Type *SrcTy = Src->getType();
8946   const Type *DestTy = CI.getType();
8947
8948   if (isa<PointerType>(SrcTy)) {
8949     if (Instruction *I = commonPointerCastTransforms(CI))
8950       return I;
8951   } else {
8952     if (Instruction *Result = commonCastTransforms(CI))
8953       return Result;
8954   }
8955
8956
8957   // Get rid of casts from one type to the same type. These are useless and can
8958   // be replaced by the operand.
8959   if (DestTy == Src->getType())
8960     return ReplaceInstUsesWith(CI, Src);
8961
8962   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8963     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8964     const Type *DstElTy = DstPTy->getElementType();
8965     const Type *SrcElTy = SrcPTy->getElementType();
8966     
8967     // If the address spaces don't match, don't eliminate the bitcast, which is
8968     // required for changing types.
8969     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8970       return 0;
8971     
8972     // If we are casting a alloca to a pointer to a type of the same
8973     // size, rewrite the allocation instruction to allocate the "right" type.
8974     // There is no need to modify malloc calls because it is their bitcast that
8975     // needs to be cleaned up.
8976     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
8977       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8978         return V;
8979     
8980     // If the source and destination are pointers, and this cast is equivalent
8981     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8982     // This can enhance SROA and other transforms that want type-safe pointers.
8983     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8984     unsigned NumZeros = 0;
8985     while (SrcElTy != DstElTy && 
8986            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8987            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8988       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8989       ++NumZeros;
8990     }
8991
8992     // If we found a path from the src to dest, create the getelementptr now.
8993     if (SrcElTy == DstElTy) {
8994       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8995       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8996                                                ((Instruction*) NULL));
8997     }
8998   }
8999
9000   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9001     if (DestVTy->getNumElements() == 1) {
9002       if (!isa<VectorType>(SrcTy)) {
9003         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
9004         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
9005                             Constant::getNullValue(Type::getInt32Ty(*Context)));
9006       }
9007       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9008     }
9009   }
9010
9011   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9012     if (SrcVTy->getNumElements() == 1) {
9013       if (!isa<VectorType>(DestTy)) {
9014         Value *Elem = 
9015           Builder->CreateExtractElement(Src,
9016                             Constant::getNullValue(Type::getInt32Ty(*Context)));
9017         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9018       }
9019     }
9020   }
9021
9022   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9023     if (SVI->hasOneUse()) {
9024       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9025       // a bitconvert to a vector with the same # elts.
9026       if (isa<VectorType>(DestTy) && 
9027           cast<VectorType>(DestTy)->getNumElements() ==
9028                 SVI->getType()->getNumElements() &&
9029           SVI->getType()->getNumElements() ==
9030             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9031         CastInst *Tmp;
9032         // If either of the operands is a cast from CI.getType(), then
9033         // evaluating the shuffle in the casted destination's type will allow
9034         // us to eliminate at least one cast.
9035         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9036              Tmp->getOperand(0)->getType() == DestTy) ||
9037             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9038              Tmp->getOperand(0)->getType() == DestTy)) {
9039           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9040           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
9041           // Return a new shuffle vector.  Use the same element ID's, as we
9042           // know the vector types match #elts.
9043           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9044         }
9045       }
9046     }
9047   }
9048   return 0;
9049 }
9050
9051 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9052 ///   %C = or %A, %B
9053 ///   %D = select %cond, %C, %A
9054 /// into:
9055 ///   %C = select %cond, %B, 0
9056 ///   %D = or %A, %C
9057 ///
9058 /// Assuming that the specified instruction is an operand to the select, return
9059 /// a bitmask indicating which operands of this instruction are foldable if they
9060 /// equal the other incoming value of the select.
9061 ///
9062 static unsigned GetSelectFoldableOperands(Instruction *I) {
9063   switch (I->getOpcode()) {
9064   case Instruction::Add:
9065   case Instruction::Mul:
9066   case Instruction::And:
9067   case Instruction::Or:
9068   case Instruction::Xor:
9069     return 3;              // Can fold through either operand.
9070   case Instruction::Sub:   // Can only fold on the amount subtracted.
9071   case Instruction::Shl:   // Can only fold on the shift amount.
9072   case Instruction::LShr:
9073   case Instruction::AShr:
9074     return 1;
9075   default:
9076     return 0;              // Cannot fold
9077   }
9078 }
9079
9080 /// GetSelectFoldableConstant - For the same transformation as the previous
9081 /// function, return the identity constant that goes into the select.
9082 static Constant *GetSelectFoldableConstant(Instruction *I,
9083                                            LLVMContext *Context) {
9084   switch (I->getOpcode()) {
9085   default: llvm_unreachable("This cannot happen!");
9086   case Instruction::Add:
9087   case Instruction::Sub:
9088   case Instruction::Or:
9089   case Instruction::Xor:
9090   case Instruction::Shl:
9091   case Instruction::LShr:
9092   case Instruction::AShr:
9093     return Constant::getNullValue(I->getType());
9094   case Instruction::And:
9095     return Constant::getAllOnesValue(I->getType());
9096   case Instruction::Mul:
9097     return ConstantInt::get(I->getType(), 1);
9098   }
9099 }
9100
9101 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9102 /// have the same opcode and only one use each.  Try to simplify this.
9103 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9104                                           Instruction *FI) {
9105   if (TI->getNumOperands() == 1) {
9106     // If this is a non-volatile load or a cast from the same type,
9107     // merge.
9108     if (TI->isCast()) {
9109       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9110         return 0;
9111     } else {
9112       return 0;  // unknown unary op.
9113     }
9114
9115     // Fold this by inserting a select from the input values.
9116     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9117                                           FI->getOperand(0), SI.getName()+".v");
9118     InsertNewInstBefore(NewSI, SI);
9119     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9120                             TI->getType());
9121   }
9122
9123   // Only handle binary operators here.
9124   if (!isa<BinaryOperator>(TI))
9125     return 0;
9126
9127   // Figure out if the operations have any operands in common.
9128   Value *MatchOp, *OtherOpT, *OtherOpF;
9129   bool MatchIsOpZero;
9130   if (TI->getOperand(0) == FI->getOperand(0)) {
9131     MatchOp  = TI->getOperand(0);
9132     OtherOpT = TI->getOperand(1);
9133     OtherOpF = FI->getOperand(1);
9134     MatchIsOpZero = true;
9135   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9136     MatchOp  = TI->getOperand(1);
9137     OtherOpT = TI->getOperand(0);
9138     OtherOpF = FI->getOperand(0);
9139     MatchIsOpZero = false;
9140   } else if (!TI->isCommutative()) {
9141     return 0;
9142   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9143     MatchOp  = TI->getOperand(0);
9144     OtherOpT = TI->getOperand(1);
9145     OtherOpF = FI->getOperand(0);
9146     MatchIsOpZero = true;
9147   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9148     MatchOp  = TI->getOperand(1);
9149     OtherOpT = TI->getOperand(0);
9150     OtherOpF = FI->getOperand(1);
9151     MatchIsOpZero = true;
9152   } else {
9153     return 0;
9154   }
9155
9156   // If we reach here, they do have operations in common.
9157   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9158                                          OtherOpF, SI.getName()+".v");
9159   InsertNewInstBefore(NewSI, SI);
9160
9161   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9162     if (MatchIsOpZero)
9163       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9164     else
9165       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9166   }
9167   llvm_unreachable("Shouldn't get here");
9168   return 0;
9169 }
9170
9171 static bool isSelect01(Constant *C1, Constant *C2) {
9172   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9173   if (!C1I)
9174     return false;
9175   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9176   if (!C2I)
9177     return false;
9178   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9179 }
9180
9181 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9182 /// facilitate further optimization.
9183 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9184                                             Value *FalseVal) {
9185   // See the comment above GetSelectFoldableOperands for a description of the
9186   // transformation we are doing here.
9187   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9188     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9189         !isa<Constant>(FalseVal)) {
9190       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9191         unsigned OpToFold = 0;
9192         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9193           OpToFold = 1;
9194         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9195           OpToFold = 2;
9196         }
9197
9198         if (OpToFold) {
9199           Constant *C = GetSelectFoldableConstant(TVI, Context);
9200           Value *OOp = TVI->getOperand(2-OpToFold);
9201           // Avoid creating select between 2 constants unless it's selecting
9202           // between 0 and 1.
9203           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9204             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9205             InsertNewInstBefore(NewSel, SI);
9206             NewSel->takeName(TVI);
9207             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9208               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9209             llvm_unreachable("Unknown instruction!!");
9210           }
9211         }
9212       }
9213     }
9214   }
9215
9216   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9217     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9218         !isa<Constant>(TrueVal)) {
9219       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9220         unsigned OpToFold = 0;
9221         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9222           OpToFold = 1;
9223         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9224           OpToFold = 2;
9225         }
9226
9227         if (OpToFold) {
9228           Constant *C = GetSelectFoldableConstant(FVI, Context);
9229           Value *OOp = FVI->getOperand(2-OpToFold);
9230           // Avoid creating select between 2 constants unless it's selecting
9231           // between 0 and 1.
9232           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9233             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9234             InsertNewInstBefore(NewSel, SI);
9235             NewSel->takeName(FVI);
9236             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9237               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9238             llvm_unreachable("Unknown instruction!!");
9239           }
9240         }
9241       }
9242     }
9243   }
9244
9245   return 0;
9246 }
9247
9248 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9249 /// ICmpInst as its first operand.
9250 ///
9251 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9252                                                    ICmpInst *ICI) {
9253   bool Changed = false;
9254   ICmpInst::Predicate Pred = ICI->getPredicate();
9255   Value *CmpLHS = ICI->getOperand(0);
9256   Value *CmpRHS = ICI->getOperand(1);
9257   Value *TrueVal = SI.getTrueValue();
9258   Value *FalseVal = SI.getFalseValue();
9259
9260   // Check cases where the comparison is with a constant that
9261   // can be adjusted to fit the min/max idiom. We may edit ICI in
9262   // place here, so make sure the select is the only user.
9263   if (ICI->hasOneUse())
9264     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9265       switch (Pred) {
9266       default: break;
9267       case ICmpInst::ICMP_ULT:
9268       case ICmpInst::ICMP_SLT: {
9269         // X < MIN ? T : F  -->  F
9270         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9271           return ReplaceInstUsesWith(SI, FalseVal);
9272         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9273         Constant *AdjustedRHS = SubOne(CI);
9274         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9275             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9276           Pred = ICmpInst::getSwappedPredicate(Pred);
9277           CmpRHS = AdjustedRHS;
9278           std::swap(FalseVal, TrueVal);
9279           ICI->setPredicate(Pred);
9280           ICI->setOperand(1, CmpRHS);
9281           SI.setOperand(1, TrueVal);
9282           SI.setOperand(2, FalseVal);
9283           Changed = true;
9284         }
9285         break;
9286       }
9287       case ICmpInst::ICMP_UGT:
9288       case ICmpInst::ICMP_SGT: {
9289         // X > MAX ? T : F  -->  F
9290         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9291           return ReplaceInstUsesWith(SI, FalseVal);
9292         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9293         Constant *AdjustedRHS = AddOne(CI);
9294         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9295             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9296           Pred = ICmpInst::getSwappedPredicate(Pred);
9297           CmpRHS = AdjustedRHS;
9298           std::swap(FalseVal, TrueVal);
9299           ICI->setPredicate(Pred);
9300           ICI->setOperand(1, CmpRHS);
9301           SI.setOperand(1, TrueVal);
9302           SI.setOperand(2, FalseVal);
9303           Changed = true;
9304         }
9305         break;
9306       }
9307       }
9308
9309       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9310       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9311       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9312       if (match(TrueVal, m_ConstantInt<-1>()) &&
9313           match(FalseVal, m_ConstantInt<0>()))
9314         Pred = ICI->getPredicate();
9315       else if (match(TrueVal, m_ConstantInt<0>()) &&
9316                match(FalseVal, m_ConstantInt<-1>()))
9317         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9318       
9319       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9320         // If we are just checking for a icmp eq of a single bit and zext'ing it
9321         // to an integer, then shift the bit to the appropriate place and then
9322         // cast to integer to avoid the comparison.
9323         const APInt &Op1CV = CI->getValue();
9324     
9325         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9326         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9327         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9328             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9329           Value *In = ICI->getOperand(0);
9330           Value *Sh = ConstantInt::get(In->getType(),
9331                                        In->getType()->getScalarSizeInBits()-1);
9332           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9333                                                         In->getName()+".lobit"),
9334                                    *ICI);
9335           if (In->getType() != SI.getType())
9336             In = CastInst::CreateIntegerCast(In, SI.getType(),
9337                                              true/*SExt*/, "tmp", ICI);
9338     
9339           if (Pred == ICmpInst::ICMP_SGT)
9340             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9341                                        In->getName()+".not"), *ICI);
9342     
9343           return ReplaceInstUsesWith(SI, In);
9344         }
9345       }
9346     }
9347
9348   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9349     // Transform (X == Y) ? X : Y  -> Y
9350     if (Pred == ICmpInst::ICMP_EQ)
9351       return ReplaceInstUsesWith(SI, FalseVal);
9352     // Transform (X != Y) ? X : Y  -> X
9353     if (Pred == ICmpInst::ICMP_NE)
9354       return ReplaceInstUsesWith(SI, TrueVal);
9355     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9356
9357   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9358     // Transform (X == Y) ? Y : X  -> X
9359     if (Pred == ICmpInst::ICMP_EQ)
9360       return ReplaceInstUsesWith(SI, FalseVal);
9361     // Transform (X != Y) ? Y : X  -> Y
9362     if (Pred == ICmpInst::ICMP_NE)
9363       return ReplaceInstUsesWith(SI, TrueVal);
9364     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9365   }
9366
9367   /// NOTE: if we wanted to, this is where to detect integer ABS
9368
9369   return Changed ? &SI : 0;
9370 }
9371
9372
9373 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9374 /// PHI node (but the two may be in different blocks).  See if the true/false
9375 /// values (V) are live in all of the predecessor blocks of the PHI.  For
9376 /// example, cases like this cannot be mapped:
9377 ///
9378 ///   X = phi [ C1, BB1], [C2, BB2]
9379 ///   Y = add
9380 ///   Z = select X, Y, 0
9381 ///
9382 /// because Y is not live in BB1/BB2.
9383 ///
9384 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9385                                                    const SelectInst &SI) {
9386   // If the value is a non-instruction value like a constant or argument, it
9387   // can always be mapped.
9388   const Instruction *I = dyn_cast<Instruction>(V);
9389   if (I == 0) return true;
9390   
9391   // If V is a PHI node defined in the same block as the condition PHI, we can
9392   // map the arguments.
9393   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9394   
9395   if (const PHINode *VP = dyn_cast<PHINode>(I))
9396     if (VP->getParent() == CondPHI->getParent())
9397       return true;
9398   
9399   // Otherwise, if the PHI and select are defined in the same block and if V is
9400   // defined in a different block, then we can transform it.
9401   if (SI.getParent() == CondPHI->getParent() &&
9402       I->getParent() != CondPHI->getParent())
9403     return true;
9404   
9405   // Otherwise we have a 'hard' case and we can't tell without doing more
9406   // detailed dominator based analysis, punt.
9407   return false;
9408 }
9409
9410 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9411   Value *CondVal = SI.getCondition();
9412   Value *TrueVal = SI.getTrueValue();
9413   Value *FalseVal = SI.getFalseValue();
9414
9415   // select true, X, Y  -> X
9416   // select false, X, Y -> Y
9417   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9418     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9419
9420   // select C, X, X -> X
9421   if (TrueVal == FalseVal)
9422     return ReplaceInstUsesWith(SI, TrueVal);
9423
9424   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9425     return ReplaceInstUsesWith(SI, FalseVal);
9426   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9427     return ReplaceInstUsesWith(SI, TrueVal);
9428   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9429     if (isa<Constant>(TrueVal))
9430       return ReplaceInstUsesWith(SI, TrueVal);
9431     else
9432       return ReplaceInstUsesWith(SI, FalseVal);
9433   }
9434
9435   if (SI.getType() == Type::getInt1Ty(*Context)) {
9436     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9437       if (C->getZExtValue()) {
9438         // Change: A = select B, true, C --> A = or B, C
9439         return BinaryOperator::CreateOr(CondVal, FalseVal);
9440       } else {
9441         // Change: A = select B, false, C --> A = and !B, C
9442         Value *NotCond =
9443           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9444                                              "not."+CondVal->getName()), SI);
9445         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9446       }
9447     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9448       if (C->getZExtValue() == false) {
9449         // Change: A = select B, C, false --> A = and B, C
9450         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9451       } else {
9452         // Change: A = select B, C, true --> A = or !B, C
9453         Value *NotCond =
9454           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9455                                              "not."+CondVal->getName()), SI);
9456         return BinaryOperator::CreateOr(NotCond, TrueVal);
9457       }
9458     }
9459     
9460     // select a, b, a  -> a&b
9461     // select a, a, b  -> a|b
9462     if (CondVal == TrueVal)
9463       return BinaryOperator::CreateOr(CondVal, FalseVal);
9464     else if (CondVal == FalseVal)
9465       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9466   }
9467
9468   // Selecting between two integer constants?
9469   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9470     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9471       // select C, 1, 0 -> zext C to int
9472       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9473         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9474       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9475         // select C, 0, 1 -> zext !C to int
9476         Value *NotCond =
9477           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9478                                                "not."+CondVal->getName()), SI);
9479         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9480       }
9481
9482       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9483         // If one of the constants is zero (we know they can't both be) and we
9484         // have an icmp instruction with zero, and we have an 'and' with the
9485         // non-constant value, eliminate this whole mess.  This corresponds to
9486         // cases like this: ((X & 27) ? 27 : 0)
9487         if (TrueValC->isZero() || FalseValC->isZero())
9488           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9489               cast<Constant>(IC->getOperand(1))->isNullValue())
9490             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9491               if (ICA->getOpcode() == Instruction::And &&
9492                   isa<ConstantInt>(ICA->getOperand(1)) &&
9493                   (ICA->getOperand(1) == TrueValC ||
9494                    ICA->getOperand(1) == FalseValC) &&
9495                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9496                 // Okay, now we know that everything is set up, we just don't
9497                 // know whether we have a icmp_ne or icmp_eq and whether the 
9498                 // true or false val is the zero.
9499                 bool ShouldNotVal = !TrueValC->isZero();
9500                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9501                 Value *V = ICA;
9502                 if (ShouldNotVal)
9503                   V = InsertNewInstBefore(BinaryOperator::Create(
9504                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9505                 return ReplaceInstUsesWith(SI, V);
9506               }
9507       }
9508     }
9509
9510   // See if we are selecting two values based on a comparison of the two values.
9511   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9512     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9513       // Transform (X == Y) ? X : Y  -> Y
9514       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9515         // This is not safe in general for floating point:  
9516         // consider X== -0, Y== +0.
9517         // It becomes safe if either operand is a nonzero constant.
9518         ConstantFP *CFPt, *CFPf;
9519         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9520               !CFPt->getValueAPF().isZero()) ||
9521             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9522              !CFPf->getValueAPF().isZero()))
9523         return ReplaceInstUsesWith(SI, FalseVal);
9524       }
9525       // Transform (X != Y) ? X : Y  -> X
9526       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9527         return ReplaceInstUsesWith(SI, TrueVal);
9528       // NOTE: if we wanted to, this is where to detect MIN/MAX
9529
9530     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9531       // Transform (X == Y) ? Y : X  -> X
9532       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9533         // This is not safe in general for floating point:  
9534         // consider X== -0, Y== +0.
9535         // It becomes safe if either operand is a nonzero constant.
9536         ConstantFP *CFPt, *CFPf;
9537         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9538               !CFPt->getValueAPF().isZero()) ||
9539             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9540              !CFPf->getValueAPF().isZero()))
9541           return ReplaceInstUsesWith(SI, FalseVal);
9542       }
9543       // Transform (X != Y) ? Y : X  -> Y
9544       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9545         return ReplaceInstUsesWith(SI, TrueVal);
9546       // NOTE: if we wanted to, this is where to detect MIN/MAX
9547     }
9548     // NOTE: if we wanted to, this is where to detect ABS
9549   }
9550
9551   // See if we are selecting two values based on a comparison of the two values.
9552   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9553     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9554       return Result;
9555
9556   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9557     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9558       if (TI->hasOneUse() && FI->hasOneUse()) {
9559         Instruction *AddOp = 0, *SubOp = 0;
9560
9561         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9562         if (TI->getOpcode() == FI->getOpcode())
9563           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9564             return IV;
9565
9566         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9567         // even legal for FP.
9568         if ((TI->getOpcode() == Instruction::Sub &&
9569              FI->getOpcode() == Instruction::Add) ||
9570             (TI->getOpcode() == Instruction::FSub &&
9571              FI->getOpcode() == Instruction::FAdd)) {
9572           AddOp = FI; SubOp = TI;
9573         } else if ((FI->getOpcode() == Instruction::Sub &&
9574                     TI->getOpcode() == Instruction::Add) ||
9575                    (FI->getOpcode() == Instruction::FSub &&
9576                     TI->getOpcode() == Instruction::FAdd)) {
9577           AddOp = TI; SubOp = FI;
9578         }
9579
9580         if (AddOp) {
9581           Value *OtherAddOp = 0;
9582           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9583             OtherAddOp = AddOp->getOperand(1);
9584           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9585             OtherAddOp = AddOp->getOperand(0);
9586           }
9587
9588           if (OtherAddOp) {
9589             // So at this point we know we have (Y -> OtherAddOp):
9590             //        select C, (add X, Y), (sub X, Z)
9591             Value *NegVal;  // Compute -Z
9592             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9593               NegVal = ConstantExpr::getNeg(C);
9594             } else {
9595               NegVal = InsertNewInstBefore(
9596                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9597                                               "tmp"), SI);
9598             }
9599
9600             Value *NewTrueOp = OtherAddOp;
9601             Value *NewFalseOp = NegVal;
9602             if (AddOp != TI)
9603               std::swap(NewTrueOp, NewFalseOp);
9604             Instruction *NewSel =
9605               SelectInst::Create(CondVal, NewTrueOp,
9606                                  NewFalseOp, SI.getName() + ".p");
9607
9608             NewSel = InsertNewInstBefore(NewSel, SI);
9609             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9610           }
9611         }
9612       }
9613
9614   // See if we can fold the select into one of our operands.
9615   if (SI.getType()->isInteger()) {
9616     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9617     if (FoldI)
9618       return FoldI;
9619   }
9620
9621   // See if we can fold the select into a phi node if the condition is a select.
9622   if (isa<PHINode>(SI.getCondition())) 
9623     // The true/false values have to be live in the PHI predecessor's blocks.
9624     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9625         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9626       if (Instruction *NV = FoldOpIntoPhi(SI))
9627         return NV;
9628
9629   if (BinaryOperator::isNot(CondVal)) {
9630     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9631     SI.setOperand(1, FalseVal);
9632     SI.setOperand(2, TrueVal);
9633     return &SI;
9634   }
9635
9636   return 0;
9637 }
9638
9639 /// EnforceKnownAlignment - If the specified pointer points to an object that
9640 /// we control, modify the object's alignment to PrefAlign. This isn't
9641 /// often possible though. If alignment is important, a more reliable approach
9642 /// is to simply align all global variables and allocation instructions to
9643 /// their preferred alignment from the beginning.
9644 ///
9645 static unsigned EnforceKnownAlignment(Value *V,
9646                                       unsigned Align, unsigned PrefAlign) {
9647
9648   User *U = dyn_cast<User>(V);
9649   if (!U) return Align;
9650
9651   switch (Operator::getOpcode(U)) {
9652   default: break;
9653   case Instruction::BitCast:
9654     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9655   case Instruction::GetElementPtr: {
9656     // If all indexes are zero, it is just the alignment of the base pointer.
9657     bool AllZeroOperands = true;
9658     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9659       if (!isa<Constant>(*i) ||
9660           !cast<Constant>(*i)->isNullValue()) {
9661         AllZeroOperands = false;
9662         break;
9663       }
9664
9665     if (AllZeroOperands) {
9666       // Treat this like a bitcast.
9667       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9668     }
9669     break;
9670   }
9671   }
9672
9673   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9674     // If there is a large requested alignment and we can, bump up the alignment
9675     // of the global.
9676     if (!GV->isDeclaration()) {
9677       if (GV->getAlignment() >= PrefAlign)
9678         Align = GV->getAlignment();
9679       else {
9680         GV->setAlignment(PrefAlign);
9681         Align = PrefAlign;
9682       }
9683     }
9684   } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9685     // If there is a requested alignment and if this is an alloca, round up.
9686     if (AI->getAlignment() >= PrefAlign)
9687       Align = AI->getAlignment();
9688     else {
9689       AI->setAlignment(PrefAlign);
9690       Align = PrefAlign;
9691     }
9692   }
9693
9694   return Align;
9695 }
9696
9697 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9698 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9699 /// and it is more than the alignment of the ultimate object, see if we can
9700 /// increase the alignment of the ultimate object, making this check succeed.
9701 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9702                                                   unsigned PrefAlign) {
9703   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9704                       sizeof(PrefAlign) * CHAR_BIT;
9705   APInt Mask = APInt::getAllOnesValue(BitWidth);
9706   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9707   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9708   unsigned TrailZ = KnownZero.countTrailingOnes();
9709   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9710
9711   if (PrefAlign > Align)
9712     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9713   
9714     // We don't need to make any adjustment.
9715   return Align;
9716 }
9717
9718 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9719   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9720   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9721   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9722   unsigned CopyAlign = MI->getAlignment();
9723
9724   if (CopyAlign < MinAlign) {
9725     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9726                                              MinAlign, false));
9727     return MI;
9728   }
9729   
9730   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9731   // load/store.
9732   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9733   if (MemOpLength == 0) return 0;
9734   
9735   // Source and destination pointer types are always "i8*" for intrinsic.  See
9736   // if the size is something we can handle with a single primitive load/store.
9737   // A single load+store correctly handles overlapping memory in the memmove
9738   // case.
9739   unsigned Size = MemOpLength->getZExtValue();
9740   if (Size == 0) return MI;  // Delete this mem transfer.
9741   
9742   if (Size > 8 || (Size&(Size-1)))
9743     return 0;  // If not 1/2/4/8 bytes, exit.
9744   
9745   // Use an integer load+store unless we can find something better.
9746   Type *NewPtrTy =
9747                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9748   
9749   // Memcpy forces the use of i8* for the source and destination.  That means
9750   // that if you're using memcpy to move one double around, you'll get a cast
9751   // from double* to i8*.  We'd much rather use a double load+store rather than
9752   // an i64 load+store, here because this improves the odds that the source or
9753   // dest address will be promotable.  See if we can find a better type than the
9754   // integer datatype.
9755   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9756     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9757     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9758       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9759       // down through these levels if so.
9760       while (!SrcETy->isSingleValueType()) {
9761         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9762           if (STy->getNumElements() == 1)
9763             SrcETy = STy->getElementType(0);
9764           else
9765             break;
9766         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9767           if (ATy->getNumElements() == 1)
9768             SrcETy = ATy->getElementType();
9769           else
9770             break;
9771         } else
9772           break;
9773       }
9774       
9775       if (SrcETy->isSingleValueType())
9776         NewPtrTy = PointerType::getUnqual(SrcETy);
9777     }
9778   }
9779   
9780   
9781   // If the memcpy/memmove provides better alignment info than we can
9782   // infer, use it.
9783   SrcAlign = std::max(SrcAlign, CopyAlign);
9784   DstAlign = std::max(DstAlign, CopyAlign);
9785   
9786   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9787   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9788   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9789   InsertNewInstBefore(L, *MI);
9790   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9791
9792   // Set the size of the copy to 0, it will be deleted on the next iteration.
9793   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9794   return MI;
9795 }
9796
9797 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9798   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9799   if (MI->getAlignment() < Alignment) {
9800     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9801                                              Alignment, false));
9802     return MI;
9803   }
9804   
9805   // Extract the length and alignment and fill if they are constant.
9806   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9807   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9808   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9809     return 0;
9810   uint64_t Len = LenC->getZExtValue();
9811   Alignment = MI->getAlignment();
9812   
9813   // If the length is zero, this is a no-op
9814   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9815   
9816   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9817   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9818     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9819     
9820     Value *Dest = MI->getDest();
9821     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9822
9823     // Alignment 0 is identity for alignment 1 for memset, but not store.
9824     if (Alignment == 0) Alignment = 1;
9825     
9826     // Extract the fill value and store.
9827     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9828     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9829                                       Dest, false, Alignment), *MI);
9830     
9831     // Set the size of the copy to 0, it will be deleted on the next iteration.
9832     MI->setLength(Constant::getNullValue(LenC->getType()));
9833     return MI;
9834   }
9835
9836   return 0;
9837 }
9838
9839
9840 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9841 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9842 /// the heavy lifting.
9843 ///
9844 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9845   if (isFreeCall(&CI))
9846     return visitFree(CI);
9847
9848   // If the caller function is nounwind, mark the call as nounwind, even if the
9849   // callee isn't.
9850   if (CI.getParent()->getParent()->doesNotThrow() &&
9851       !CI.doesNotThrow()) {
9852     CI.setDoesNotThrow();
9853     return &CI;
9854   }
9855   
9856   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9857   if (!II) return visitCallSite(&CI);
9858   
9859   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9860   // visitCallSite.
9861   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9862     bool Changed = false;
9863
9864     // memmove/cpy/set of zero bytes is a noop.
9865     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9866       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9867
9868       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9869         if (CI->getZExtValue() == 1) {
9870           // Replace the instruction with just byte operations.  We would
9871           // transform other cases to loads/stores, but we don't know if
9872           // alignment is sufficient.
9873         }
9874     }
9875
9876     // If we have a memmove and the source operation is a constant global,
9877     // then the source and dest pointers can't alias, so we can change this
9878     // into a call to memcpy.
9879     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9880       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9881         if (GVSrc->isConstant()) {
9882           Module *M = CI.getParent()->getParent()->getParent();
9883           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9884           const Type *Tys[1];
9885           Tys[0] = CI.getOperand(3)->getType();
9886           CI.setOperand(0, 
9887                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9888           Changed = true;
9889         }
9890
9891       // memmove(x,x,size) -> noop.
9892       if (MMI->getSource() == MMI->getDest())
9893         return EraseInstFromFunction(CI);
9894     }
9895
9896     // If we can determine a pointer alignment that is bigger than currently
9897     // set, update the alignment.
9898     if (isa<MemTransferInst>(MI)) {
9899       if (Instruction *I = SimplifyMemTransfer(MI))
9900         return I;
9901     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9902       if (Instruction *I = SimplifyMemSet(MSI))
9903         return I;
9904     }
9905           
9906     if (Changed) return II;
9907   }
9908   
9909   switch (II->getIntrinsicID()) {
9910   default: break;
9911   case Intrinsic::bswap:
9912     // bswap(bswap(x)) -> x
9913     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9914       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9915         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9916     break;
9917   case Intrinsic::ppc_altivec_lvx:
9918   case Intrinsic::ppc_altivec_lvxl:
9919   case Intrinsic::x86_sse_loadu_ps:
9920   case Intrinsic::x86_sse2_loadu_pd:
9921   case Intrinsic::x86_sse2_loadu_dq:
9922     // Turn PPC lvx     -> load if the pointer is known aligned.
9923     // Turn X86 loadups -> load if the pointer is known aligned.
9924     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9925       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9926                                          PointerType::getUnqual(II->getType()));
9927       return new LoadInst(Ptr);
9928     }
9929     break;
9930   case Intrinsic::ppc_altivec_stvx:
9931   case Intrinsic::ppc_altivec_stvxl:
9932     // Turn stvx -> store if the pointer is known aligned.
9933     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9934       const Type *OpPtrTy = 
9935         PointerType::getUnqual(II->getOperand(1)->getType());
9936       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9937       return new StoreInst(II->getOperand(1), Ptr);
9938     }
9939     break;
9940   case Intrinsic::x86_sse_storeu_ps:
9941   case Intrinsic::x86_sse2_storeu_pd:
9942   case Intrinsic::x86_sse2_storeu_dq:
9943     // Turn X86 storeu -> store if the pointer is known aligned.
9944     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9945       const Type *OpPtrTy = 
9946         PointerType::getUnqual(II->getOperand(2)->getType());
9947       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9948       return new StoreInst(II->getOperand(2), Ptr);
9949     }
9950     break;
9951     
9952   case Intrinsic::x86_sse_cvttss2si: {
9953     // These intrinsics only demands the 0th element of its input vector.  If
9954     // we can simplify the input based on that, do so now.
9955     unsigned VWidth =
9956       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9957     APInt DemandedElts(VWidth, 1);
9958     APInt UndefElts(VWidth, 0);
9959     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9960                                               UndefElts)) {
9961       II->setOperand(1, V);
9962       return II;
9963     }
9964     break;
9965   }
9966     
9967   case Intrinsic::ppc_altivec_vperm:
9968     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9969     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9970       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9971       
9972       // Check that all of the elements are integer constants or undefs.
9973       bool AllEltsOk = true;
9974       for (unsigned i = 0; i != 16; ++i) {
9975         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9976             !isa<UndefValue>(Mask->getOperand(i))) {
9977           AllEltsOk = false;
9978           break;
9979         }
9980       }
9981       
9982       if (AllEltsOk) {
9983         // Cast the input vectors to byte vectors.
9984         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9985         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9986         Value *Result = UndefValue::get(Op0->getType());
9987         
9988         // Only extract each element once.
9989         Value *ExtractedElts[32];
9990         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9991         
9992         for (unsigned i = 0; i != 16; ++i) {
9993           if (isa<UndefValue>(Mask->getOperand(i)))
9994             continue;
9995           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9996           Idx &= 31;  // Match the hardware behavior.
9997           
9998           if (ExtractedElts[Idx] == 0) {
9999             ExtractedElts[Idx] = 
10000               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
10001                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10002                                             "tmp");
10003           }
10004         
10005           // Insert this value into the result vector.
10006           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10007                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10008                                                 "tmp");
10009         }
10010         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
10011       }
10012     }
10013     break;
10014
10015   case Intrinsic::stackrestore: {
10016     // If the save is right next to the restore, remove the restore.  This can
10017     // happen when variable allocas are DCE'd.
10018     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10019       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10020         BasicBlock::iterator BI = SS;
10021         if (&*++BI == II)
10022           return EraseInstFromFunction(CI);
10023       }
10024     }
10025     
10026     // Scan down this block to see if there is another stack restore in the
10027     // same block without an intervening call/alloca.
10028     BasicBlock::iterator BI = II;
10029     TerminatorInst *TI = II->getParent()->getTerminator();
10030     bool CannotRemove = false;
10031     for (++BI; &*BI != TI; ++BI) {
10032       if (isa<AllocaInst>(BI) || isMalloc(BI)) {
10033         CannotRemove = true;
10034         break;
10035       }
10036       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10037         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10038           // If there is a stackrestore below this one, remove this one.
10039           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10040             return EraseInstFromFunction(CI);
10041           // Otherwise, ignore the intrinsic.
10042         } else {
10043           // If we found a non-intrinsic call, we can't remove the stack
10044           // restore.
10045           CannotRemove = true;
10046           break;
10047         }
10048       }
10049     }
10050     
10051     // If the stack restore is in a return/unwind block and if there are no
10052     // allocas or calls between the restore and the return, nuke the restore.
10053     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10054       return EraseInstFromFunction(CI);
10055     break;
10056   }
10057   }
10058
10059   return visitCallSite(II);
10060 }
10061
10062 // InvokeInst simplification
10063 //
10064 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10065   return visitCallSite(&II);
10066 }
10067
10068 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10069 /// passed through the varargs area, we can eliminate the use of the cast.
10070 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10071                                          const CastInst * const CI,
10072                                          const TargetData * const TD,
10073                                          const int ix) {
10074   if (!CI->isLosslessCast())
10075     return false;
10076
10077   // The size of ByVal arguments is derived from the type, so we
10078   // can't change to a type with a different size.  If the size were
10079   // passed explicitly we could avoid this check.
10080   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10081     return true;
10082
10083   const Type* SrcTy = 
10084             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10085   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10086   if (!SrcTy->isSized() || !DstTy->isSized())
10087     return false;
10088   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10089     return false;
10090   return true;
10091 }
10092
10093 // visitCallSite - Improvements for call and invoke instructions.
10094 //
10095 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10096   bool Changed = false;
10097
10098   // If the callee is a constexpr cast of a function, attempt to move the cast
10099   // to the arguments of the call/invoke.
10100   if (transformConstExprCastCall(CS)) return 0;
10101
10102   Value *Callee = CS.getCalledValue();
10103
10104   if (Function *CalleeF = dyn_cast<Function>(Callee))
10105     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10106       Instruction *OldCall = CS.getInstruction();
10107       // If the call and callee calling conventions don't match, this call must
10108       // be unreachable, as the call is undefined.
10109       new StoreInst(ConstantInt::getTrue(*Context),
10110                 UndefValue::get(Type::getInt1PtrTy(*Context)), 
10111                                   OldCall);
10112       // If OldCall dues not return void then replaceAllUsesWith undef.
10113       // This allows ValueHandlers and custom metadata to adjust itself.
10114       if (!OldCall->getType()->isVoidTy())
10115         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10116       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10117         return EraseInstFromFunction(*OldCall);
10118       return 0;
10119     }
10120
10121   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10122     // This instruction is not reachable, just remove it.  We insert a store to
10123     // undef so that we know that this code is not reachable, despite the fact
10124     // that we can't modify the CFG here.
10125     new StoreInst(ConstantInt::getTrue(*Context),
10126                UndefValue::get(Type::getInt1PtrTy(*Context)),
10127                   CS.getInstruction());
10128
10129     // If CS dues not return void then replaceAllUsesWith undef.
10130     // This allows ValueHandlers and custom metadata to adjust itself.
10131     if (!CS.getInstruction()->getType()->isVoidTy())
10132       CS.getInstruction()->
10133         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10134
10135     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10136       // Don't break the CFG, insert a dummy cond branch.
10137       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10138                          ConstantInt::getTrue(*Context), II);
10139     }
10140     return EraseInstFromFunction(*CS.getInstruction());
10141   }
10142
10143   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10144     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10145       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10146         return transformCallThroughTrampoline(CS);
10147
10148   const PointerType *PTy = cast<PointerType>(Callee->getType());
10149   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10150   if (FTy->isVarArg()) {
10151     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10152     // See if we can optimize any arguments passed through the varargs area of
10153     // the call.
10154     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10155            E = CS.arg_end(); I != E; ++I, ++ix) {
10156       CastInst *CI = dyn_cast<CastInst>(*I);
10157       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10158         *I = CI->getOperand(0);
10159         Changed = true;
10160       }
10161     }
10162   }
10163
10164   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10165     // Inline asm calls cannot throw - mark them 'nounwind'.
10166     CS.setDoesNotThrow();
10167     Changed = true;
10168   }
10169
10170   return Changed ? CS.getInstruction() : 0;
10171 }
10172
10173 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10174 // attempt to move the cast to the arguments of the call/invoke.
10175 //
10176 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10177   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10178   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10179   if (CE->getOpcode() != Instruction::BitCast || 
10180       !isa<Function>(CE->getOperand(0)))
10181     return false;
10182   Function *Callee = cast<Function>(CE->getOperand(0));
10183   Instruction *Caller = CS.getInstruction();
10184   const AttrListPtr &CallerPAL = CS.getAttributes();
10185
10186   // Okay, this is a cast from a function to a different type.  Unless doing so
10187   // would cause a type conversion of one of our arguments, change this call to
10188   // be a direct call with arguments casted to the appropriate types.
10189   //
10190   const FunctionType *FT = Callee->getFunctionType();
10191   const Type *OldRetTy = Caller->getType();
10192   const Type *NewRetTy = FT->getReturnType();
10193
10194   if (isa<StructType>(NewRetTy))
10195     return false; // TODO: Handle multiple return values.
10196
10197   // Check to see if we are changing the return type...
10198   if (OldRetTy != NewRetTy) {
10199     if (Callee->isDeclaration() &&
10200         // Conversion is ok if changing from one pointer type to another or from
10201         // a pointer to an integer of the same size.
10202         !((isa<PointerType>(OldRetTy) || !TD ||
10203            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10204           (isa<PointerType>(NewRetTy) || !TD ||
10205            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10206       return false;   // Cannot transform this return value.
10207
10208     if (!Caller->use_empty() &&
10209         // void -> non-void is handled specially
10210         !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
10211       return false;   // Cannot transform this return value.
10212
10213     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10214       Attributes RAttrs = CallerPAL.getRetAttributes();
10215       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10216         return false;   // Attribute not compatible with transformed value.
10217     }
10218
10219     // If the callsite is an invoke instruction, and the return value is used by
10220     // a PHI node in a successor, we cannot change the return type of the call
10221     // because there is no place to put the cast instruction (without breaking
10222     // the critical edge).  Bail out in this case.
10223     if (!Caller->use_empty())
10224       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10225         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10226              UI != E; ++UI)
10227           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10228             if (PN->getParent() == II->getNormalDest() ||
10229                 PN->getParent() == II->getUnwindDest())
10230               return false;
10231   }
10232
10233   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10234   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10235
10236   CallSite::arg_iterator AI = CS.arg_begin();
10237   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10238     const Type *ParamTy = FT->getParamType(i);
10239     const Type *ActTy = (*AI)->getType();
10240
10241     if (!CastInst::isCastable(ActTy, ParamTy))
10242       return false;   // Cannot transform this parameter value.
10243
10244     if (CallerPAL.getParamAttributes(i + 1) 
10245         & Attribute::typeIncompatible(ParamTy))
10246       return false;   // Attribute not compatible with transformed value.
10247
10248     // Converting from one pointer type to another or between a pointer and an
10249     // integer of the same size is safe even if we do not have a body.
10250     bool isConvertible = ActTy == ParamTy ||
10251       (TD && ((isa<PointerType>(ParamTy) ||
10252       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10253               (isa<PointerType>(ActTy) ||
10254               ActTy == TD->getIntPtrType(Caller->getContext()))));
10255     if (Callee->isDeclaration() && !isConvertible) return false;
10256   }
10257
10258   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10259       Callee->isDeclaration())
10260     return false;   // Do not delete arguments unless we have a function body.
10261
10262   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10263       !CallerPAL.isEmpty())
10264     // In this case we have more arguments than the new function type, but we
10265     // won't be dropping them.  Check that these extra arguments have attributes
10266     // that are compatible with being a vararg call argument.
10267     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10268       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10269         break;
10270       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10271       if (PAttrs & Attribute::VarArgsIncompatible)
10272         return false;
10273     }
10274
10275   // Okay, we decided that this is a safe thing to do: go ahead and start
10276   // inserting cast instructions as necessary...
10277   std::vector<Value*> Args;
10278   Args.reserve(NumActualArgs);
10279   SmallVector<AttributeWithIndex, 8> attrVec;
10280   attrVec.reserve(NumCommonArgs);
10281
10282   // Get any return attributes.
10283   Attributes RAttrs = CallerPAL.getRetAttributes();
10284
10285   // If the return value is not being used, the type may not be compatible
10286   // with the existing attributes.  Wipe out any problematic attributes.
10287   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10288
10289   // Add the new return attributes.
10290   if (RAttrs)
10291     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10292
10293   AI = CS.arg_begin();
10294   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10295     const Type *ParamTy = FT->getParamType(i);
10296     if ((*AI)->getType() == ParamTy) {
10297       Args.push_back(*AI);
10298     } else {
10299       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10300           false, ParamTy, false);
10301       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10302     }
10303
10304     // Add any parameter attributes.
10305     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10306       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10307   }
10308
10309   // If the function takes more arguments than the call was taking, add them
10310   // now.
10311   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10312     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10313
10314   // If we are removing arguments to the function, emit an obnoxious warning.
10315   if (FT->getNumParams() < NumActualArgs) {
10316     if (!FT->isVarArg()) {
10317       errs() << "WARNING: While resolving call to function '"
10318              << Callee->getName() << "' arguments were dropped!\n";
10319     } else {
10320       // Add all of the arguments in their promoted form to the arg list.
10321       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10322         const Type *PTy = getPromotedType((*AI)->getType());
10323         if (PTy != (*AI)->getType()) {
10324           // Must promote to pass through va_arg area!
10325           Instruction::CastOps opcode =
10326             CastInst::getCastOpcode(*AI, false, PTy, false);
10327           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10328         } else {
10329           Args.push_back(*AI);
10330         }
10331
10332         // Add any parameter attributes.
10333         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10334           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10335       }
10336     }
10337   }
10338
10339   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10340     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10341
10342   if (NewRetTy->isVoidTy())
10343     Caller->setName("");   // Void type should not have a name.
10344
10345   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10346                                                      attrVec.end());
10347
10348   Instruction *NC;
10349   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10350     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10351                             Args.begin(), Args.end(),
10352                             Caller->getName(), Caller);
10353     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10354     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10355   } else {
10356     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10357                           Caller->getName(), Caller);
10358     CallInst *CI = cast<CallInst>(Caller);
10359     if (CI->isTailCall())
10360       cast<CallInst>(NC)->setTailCall();
10361     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10362     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10363   }
10364
10365   // Insert a cast of the return type as necessary.
10366   Value *NV = NC;
10367   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10368     if (!NV->getType()->isVoidTy()) {
10369       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10370                                                             OldRetTy, false);
10371       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10372
10373       // If this is an invoke instruction, we should insert it after the first
10374       // non-phi, instruction in the normal successor block.
10375       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10376         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10377         InsertNewInstBefore(NC, *I);
10378       } else {
10379         // Otherwise, it's a call, just insert cast right after the call instr
10380         InsertNewInstBefore(NC, *Caller);
10381       }
10382       Worklist.AddUsersToWorkList(*Caller);
10383     } else {
10384       NV = UndefValue::get(Caller->getType());
10385     }
10386   }
10387
10388
10389   if (!Caller->use_empty())
10390     Caller->replaceAllUsesWith(NV);
10391   
10392   EraseInstFromFunction(*Caller);
10393   return true;
10394 }
10395
10396 // transformCallThroughTrampoline - Turn a call to a function created by the
10397 // init_trampoline intrinsic into a direct call to the underlying function.
10398 //
10399 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10400   Value *Callee = CS.getCalledValue();
10401   const PointerType *PTy = cast<PointerType>(Callee->getType());
10402   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10403   const AttrListPtr &Attrs = CS.getAttributes();
10404
10405   // If the call already has the 'nest' attribute somewhere then give up -
10406   // otherwise 'nest' would occur twice after splicing in the chain.
10407   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10408     return 0;
10409
10410   IntrinsicInst *Tramp =
10411     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10412
10413   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10414   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10415   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10416
10417   const AttrListPtr &NestAttrs = NestF->getAttributes();
10418   if (!NestAttrs.isEmpty()) {
10419     unsigned NestIdx = 1;
10420     const Type *NestTy = 0;
10421     Attributes NestAttr = Attribute::None;
10422
10423     // Look for a parameter marked with the 'nest' attribute.
10424     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10425          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10426       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10427         // Record the parameter type and any other attributes.
10428         NestTy = *I;
10429         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10430         break;
10431       }
10432
10433     if (NestTy) {
10434       Instruction *Caller = CS.getInstruction();
10435       std::vector<Value*> NewArgs;
10436       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10437
10438       SmallVector<AttributeWithIndex, 8> NewAttrs;
10439       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10440
10441       // Insert the nest argument into the call argument list, which may
10442       // mean appending it.  Likewise for attributes.
10443
10444       // Add any result attributes.
10445       if (Attributes Attr = Attrs.getRetAttributes())
10446         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10447
10448       {
10449         unsigned Idx = 1;
10450         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10451         do {
10452           if (Idx == NestIdx) {
10453             // Add the chain argument and attributes.
10454             Value *NestVal = Tramp->getOperand(3);
10455             if (NestVal->getType() != NestTy)
10456               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10457             NewArgs.push_back(NestVal);
10458             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10459           }
10460
10461           if (I == E)
10462             break;
10463
10464           // Add the original argument and attributes.
10465           NewArgs.push_back(*I);
10466           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10467             NewAttrs.push_back
10468               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10469
10470           ++Idx, ++I;
10471         } while (1);
10472       }
10473
10474       // Add any function attributes.
10475       if (Attributes Attr = Attrs.getFnAttributes())
10476         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10477
10478       // The trampoline may have been bitcast to a bogus type (FTy).
10479       // Handle this by synthesizing a new function type, equal to FTy
10480       // with the chain parameter inserted.
10481
10482       std::vector<const Type*> NewTypes;
10483       NewTypes.reserve(FTy->getNumParams()+1);
10484
10485       // Insert the chain's type into the list of parameter types, which may
10486       // mean appending it.
10487       {
10488         unsigned Idx = 1;
10489         FunctionType::param_iterator I = FTy->param_begin(),
10490           E = FTy->param_end();
10491
10492         do {
10493           if (Idx == NestIdx)
10494             // Add the chain's type.
10495             NewTypes.push_back(NestTy);
10496
10497           if (I == E)
10498             break;
10499
10500           // Add the original type.
10501           NewTypes.push_back(*I);
10502
10503           ++Idx, ++I;
10504         } while (1);
10505       }
10506
10507       // Replace the trampoline call with a direct call.  Let the generic
10508       // code sort out any function type mismatches.
10509       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10510                                                 FTy->isVarArg());
10511       Constant *NewCallee =
10512         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10513         NestF : ConstantExpr::getBitCast(NestF, 
10514                                          PointerType::getUnqual(NewFTy));
10515       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10516                                                    NewAttrs.end());
10517
10518       Instruction *NewCaller;
10519       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10520         NewCaller = InvokeInst::Create(NewCallee,
10521                                        II->getNormalDest(), II->getUnwindDest(),
10522                                        NewArgs.begin(), NewArgs.end(),
10523                                        Caller->getName(), Caller);
10524         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10525         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10526       } else {
10527         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10528                                      Caller->getName(), Caller);
10529         if (cast<CallInst>(Caller)->isTailCall())
10530           cast<CallInst>(NewCaller)->setTailCall();
10531         cast<CallInst>(NewCaller)->
10532           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10533         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10534       }
10535       if (!Caller->getType()->isVoidTy())
10536         Caller->replaceAllUsesWith(NewCaller);
10537       Caller->eraseFromParent();
10538       Worklist.Remove(Caller);
10539       return 0;
10540     }
10541   }
10542
10543   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10544   // parameter, there is no need to adjust the argument list.  Let the generic
10545   // code sort out any function type mismatches.
10546   Constant *NewCallee =
10547     NestF->getType() == PTy ? NestF : 
10548                               ConstantExpr::getBitCast(NestF, PTy);
10549   CS.setCalledFunction(NewCallee);
10550   return CS.getInstruction();
10551 }
10552
10553 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10554 /// and if a/b/c and the add's all have a single use, turn this into a phi
10555 /// and a single binop.
10556 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10557   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10558   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10559   unsigned Opc = FirstInst->getOpcode();
10560   Value *LHSVal = FirstInst->getOperand(0);
10561   Value *RHSVal = FirstInst->getOperand(1);
10562     
10563   const Type *LHSType = LHSVal->getType();
10564   const Type *RHSType = RHSVal->getType();
10565   
10566   // Scan to see if all operands are the same opcode, and all have one use.
10567   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10568     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10569     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10570         // Verify type of the LHS matches so we don't fold cmp's of different
10571         // types or GEP's with different index types.
10572         I->getOperand(0)->getType() != LHSType ||
10573         I->getOperand(1)->getType() != RHSType)
10574       return 0;
10575
10576     // If they are CmpInst instructions, check their predicates
10577     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10578       if (cast<CmpInst>(I)->getPredicate() !=
10579           cast<CmpInst>(FirstInst)->getPredicate())
10580         return 0;
10581     
10582     // Keep track of which operand needs a phi node.
10583     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10584     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10585   }
10586
10587   // If both LHS and RHS would need a PHI, don't do this transformation,
10588   // because it would increase the number of PHIs entering the block,
10589   // which leads to higher register pressure. This is especially
10590   // bad when the PHIs are in the header of a loop.
10591   if (!LHSVal && !RHSVal)
10592     return 0;
10593   
10594   // Otherwise, this is safe to transform!
10595   
10596   Value *InLHS = FirstInst->getOperand(0);
10597   Value *InRHS = FirstInst->getOperand(1);
10598   PHINode *NewLHS = 0, *NewRHS = 0;
10599   if (LHSVal == 0) {
10600     NewLHS = PHINode::Create(LHSType,
10601                              FirstInst->getOperand(0)->getName() + ".pn");
10602     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10603     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10604     InsertNewInstBefore(NewLHS, PN);
10605     LHSVal = NewLHS;
10606   }
10607   
10608   if (RHSVal == 0) {
10609     NewRHS = PHINode::Create(RHSType,
10610                              FirstInst->getOperand(1)->getName() + ".pn");
10611     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10612     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10613     InsertNewInstBefore(NewRHS, PN);
10614     RHSVal = NewRHS;
10615   }
10616   
10617   // Add all operands to the new PHIs.
10618   if (NewLHS || NewRHS) {
10619     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10620       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10621       if (NewLHS) {
10622         Value *NewInLHS = InInst->getOperand(0);
10623         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10624       }
10625       if (NewRHS) {
10626         Value *NewInRHS = InInst->getOperand(1);
10627         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10628       }
10629     }
10630   }
10631     
10632   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10633     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10634   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10635   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10636                          LHSVal, RHSVal);
10637 }
10638
10639 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10640   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10641   
10642   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10643                                         FirstInst->op_end());
10644   // This is true if all GEP bases are allocas and if all indices into them are
10645   // constants.
10646   bool AllBasePointersAreAllocas = true;
10647
10648   // We don't want to replace this phi if the replacement would require
10649   // more than one phi, which leads to higher register pressure. This is
10650   // especially bad when the PHIs are in the header of a loop.
10651   bool NeededPhi = false;
10652   
10653   // Scan to see if all operands are the same opcode, and all have one use.
10654   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10655     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10656     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10657       GEP->getNumOperands() != FirstInst->getNumOperands())
10658       return 0;
10659
10660     // Keep track of whether or not all GEPs are of alloca pointers.
10661     if (AllBasePointersAreAllocas &&
10662         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10663          !GEP->hasAllConstantIndices()))
10664       AllBasePointersAreAllocas = false;
10665     
10666     // Compare the operand lists.
10667     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10668       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10669         continue;
10670       
10671       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10672       // if one of the PHIs has a constant for the index.  The index may be
10673       // substantially cheaper to compute for the constants, so making it a
10674       // variable index could pessimize the path.  This also handles the case
10675       // for struct indices, which must always be constant.
10676       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10677           isa<ConstantInt>(GEP->getOperand(op)))
10678         return 0;
10679       
10680       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10681         return 0;
10682
10683       // If we already needed a PHI for an earlier operand, and another operand
10684       // also requires a PHI, we'd be introducing more PHIs than we're
10685       // eliminating, which increases register pressure on entry to the PHI's
10686       // block.
10687       if (NeededPhi)
10688         return 0;
10689
10690       FixedOperands[op] = 0;  // Needs a PHI.
10691       NeededPhi = true;
10692     }
10693   }
10694   
10695   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10696   // bother doing this transformation.  At best, this will just save a bit of
10697   // offset calculation, but all the predecessors will have to materialize the
10698   // stack address into a register anyway.  We'd actually rather *clone* the
10699   // load up into the predecessors so that we have a load of a gep of an alloca,
10700   // which can usually all be folded into the load.
10701   if (AllBasePointersAreAllocas)
10702     return 0;
10703   
10704   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10705   // that is variable.
10706   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10707   
10708   bool HasAnyPHIs = false;
10709   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10710     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10711     Value *FirstOp = FirstInst->getOperand(i);
10712     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10713                                      FirstOp->getName()+".pn");
10714     InsertNewInstBefore(NewPN, PN);
10715     
10716     NewPN->reserveOperandSpace(e);
10717     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10718     OperandPhis[i] = NewPN;
10719     FixedOperands[i] = NewPN;
10720     HasAnyPHIs = true;
10721   }
10722
10723   
10724   // Add all operands to the new PHIs.
10725   if (HasAnyPHIs) {
10726     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10727       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10728       BasicBlock *InBB = PN.getIncomingBlock(i);
10729       
10730       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10731         if (PHINode *OpPhi = OperandPhis[op])
10732           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10733     }
10734   }
10735   
10736   Value *Base = FixedOperands[0];
10737   return cast<GEPOperator>(FirstInst)->isInBounds() ?
10738     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10739                                       FixedOperands.end()) :
10740     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10741                               FixedOperands.end());
10742 }
10743
10744
10745 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10746 /// sink the load out of the block that defines it.  This means that it must be
10747 /// obvious the value of the load is not changed from the point of the load to
10748 /// the end of the block it is in.
10749 ///
10750 /// Finally, it is safe, but not profitable, to sink a load targetting a
10751 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10752 /// to a register.
10753 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10754   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10755   
10756   for (++BBI; BBI != E; ++BBI)
10757     if (BBI->mayWriteToMemory())
10758       return false;
10759   
10760   // Check for non-address taken alloca.  If not address-taken already, it isn't
10761   // profitable to do this xform.
10762   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10763     bool isAddressTaken = false;
10764     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10765          UI != E; ++UI) {
10766       if (isa<LoadInst>(UI)) continue;
10767       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10768         // If storing TO the alloca, then the address isn't taken.
10769         if (SI->getOperand(1) == AI) continue;
10770       }
10771       isAddressTaken = true;
10772       break;
10773     }
10774     
10775     if (!isAddressTaken && AI->isStaticAlloca())
10776       return false;
10777   }
10778   
10779   // If this load is a load from a GEP with a constant offset from an alloca,
10780   // then we don't want to sink it.  In its present form, it will be
10781   // load [constant stack offset].  Sinking it will cause us to have to
10782   // materialize the stack addresses in each predecessor in a register only to
10783   // do a shared load from register in the successor.
10784   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10785     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10786       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10787         return false;
10788   
10789   return true;
10790 }
10791
10792 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10793   LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10794   
10795   // When processing loads, we need to propagate two bits of information to the
10796   // sunk load: whether it is volatile, and what its alignment is.  We currently
10797   // don't sink loads when some have their alignment specified and some don't.
10798   // visitLoadInst will propagate an alignment onto the load when TD is around,
10799   // and if TD isn't around, we can't handle the mixed case.
10800   bool isVolatile = FirstLI->isVolatile();
10801   unsigned LoadAlignment = FirstLI->getAlignment();
10802   
10803   // We can't sink the load if the loaded value could be modified between the
10804   // load and the PHI.
10805   if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
10806       !isSafeAndProfitableToSinkLoad(FirstLI))
10807     return 0;
10808   
10809   // If the PHI is of volatile loads and the load block has multiple
10810   // successors, sinking it would remove a load of the volatile value from
10811   // the path through the other successor.
10812   if (isVolatile && 
10813       FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
10814     return 0;
10815   
10816   // Check to see if all arguments are the same operation.
10817   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10818     LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
10819     if (!LI || !LI->hasOneUse())
10820       return 0;
10821     
10822     // We can't sink the load if the loaded value could be modified between 
10823     // the load and the PHI.
10824     if (LI->isVolatile() != isVolatile ||
10825         LI->getParent() != PN.getIncomingBlock(i) ||
10826         !isSafeAndProfitableToSinkLoad(LI))
10827       return 0;
10828       
10829     // If some of the loads have an alignment specified but not all of them,
10830     // we can't do the transformation.
10831     if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
10832       return 0;
10833     
10834     LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
10835     
10836     // If the PHI is of volatile loads and the load block has multiple
10837     // successors, sinking it would remove a load of the volatile value from
10838     // the path through the other successor.
10839     if (isVolatile &&
10840         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10841       return 0;
10842   }
10843   
10844   // Okay, they are all the same operation.  Create a new PHI node of the
10845   // correct type, and PHI together all of the LHS's of the instructions.
10846   PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
10847                                    PN.getName()+".in");
10848   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10849   
10850   Value *InVal = FirstLI->getOperand(0);
10851   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10852   
10853   // Add all operands to the new PHI.
10854   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10855     Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
10856     if (NewInVal != InVal)
10857       InVal = 0;
10858     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10859   }
10860   
10861   Value *PhiVal;
10862   if (InVal) {
10863     // The new PHI unions all of the same values together.  This is really
10864     // common, so we handle it intelligently here for compile-time speed.
10865     PhiVal = InVal;
10866     delete NewPN;
10867   } else {
10868     InsertNewInstBefore(NewPN, PN);
10869     PhiVal = NewPN;
10870   }
10871   
10872   // If this was a volatile load that we are merging, make sure to loop through
10873   // and mark all the input loads as non-volatile.  If we don't do this, we will
10874   // insert a new volatile load and the old ones will not be deletable.
10875   if (isVolatile)
10876     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10877       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10878   
10879   return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
10880 }
10881
10882
10883 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10884 // operator and they all are only used by the PHI, PHI together their
10885 // inputs, and do the operation once, to the result of the PHI.
10886 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10887   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10888
10889   if (isa<GetElementPtrInst>(FirstInst))
10890     return FoldPHIArgGEPIntoPHI(PN);
10891   if (isa<LoadInst>(FirstInst))
10892     return FoldPHIArgLoadIntoPHI(PN);
10893   
10894   // Scan the instruction, looking for input operations that can be folded away.
10895   // If all input operands to the phi are the same instruction (e.g. a cast from
10896   // the same type or "+42") we can pull the operation through the PHI, reducing
10897   // code size and simplifying code.
10898   Constant *ConstantOp = 0;
10899   const Type *CastSrcTy = 0;
10900   
10901   if (isa<CastInst>(FirstInst)) {
10902     CastSrcTy = FirstInst->getOperand(0)->getType();
10903   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10904     // Can fold binop, compare or shift here if the RHS is a constant, 
10905     // otherwise call FoldPHIArgBinOpIntoPHI.
10906     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10907     if (ConstantOp == 0)
10908       return FoldPHIArgBinOpIntoPHI(PN);
10909   } else {
10910     return 0;  // Cannot fold this operation.
10911   }
10912
10913   // Check to see if all arguments are the same operation.
10914   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10915     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10916     if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10917       return 0;
10918     if (CastSrcTy) {
10919       if (I->getOperand(0)->getType() != CastSrcTy)
10920         return 0;  // Cast operation must match.
10921     } else if (I->getOperand(1) != ConstantOp) {
10922       return 0;
10923     }
10924   }
10925
10926   // Okay, they are all the same operation.  Create a new PHI node of the
10927   // correct type, and PHI together all of the LHS's of the instructions.
10928   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10929                                    PN.getName()+".in");
10930   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10931
10932   Value *InVal = FirstInst->getOperand(0);
10933   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10934
10935   // Add all operands to the new PHI.
10936   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10937     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10938     if (NewInVal != InVal)
10939       InVal = 0;
10940     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10941   }
10942
10943   Value *PhiVal;
10944   if (InVal) {
10945     // The new PHI unions all of the same values together.  This is really
10946     // common, so we handle it intelligently here for compile-time speed.
10947     PhiVal = InVal;
10948     delete NewPN;
10949   } else {
10950     InsertNewInstBefore(NewPN, PN);
10951     PhiVal = NewPN;
10952   }
10953
10954   // Insert and return the new operation.
10955   if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
10956     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10957   
10958   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10959     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10960   
10961   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10962   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10963                          PhiVal, ConstantOp);
10964 }
10965
10966 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10967 /// that is dead.
10968 static bool DeadPHICycle(PHINode *PN,
10969                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10970   if (PN->use_empty()) return true;
10971   if (!PN->hasOneUse()) return false;
10972
10973   // Remember this node, and if we find the cycle, return.
10974   if (!PotentiallyDeadPHIs.insert(PN))
10975     return true;
10976   
10977   // Don't scan crazily complex things.
10978   if (PotentiallyDeadPHIs.size() == 16)
10979     return false;
10980
10981   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10982     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10983
10984   return false;
10985 }
10986
10987 /// PHIsEqualValue - Return true if this phi node is always equal to
10988 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10989 ///   z = some value; x = phi (y, z); y = phi (x, z)
10990 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10991                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10992   // See if we already saw this PHI node.
10993   if (!ValueEqualPHIs.insert(PN))
10994     return true;
10995   
10996   // Don't scan crazily complex things.
10997   if (ValueEqualPHIs.size() == 16)
10998     return false;
10999  
11000   // Scan the operands to see if they are either phi nodes or are equal to
11001   // the value.
11002   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11003     Value *Op = PN->getIncomingValue(i);
11004     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11005       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11006         return false;
11007     } else if (Op != NonPhiInVal)
11008       return false;
11009   }
11010   
11011   return true;
11012 }
11013
11014
11015 // PHINode simplification
11016 //
11017 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
11018   // If LCSSA is around, don't mess with Phi nodes
11019   if (MustPreserveLCSSA) return 0;
11020   
11021   if (Value *V = PN.hasConstantValue())
11022     return ReplaceInstUsesWith(PN, V);
11023
11024   // If all PHI operands are the same operation, pull them through the PHI,
11025   // reducing code size.
11026   if (isa<Instruction>(PN.getIncomingValue(0)) &&
11027       isa<Instruction>(PN.getIncomingValue(1)) &&
11028       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11029       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11030       // FIXME: The hasOneUse check will fail for PHIs that use the value more
11031       // than themselves more than once.
11032       PN.getIncomingValue(0)->hasOneUse())
11033     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11034       return Result;
11035
11036   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
11037   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11038   // PHI)... break the cycle.
11039   if (PN.hasOneUse()) {
11040     Instruction *PHIUser = cast<Instruction>(PN.use_back());
11041     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
11042       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
11043       PotentiallyDeadPHIs.insert(&PN);
11044       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
11045         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11046     }
11047    
11048     // If this phi has a single use, and if that use just computes a value for
11049     // the next iteration of a loop, delete the phi.  This occurs with unused
11050     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
11051     // common case here is good because the only other things that catch this
11052     // are induction variable analysis (sometimes) and ADCE, which is only run
11053     // late.
11054     if (PHIUser->hasOneUse() &&
11055         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11056         PHIUser->use_back() == &PN) {
11057       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11058     }
11059   }
11060
11061   // We sometimes end up with phi cycles that non-obviously end up being the
11062   // same value, for example:
11063   //   z = some value; x = phi (y, z); y = phi (x, z)
11064   // where the phi nodes don't necessarily need to be in the same block.  Do a
11065   // quick check to see if the PHI node only contains a single non-phi value, if
11066   // so, scan to see if the phi cycle is actually equal to that value.
11067   {
11068     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11069     // Scan for the first non-phi operand.
11070     while (InValNo != NumOperandVals && 
11071            isa<PHINode>(PN.getIncomingValue(InValNo)))
11072       ++InValNo;
11073
11074     if (InValNo != NumOperandVals) {
11075       Value *NonPhiInVal = PN.getOperand(InValNo);
11076       
11077       // Scan the rest of the operands to see if there are any conflicts, if so
11078       // there is no need to recursively scan other phis.
11079       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11080         Value *OpVal = PN.getIncomingValue(InValNo);
11081         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11082           break;
11083       }
11084       
11085       // If we scanned over all operands, then we have one unique value plus
11086       // phi values.  Scan PHI nodes to see if they all merge in each other or
11087       // the value.
11088       if (InValNo == NumOperandVals) {
11089         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11090         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11091           return ReplaceInstUsesWith(PN, NonPhiInVal);
11092       }
11093     }
11094   }
11095
11096   // If there are multiple PHIs, sort their operands so that they all list
11097   // the blocks in the same order. This will help identical PHIs be eliminated
11098   // by other passes. Other passes shouldn't depend on this for correctness
11099   // however.
11100   PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11101   if (&PN != FirstPN)
11102     for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
11103       BasicBlock *BBA = PN.getIncomingBlock(i);
11104       BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11105       if (BBA != BBB) {
11106         Value *VA = PN.getIncomingValue(i);
11107         unsigned j = PN.getBasicBlockIndex(BBB);
11108         Value *VB = PN.getIncomingValue(j);
11109         PN.setIncomingBlock(i, BBB);
11110         PN.setIncomingValue(i, VB);
11111         PN.setIncomingBlock(j, BBA);
11112         PN.setIncomingValue(j, VA);
11113         // NOTE: Instcombine normally would want us to "return &PN" if we
11114         // modified any of the operands of an instruction.  However, since we
11115         // aren't adding or removing uses (just rearranging them) we don't do
11116         // this in this case.
11117       }
11118     }
11119
11120   return 0;
11121 }
11122
11123 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11124   Value *PtrOp = GEP.getOperand(0);
11125   // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
11126   if (GEP.getNumOperands() == 1)
11127     return ReplaceInstUsesWith(GEP, PtrOp);
11128
11129   if (isa<UndefValue>(GEP.getOperand(0)))
11130     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
11131
11132   bool HasZeroPointerIndex = false;
11133   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11134     HasZeroPointerIndex = C->isNullValue();
11135
11136   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11137     return ReplaceInstUsesWith(GEP, PtrOp);
11138
11139   // Eliminate unneeded casts for indices.
11140   if (TD) {
11141     bool MadeChange = false;
11142     unsigned PtrSize = TD->getPointerSizeInBits();
11143     
11144     gep_type_iterator GTI = gep_type_begin(GEP);
11145     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11146          I != E; ++I, ++GTI) {
11147       if (!isa<SequentialType>(*GTI)) continue;
11148       
11149       // If we are using a wider index than needed for this platform, shrink it
11150       // to what we need.  If narrower, sign-extend it to what we need.  This
11151       // explicit cast can make subsequent optimizations more obvious.
11152       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11153       if (OpBits == PtrSize)
11154         continue;
11155       
11156       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
11157       MadeChange = true;
11158     }
11159     if (MadeChange) return &GEP;
11160   }
11161
11162   // Combine Indices - If the source pointer to this getelementptr instruction
11163   // is a getelementptr instruction, combine the indices of the two
11164   // getelementptr instructions into a single instruction.
11165   //
11166   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11167     // Note that if our source is a gep chain itself that we wait for that
11168     // chain to be resolved before we perform this transformation.  This
11169     // avoids us creating a TON of code in some cases.
11170     //
11171     if (GetElementPtrInst *SrcGEP =
11172           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11173       if (SrcGEP->getNumOperands() == 2)
11174         return 0;   // Wait until our source is folded to completion.
11175
11176     SmallVector<Value*, 8> Indices;
11177
11178     // Find out whether the last index in the source GEP is a sequential idx.
11179     bool EndsWithSequential = false;
11180     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11181          I != E; ++I)
11182       EndsWithSequential = !isa<StructType>(*I);
11183
11184     // Can we combine the two pointer arithmetics offsets?
11185     if (EndsWithSequential) {
11186       // Replace: gep (gep %P, long B), long A, ...
11187       // With:    T = long A+B; gep %P, T, ...
11188       //
11189       Value *Sum;
11190       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11191       Value *GO1 = GEP.getOperand(1);
11192       if (SO1 == Constant::getNullValue(SO1->getType())) {
11193         Sum = GO1;
11194       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11195         Sum = SO1;
11196       } else {
11197         // If they aren't the same type, then the input hasn't been processed
11198         // by the loop above yet (which canonicalizes sequential index types to
11199         // intptr_t).  Just avoid transforming this until the input has been
11200         // normalized.
11201         if (SO1->getType() != GO1->getType())
11202           return 0;
11203         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11204       }
11205
11206       // Update the GEP in place if possible.
11207       if (Src->getNumOperands() == 2) {
11208         GEP.setOperand(0, Src->getOperand(0));
11209         GEP.setOperand(1, Sum);
11210         return &GEP;
11211       }
11212       Indices.append(Src->op_begin()+1, Src->op_end()-1);
11213       Indices.push_back(Sum);
11214       Indices.append(GEP.op_begin()+2, GEP.op_end());
11215     } else if (isa<Constant>(*GEP.idx_begin()) &&
11216                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11217                Src->getNumOperands() != 1) {
11218       // Otherwise we can do the fold if the first index of the GEP is a zero
11219       Indices.append(Src->op_begin()+1, Src->op_end());
11220       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
11221     }
11222
11223     if (!Indices.empty())
11224       return (cast<GEPOperator>(&GEP)->isInBounds() &&
11225               Src->isInBounds()) ?
11226         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11227                                           Indices.end(), GEP.getName()) :
11228         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11229                                   Indices.end(), GEP.getName());
11230   }
11231   
11232   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11233   if (Value *X = getBitCastOperand(PtrOp)) {
11234     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11235
11236     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
11237     // want to change the gep until the bitcasts are eliminated.
11238     if (getBitCastOperand(X)) {
11239       Worklist.AddValue(PtrOp);
11240       return 0;
11241     }
11242     
11243     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11244     // into     : GEP [10 x i8]* X, i32 0, ...
11245     //
11246     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11247     //           into     : GEP i8* X, ...
11248     // 
11249     // This occurs when the program declares an array extern like "int X[];"
11250     if (HasZeroPointerIndex) {
11251       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11252       const PointerType *XTy = cast<PointerType>(X->getType());
11253       if (const ArrayType *CATy =
11254           dyn_cast<ArrayType>(CPTy->getElementType())) {
11255         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11256         if (CATy->getElementType() == XTy->getElementType()) {
11257           // -> GEP i8* X, ...
11258           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11259           return cast<GEPOperator>(&GEP)->isInBounds() ?
11260             GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11261                                               GEP.getName()) :
11262             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11263                                       GEP.getName());
11264         }
11265         
11266         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11267           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11268           if (CATy->getElementType() == XATy->getElementType()) {
11269             // -> GEP [10 x i8]* X, i32 0, ...
11270             // At this point, we know that the cast source type is a pointer
11271             // to an array of the same type as the destination pointer
11272             // array.  Because the array type is never stepped over (there
11273             // is a leading zero) we can fold the cast into this GEP.
11274             GEP.setOperand(0, X);
11275             return &GEP;
11276           }
11277         }
11278       }
11279     } else if (GEP.getNumOperands() == 2) {
11280       // Transform things like:
11281       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11282       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11283       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11284       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11285       if (TD && isa<ArrayType>(SrcElTy) &&
11286           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11287           TD->getTypeAllocSize(ResElTy)) {
11288         Value *Idx[2];
11289         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11290         Idx[1] = GEP.getOperand(1);
11291         Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11292           Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11293           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11294         // V and GEP are both pointer types --> BitCast
11295         return new BitCastInst(NewGEP, GEP.getType());
11296       }
11297       
11298       // Transform things like:
11299       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11300       //   (where tmp = 8*tmp2) into:
11301       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11302       
11303       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11304         uint64_t ArrayEltSize =
11305             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11306         
11307         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11308         // allow either a mul, shift, or constant here.
11309         Value *NewIdx = 0;
11310         ConstantInt *Scale = 0;
11311         if (ArrayEltSize == 1) {
11312           NewIdx = GEP.getOperand(1);
11313           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11314         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11315           NewIdx = ConstantInt::get(CI->getType(), 1);
11316           Scale = CI;
11317         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11318           if (Inst->getOpcode() == Instruction::Shl &&
11319               isa<ConstantInt>(Inst->getOperand(1))) {
11320             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11321             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11322             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11323                                      1ULL << ShAmtVal);
11324             NewIdx = Inst->getOperand(0);
11325           } else if (Inst->getOpcode() == Instruction::Mul &&
11326                      isa<ConstantInt>(Inst->getOperand(1))) {
11327             Scale = cast<ConstantInt>(Inst->getOperand(1));
11328             NewIdx = Inst->getOperand(0);
11329           }
11330         }
11331         
11332         // If the index will be to exactly the right offset with the scale taken
11333         // out, perform the transformation. Note, we don't know whether Scale is
11334         // signed or not. We'll use unsigned version of division/modulo
11335         // operation after making sure Scale doesn't have the sign bit set.
11336         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11337             Scale->getZExtValue() % ArrayEltSize == 0) {
11338           Scale = ConstantInt::get(Scale->getType(),
11339                                    Scale->getZExtValue() / ArrayEltSize);
11340           if (Scale->getZExtValue() != 1) {
11341             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11342                                                        false /*ZExt*/);
11343             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11344           }
11345
11346           // Insert the new GEP instruction.
11347           Value *Idx[2];
11348           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11349           Idx[1] = NewIdx;
11350           Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11351             Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11352             Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11353           // The NewGEP must be pointer typed, so must the old one -> BitCast
11354           return new BitCastInst(NewGEP, GEP.getType());
11355         }
11356       }
11357     }
11358   }
11359   
11360   /// See if we can simplify:
11361   ///   X = bitcast A* to B*
11362   ///   Y = gep X, <...constant indices...>
11363   /// into a gep of the original struct.  This is important for SROA and alias
11364   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11365   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11366     if (TD &&
11367         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11368       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11369       // a constant back from EmitGEPOffset.
11370       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
11371       int64_t Offset = OffsetV->getSExtValue();
11372       
11373       // If this GEP instruction doesn't move the pointer, just replace the GEP
11374       // with a bitcast of the real input to the dest type.
11375       if (Offset == 0) {
11376         // If the bitcast is of an allocation, and the allocation will be
11377         // converted to match the type of the cast, don't touch this.
11378         if (isa<AllocaInst>(BCI->getOperand(0)) ||
11379             isMalloc(BCI->getOperand(0))) {
11380           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11381           if (Instruction *I = visitBitCast(*BCI)) {
11382             if (I != BCI) {
11383               I->takeName(BCI);
11384               BCI->getParent()->getInstList().insert(BCI, I);
11385               ReplaceInstUsesWith(*BCI, I);
11386             }
11387             return &GEP;
11388           }
11389         }
11390         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11391       }
11392       
11393       // Otherwise, if the offset is non-zero, we need to find out if there is a
11394       // field at Offset in 'A's type.  If so, we can pull the cast through the
11395       // GEP.
11396       SmallVector<Value*, 8> NewIndices;
11397       const Type *InTy =
11398         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11399       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11400         Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11401           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11402                                      NewIndices.end()) :
11403           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11404                              NewIndices.end());
11405         
11406         if (NGEP->getType() == GEP.getType())
11407           return ReplaceInstUsesWith(GEP, NGEP);
11408         NGEP->takeName(&GEP);
11409         return new BitCastInst(NGEP, GEP.getType());
11410       }
11411     }
11412   }    
11413     
11414   return 0;
11415 }
11416
11417 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
11418   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
11419   if (AI.isArrayAllocation()) {  // Check C != 1
11420     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11421       const Type *NewTy = 
11422         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11423       assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11424       AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11425       New->setAlignment(AI.getAlignment());
11426
11427       // Scan to the end of the allocation instructions, to skip over a block of
11428       // allocas if possible...also skip interleaved debug info
11429       //
11430       BasicBlock::iterator It = New;
11431       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11432
11433       // Now that I is pointing to the first non-allocation-inst in the block,
11434       // insert our getelementptr instruction...
11435       //
11436       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11437       Value *Idx[2];
11438       Idx[0] = NullIdx;
11439       Idx[1] = NullIdx;
11440       Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11441                                                    New->getName()+".sub", It);
11442
11443       // Now make everything use the getelementptr instead of the original
11444       // allocation.
11445       return ReplaceInstUsesWith(AI, V);
11446     } else if (isa<UndefValue>(AI.getArraySize())) {
11447       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11448     }
11449   }
11450
11451   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11452     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11453     // Note that we only do this for alloca's, because malloc should allocate
11454     // and return a unique pointer, even for a zero byte allocation.
11455     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11456       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11457
11458     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11459     if (AI.getAlignment() == 0)
11460       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11461   }
11462
11463   return 0;
11464 }
11465
11466 Instruction *InstCombiner::visitFree(Instruction &FI) {
11467   Value *Op = FI.getOperand(1);
11468
11469   // free undef -> unreachable.
11470   if (isa<UndefValue>(Op)) {
11471     // Insert a new store to null because we cannot modify the CFG here.
11472     new StoreInst(ConstantInt::getTrue(*Context),
11473            UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11474     return EraseInstFromFunction(FI);
11475   }
11476   
11477   // If we have 'free null' delete the instruction.  This can happen in stl code
11478   // when lots of inlining happens.
11479   if (isa<ConstantPointerNull>(Op))
11480     return EraseInstFromFunction(FI);
11481
11482   // If we have a malloc call whose only use is a free call, delete both.
11483   if (isMalloc(Op)) {
11484     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11485       if (Op->hasOneUse() && CI->hasOneUse()) {
11486         EraseInstFromFunction(FI);
11487         EraseInstFromFunction(*CI);
11488         return EraseInstFromFunction(*cast<Instruction>(Op));
11489       }
11490     } else {
11491       // Op is a call to malloc
11492       if (Op->hasOneUse()) {
11493         EraseInstFromFunction(FI);
11494         return EraseInstFromFunction(*cast<Instruction>(Op));
11495       }
11496     }
11497   }
11498
11499   return 0;
11500 }
11501
11502 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11503 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11504                                         const TargetData *TD) {
11505   User *CI = cast<User>(LI.getOperand(0));
11506   Value *CastOp = CI->getOperand(0);
11507   LLVMContext *Context = IC.getContext();
11508
11509   const PointerType *DestTy = cast<PointerType>(CI->getType());
11510   const Type *DestPTy = DestTy->getElementType();
11511   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11512
11513     // If the address spaces don't match, don't eliminate the cast.
11514     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11515       return 0;
11516
11517     const Type *SrcPTy = SrcTy->getElementType();
11518
11519     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11520          isa<VectorType>(DestPTy)) {
11521       // If the source is an array, the code below will not succeed.  Check to
11522       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11523       // constants.
11524       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11525         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11526           if (ASrcTy->getNumElements() != 0) {
11527             Value *Idxs[2];
11528             Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11529             Idxs[1] = Idxs[0];
11530             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11531             SrcTy = cast<PointerType>(CastOp->getType());
11532             SrcPTy = SrcTy->getElementType();
11533           }
11534
11535       if (IC.getTargetData() &&
11536           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11537             isa<VectorType>(SrcPTy)) &&
11538           // Do not allow turning this into a load of an integer, which is then
11539           // casted to a pointer, this pessimizes pointer analysis a lot.
11540           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11541           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11542                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11543
11544         // Okay, we are casting from one integer or pointer type to another of
11545         // the same size.  Instead of casting the pointer before the load, cast
11546         // the result of the loaded value.
11547         Value *NewLoad = 
11548           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11549         // Now cast the result of the load.
11550         return new BitCastInst(NewLoad, LI.getType());
11551       }
11552     }
11553   }
11554   return 0;
11555 }
11556
11557 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11558   Value *Op = LI.getOperand(0);
11559
11560   // Attempt to improve the alignment.
11561   if (TD) {
11562     unsigned KnownAlign =
11563       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11564     if (KnownAlign >
11565         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11566                                   LI.getAlignment()))
11567       LI.setAlignment(KnownAlign);
11568   }
11569
11570   // load (cast X) --> cast (load X) iff safe.
11571   if (isa<CastInst>(Op))
11572     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11573       return Res;
11574
11575   // None of the following transforms are legal for volatile loads.
11576   if (LI.isVolatile()) return 0;
11577   
11578   // Do really simple store-to-load forwarding and load CSE, to catch cases
11579   // where there are several consequtive memory accesses to the same location,
11580   // separated by a few arithmetic operations.
11581   BasicBlock::iterator BBI = &LI;
11582   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11583     return ReplaceInstUsesWith(LI, AvailableVal);
11584
11585   // load(gep null, ...) -> unreachable
11586   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11587     const Value *GEPI0 = GEPI->getOperand(0);
11588     // TODO: Consider a target hook for valid address spaces for this xform.
11589     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11590       // Insert a new store to null instruction before the load to indicate
11591       // that this code is not reachable.  We do this instead of inserting
11592       // an unreachable instruction directly because we cannot modify the
11593       // CFG.
11594       new StoreInst(UndefValue::get(LI.getType()),
11595                     Constant::getNullValue(Op->getType()), &LI);
11596       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11597     }
11598   } 
11599
11600   // load null/undef -> unreachable
11601   // TODO: Consider a target hook for valid address spaces for this xform.
11602   if (isa<UndefValue>(Op) ||
11603       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11604     // Insert a new store to null instruction before the load to indicate that
11605     // this code is not reachable.  We do this instead of inserting an
11606     // unreachable instruction directly because we cannot modify the CFG.
11607     new StoreInst(UndefValue::get(LI.getType()),
11608                   Constant::getNullValue(Op->getType()), &LI);
11609     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11610   }
11611
11612   // Instcombine load (constantexpr_cast global) -> cast (load global)
11613   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11614     if (CE->isCast())
11615       if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11616         return Res;
11617   
11618   if (Op->hasOneUse()) {
11619     // Change select and PHI nodes to select values instead of addresses: this
11620     // helps alias analysis out a lot, allows many others simplifications, and
11621     // exposes redundancy in the code.
11622     //
11623     // Note that we cannot do the transformation unless we know that the
11624     // introduced loads cannot trap!  Something like this is valid as long as
11625     // the condition is always false: load (select bool %C, int* null, int* %G),
11626     // but it would not be valid if we transformed it to load from null
11627     // unconditionally.
11628     //
11629     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11630       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11631       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11632           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11633         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11634                                         SI->getOperand(1)->getName()+".val");
11635         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11636                                         SI->getOperand(2)->getName()+".val");
11637         return SelectInst::Create(SI->getCondition(), V1, V2);
11638       }
11639
11640       // load (select (cond, null, P)) -> load P
11641       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11642         if (C->isNullValue()) {
11643           LI.setOperand(0, SI->getOperand(2));
11644           return &LI;
11645         }
11646
11647       // load (select (cond, P, null)) -> load P
11648       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11649         if (C->isNullValue()) {
11650           LI.setOperand(0, SI->getOperand(1));
11651           return &LI;
11652         }
11653     }
11654   }
11655   return 0;
11656 }
11657
11658 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11659 /// when possible.  This makes it generally easy to do alias analysis and/or
11660 /// SROA/mem2reg of the memory object.
11661 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11662   User *CI = cast<User>(SI.getOperand(1));
11663   Value *CastOp = CI->getOperand(0);
11664
11665   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11666   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11667   if (SrcTy == 0) return 0;
11668   
11669   const Type *SrcPTy = SrcTy->getElementType();
11670
11671   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11672     return 0;
11673   
11674   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11675   /// to its first element.  This allows us to handle things like:
11676   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11677   /// on 32-bit hosts.
11678   SmallVector<Value*, 4> NewGEPIndices;
11679   
11680   // If the source is an array, the code below will not succeed.  Check to
11681   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11682   // constants.
11683   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11684     // Index through pointer.
11685     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11686     NewGEPIndices.push_back(Zero);
11687     
11688     while (1) {
11689       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11690         if (!STy->getNumElements()) /* Struct can be empty {} */
11691           break;
11692         NewGEPIndices.push_back(Zero);
11693         SrcPTy = STy->getElementType(0);
11694       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11695         NewGEPIndices.push_back(Zero);
11696         SrcPTy = ATy->getElementType();
11697       } else {
11698         break;
11699       }
11700     }
11701     
11702     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11703   }
11704
11705   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11706     return 0;
11707   
11708   // If the pointers point into different address spaces or if they point to
11709   // values with different sizes, we can't do the transformation.
11710   if (!IC.getTargetData() ||
11711       SrcTy->getAddressSpace() != 
11712         cast<PointerType>(CI->getType())->getAddressSpace() ||
11713       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11714       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11715     return 0;
11716
11717   // Okay, we are casting from one integer or pointer type to another of
11718   // the same size.  Instead of casting the pointer before 
11719   // the store, cast the value to be stored.
11720   Value *NewCast;
11721   Value *SIOp0 = SI.getOperand(0);
11722   Instruction::CastOps opcode = Instruction::BitCast;
11723   const Type* CastSrcTy = SIOp0->getType();
11724   const Type* CastDstTy = SrcPTy;
11725   if (isa<PointerType>(CastDstTy)) {
11726     if (CastSrcTy->isInteger())
11727       opcode = Instruction::IntToPtr;
11728   } else if (isa<IntegerType>(CastDstTy)) {
11729     if (isa<PointerType>(SIOp0->getType()))
11730       opcode = Instruction::PtrToInt;
11731   }
11732   
11733   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11734   // emit a GEP to index into its first field.
11735   if (!NewGEPIndices.empty())
11736     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11737                                            NewGEPIndices.end());
11738   
11739   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11740                                    SIOp0->getName()+".c");
11741   return new StoreInst(NewCast, CastOp);
11742 }
11743
11744 /// equivalentAddressValues - Test if A and B will obviously have the same
11745 /// value. This includes recognizing that %t0 and %t1 will have the same
11746 /// value in code like this:
11747 ///   %t0 = getelementptr \@a, 0, 3
11748 ///   store i32 0, i32* %t0
11749 ///   %t1 = getelementptr \@a, 0, 3
11750 ///   %t2 = load i32* %t1
11751 ///
11752 static bool equivalentAddressValues(Value *A, Value *B) {
11753   // Test if the values are trivially equivalent.
11754   if (A == B) return true;
11755   
11756   // Test if the values come form identical arithmetic instructions.
11757   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11758   // its only used to compare two uses within the same basic block, which
11759   // means that they'll always either have the same value or one of them
11760   // will have an undefined value.
11761   if (isa<BinaryOperator>(A) ||
11762       isa<CastInst>(A) ||
11763       isa<PHINode>(A) ||
11764       isa<GetElementPtrInst>(A))
11765     if (Instruction *BI = dyn_cast<Instruction>(B))
11766       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11767         return true;
11768   
11769   // Otherwise they may not be equivalent.
11770   return false;
11771 }
11772
11773 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11774 // return the llvm.dbg.declare.
11775 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11776   if (!V->hasNUses(2))
11777     return 0;
11778   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11779        UI != E; ++UI) {
11780     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11781       return DI;
11782     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11783       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11784         return DI;
11785       }
11786   }
11787   return 0;
11788 }
11789
11790 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11791   Value *Val = SI.getOperand(0);
11792   Value *Ptr = SI.getOperand(1);
11793
11794   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11795     EraseInstFromFunction(SI);
11796     ++NumCombined;
11797     return 0;
11798   }
11799   
11800   // If the RHS is an alloca with a single use, zapify the store, making the
11801   // alloca dead.
11802   // If the RHS is an alloca with a two uses, the other one being a 
11803   // llvm.dbg.declare, zapify the store and the declare, making the
11804   // alloca dead.  We must do this to prevent declare's from affecting
11805   // codegen.
11806   if (!SI.isVolatile()) {
11807     if (Ptr->hasOneUse()) {
11808       if (isa<AllocaInst>(Ptr)) {
11809         EraseInstFromFunction(SI);
11810         ++NumCombined;
11811         return 0;
11812       }
11813       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11814         if (isa<AllocaInst>(GEP->getOperand(0))) {
11815           if (GEP->getOperand(0)->hasOneUse()) {
11816             EraseInstFromFunction(SI);
11817             ++NumCombined;
11818             return 0;
11819           }
11820           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11821             EraseInstFromFunction(*DI);
11822             EraseInstFromFunction(SI);
11823             ++NumCombined;
11824             return 0;
11825           }
11826         }
11827       }
11828     }
11829     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11830       EraseInstFromFunction(*DI);
11831       EraseInstFromFunction(SI);
11832       ++NumCombined;
11833       return 0;
11834     }
11835   }
11836
11837   // Attempt to improve the alignment.
11838   if (TD) {
11839     unsigned KnownAlign =
11840       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11841     if (KnownAlign >
11842         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11843                                   SI.getAlignment()))
11844       SI.setAlignment(KnownAlign);
11845   }
11846
11847   // Do really simple DSE, to catch cases where there are several consecutive
11848   // stores to the same location, separated by a few arithmetic operations. This
11849   // situation often occurs with bitfield accesses.
11850   BasicBlock::iterator BBI = &SI;
11851   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11852        --ScanInsts) {
11853     --BBI;
11854     // Don't count debug info directives, lest they affect codegen,
11855     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11856     // It is necessary for correctness to skip those that feed into a
11857     // llvm.dbg.declare, as these are not present when debugging is off.
11858     if (isa<DbgInfoIntrinsic>(BBI) ||
11859         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11860       ScanInsts++;
11861       continue;
11862     }    
11863     
11864     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11865       // Prev store isn't volatile, and stores to the same location?
11866       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11867                                                           SI.getOperand(1))) {
11868         ++NumDeadStore;
11869         ++BBI;
11870         EraseInstFromFunction(*PrevSI);
11871         continue;
11872       }
11873       break;
11874     }
11875     
11876     // If this is a load, we have to stop.  However, if the loaded value is from
11877     // the pointer we're loading and is producing the pointer we're storing,
11878     // then *this* store is dead (X = load P; store X -> P).
11879     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11880       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11881           !SI.isVolatile()) {
11882         EraseInstFromFunction(SI);
11883         ++NumCombined;
11884         return 0;
11885       }
11886       // Otherwise, this is a load from some other location.  Stores before it
11887       // may not be dead.
11888       break;
11889     }
11890     
11891     // Don't skip over loads or things that can modify memory.
11892     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11893       break;
11894   }
11895   
11896   
11897   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11898
11899   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11900   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11901     if (!isa<UndefValue>(Val)) {
11902       SI.setOperand(0, UndefValue::get(Val->getType()));
11903       if (Instruction *U = dyn_cast<Instruction>(Val))
11904         Worklist.Add(U);  // Dropped a use.
11905       ++NumCombined;
11906     }
11907     return 0;  // Do not modify these!
11908   }
11909
11910   // store undef, Ptr -> noop
11911   if (isa<UndefValue>(Val)) {
11912     EraseInstFromFunction(SI);
11913     ++NumCombined;
11914     return 0;
11915   }
11916
11917   // If the pointer destination is a cast, see if we can fold the cast into the
11918   // source instead.
11919   if (isa<CastInst>(Ptr))
11920     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11921       return Res;
11922   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11923     if (CE->isCast())
11924       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11925         return Res;
11926
11927   
11928   // If this store is the last instruction in the basic block (possibly
11929   // excepting debug info instructions and the pointer bitcasts that feed
11930   // into them), and if the block ends with an unconditional branch, try
11931   // to move it to the successor block.
11932   BBI = &SI; 
11933   do {
11934     ++BBI;
11935   } while (isa<DbgInfoIntrinsic>(BBI) ||
11936            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11937   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11938     if (BI->isUnconditional())
11939       if (SimplifyStoreAtEndOfBlock(SI))
11940         return 0;  // xform done!
11941   
11942   return 0;
11943 }
11944
11945 /// SimplifyStoreAtEndOfBlock - Turn things like:
11946 ///   if () { *P = v1; } else { *P = v2 }
11947 /// into a phi node with a store in the successor.
11948 ///
11949 /// Simplify things like:
11950 ///   *P = v1; if () { *P = v2; }
11951 /// into a phi node with a store in the successor.
11952 ///
11953 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11954   BasicBlock *StoreBB = SI.getParent();
11955   
11956   // Check to see if the successor block has exactly two incoming edges.  If
11957   // so, see if the other predecessor contains a store to the same location.
11958   // if so, insert a PHI node (if needed) and move the stores down.
11959   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11960   
11961   // Determine whether Dest has exactly two predecessors and, if so, compute
11962   // the other predecessor.
11963   pred_iterator PI = pred_begin(DestBB);
11964   BasicBlock *OtherBB = 0;
11965   if (*PI != StoreBB)
11966     OtherBB = *PI;
11967   ++PI;
11968   if (PI == pred_end(DestBB))
11969     return false;
11970   
11971   if (*PI != StoreBB) {
11972     if (OtherBB)
11973       return false;
11974     OtherBB = *PI;
11975   }
11976   if (++PI != pred_end(DestBB))
11977     return false;
11978
11979   // Bail out if all the relevant blocks aren't distinct (this can happen,
11980   // for example, if SI is in an infinite loop)
11981   if (StoreBB == DestBB || OtherBB == DestBB)
11982     return false;
11983
11984   // Verify that the other block ends in a branch and is not otherwise empty.
11985   BasicBlock::iterator BBI = OtherBB->getTerminator();
11986   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11987   if (!OtherBr || BBI == OtherBB->begin())
11988     return false;
11989   
11990   // If the other block ends in an unconditional branch, check for the 'if then
11991   // else' case.  there is an instruction before the branch.
11992   StoreInst *OtherStore = 0;
11993   if (OtherBr->isUnconditional()) {
11994     --BBI;
11995     // Skip over debugging info.
11996     while (isa<DbgInfoIntrinsic>(BBI) ||
11997            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11998       if (BBI==OtherBB->begin())
11999         return false;
12000       --BBI;
12001     }
12002     // If this isn't a store, isn't a store to the same location, or if the
12003     // alignments differ, bail out.
12004     OtherStore = dyn_cast<StoreInst>(BBI);
12005     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12006         OtherStore->getAlignment() != SI.getAlignment())
12007       return false;
12008   } else {
12009     // Otherwise, the other block ended with a conditional branch. If one of the
12010     // destinations is StoreBB, then we have the if/then case.
12011     if (OtherBr->getSuccessor(0) != StoreBB && 
12012         OtherBr->getSuccessor(1) != StoreBB)
12013       return false;
12014     
12015     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12016     // if/then triangle.  See if there is a store to the same ptr as SI that
12017     // lives in OtherBB.
12018     for (;; --BBI) {
12019       // Check to see if we find the matching store.
12020       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12021         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12022             OtherStore->getAlignment() != SI.getAlignment())
12023           return false;
12024         break;
12025       }
12026       // If we find something that may be using or overwriting the stored
12027       // value, or if we run out of instructions, we can't do the xform.
12028       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12029           BBI == OtherBB->begin())
12030         return false;
12031     }
12032     
12033     // In order to eliminate the store in OtherBr, we have to
12034     // make sure nothing reads or overwrites the stored value in
12035     // StoreBB.
12036     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12037       // FIXME: This should really be AA driven.
12038       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12039         return false;
12040     }
12041   }
12042   
12043   // Insert a PHI node now if we need it.
12044   Value *MergedVal = OtherStore->getOperand(0);
12045   if (MergedVal != SI.getOperand(0)) {
12046     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12047     PN->reserveOperandSpace(2);
12048     PN->addIncoming(SI.getOperand(0), SI.getParent());
12049     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12050     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12051   }
12052   
12053   // Advance to a place where it is safe to insert the new store and
12054   // insert it.
12055   BBI = DestBB->getFirstNonPHI();
12056   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12057                                     OtherStore->isVolatile(),
12058                                     SI.getAlignment()), *BBI);
12059   
12060   // Nuke the old stores.
12061   EraseInstFromFunction(SI);
12062   EraseInstFromFunction(*OtherStore);
12063   ++NumCombined;
12064   return true;
12065 }
12066
12067
12068 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12069   // Change br (not X), label True, label False to: br X, label False, True
12070   Value *X = 0;
12071   BasicBlock *TrueDest;
12072   BasicBlock *FalseDest;
12073   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12074       !isa<Constant>(X)) {
12075     // Swap Destinations and condition...
12076     BI.setCondition(X);
12077     BI.setSuccessor(0, FalseDest);
12078     BI.setSuccessor(1, TrueDest);
12079     return &BI;
12080   }
12081
12082   // Cannonicalize fcmp_one -> fcmp_oeq
12083   FCmpInst::Predicate FPred; Value *Y;
12084   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12085                              TrueDest, FalseDest)) &&
12086       BI.getCondition()->hasOneUse())
12087     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12088         FPred == FCmpInst::FCMP_OGE) {
12089       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12090       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12091       
12092       // Swap Destinations and condition.
12093       BI.setSuccessor(0, FalseDest);
12094       BI.setSuccessor(1, TrueDest);
12095       Worklist.Add(Cond);
12096       return &BI;
12097     }
12098
12099   // Cannonicalize icmp_ne -> icmp_eq
12100   ICmpInst::Predicate IPred;
12101   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12102                       TrueDest, FalseDest)) &&
12103       BI.getCondition()->hasOneUse())
12104     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12105         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12106         IPred == ICmpInst::ICMP_SGE) {
12107       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12108       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12109       // Swap Destinations and condition.
12110       BI.setSuccessor(0, FalseDest);
12111       BI.setSuccessor(1, TrueDest);
12112       Worklist.Add(Cond);
12113       return &BI;
12114     }
12115
12116   return 0;
12117 }
12118
12119 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12120   Value *Cond = SI.getCondition();
12121   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12122     if (I->getOpcode() == Instruction::Add)
12123       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12124         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12125         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12126           SI.setOperand(i,
12127                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12128                                                 AddRHS));
12129         SI.setOperand(0, I->getOperand(0));
12130         Worklist.Add(I);
12131         return &SI;
12132       }
12133   }
12134   return 0;
12135 }
12136
12137 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12138   Value *Agg = EV.getAggregateOperand();
12139
12140   if (!EV.hasIndices())
12141     return ReplaceInstUsesWith(EV, Agg);
12142
12143   if (Constant *C = dyn_cast<Constant>(Agg)) {
12144     if (isa<UndefValue>(C))
12145       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12146       
12147     if (isa<ConstantAggregateZero>(C))
12148       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12149
12150     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12151       // Extract the element indexed by the first index out of the constant
12152       Value *V = C->getOperand(*EV.idx_begin());
12153       if (EV.getNumIndices() > 1)
12154         // Extract the remaining indices out of the constant indexed by the
12155         // first index
12156         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12157       else
12158         return ReplaceInstUsesWith(EV, V);
12159     }
12160     return 0; // Can't handle other constants
12161   } 
12162   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12163     // We're extracting from an insertvalue instruction, compare the indices
12164     const unsigned *exti, *exte, *insi, *inse;
12165     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12166          exte = EV.idx_end(), inse = IV->idx_end();
12167          exti != exte && insi != inse;
12168          ++exti, ++insi) {
12169       if (*insi != *exti)
12170         // The insert and extract both reference distinctly different elements.
12171         // This means the extract is not influenced by the insert, and we can
12172         // replace the aggregate operand of the extract with the aggregate
12173         // operand of the insert. i.e., replace
12174         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12175         // %E = extractvalue { i32, { i32 } } %I, 0
12176         // with
12177         // %E = extractvalue { i32, { i32 } } %A, 0
12178         return ExtractValueInst::Create(IV->getAggregateOperand(),
12179                                         EV.idx_begin(), EV.idx_end());
12180     }
12181     if (exti == exte && insi == inse)
12182       // Both iterators are at the end: Index lists are identical. Replace
12183       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12184       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12185       // with "i32 42"
12186       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12187     if (exti == exte) {
12188       // The extract list is a prefix of the insert list. i.e. replace
12189       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12190       // %E = extractvalue { i32, { i32 } } %I, 1
12191       // with
12192       // %X = extractvalue { i32, { i32 } } %A, 1
12193       // %E = insertvalue { i32 } %X, i32 42, 0
12194       // by switching the order of the insert and extract (though the
12195       // insertvalue should be left in, since it may have other uses).
12196       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12197                                                  EV.idx_begin(), EV.idx_end());
12198       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12199                                      insi, inse);
12200     }
12201     if (insi == inse)
12202       // The insert list is a prefix of the extract list
12203       // We can simply remove the common indices from the extract and make it
12204       // operate on the inserted value instead of the insertvalue result.
12205       // i.e., replace
12206       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12207       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12208       // with
12209       // %E extractvalue { i32 } { i32 42 }, 0
12210       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12211                                       exti, exte);
12212   }
12213   // Can't simplify extracts from other values. Note that nested extracts are
12214   // already simplified implicitely by the above (extract ( extract (insert) )
12215   // will be translated into extract ( insert ( extract ) ) first and then just
12216   // the value inserted, if appropriate).
12217   return 0;
12218 }
12219
12220 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12221 /// is to leave as a vector operation.
12222 static bool CheapToScalarize(Value *V, bool isConstant) {
12223   if (isa<ConstantAggregateZero>(V)) 
12224     return true;
12225   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12226     if (isConstant) return true;
12227     // If all elts are the same, we can extract.
12228     Constant *Op0 = C->getOperand(0);
12229     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12230       if (C->getOperand(i) != Op0)
12231         return false;
12232     return true;
12233   }
12234   Instruction *I = dyn_cast<Instruction>(V);
12235   if (!I) return false;
12236   
12237   // Insert element gets simplified to the inserted element or is deleted if
12238   // this is constant idx extract element and its a constant idx insertelt.
12239   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12240       isa<ConstantInt>(I->getOperand(2)))
12241     return true;
12242   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12243     return true;
12244   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12245     if (BO->hasOneUse() &&
12246         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12247          CheapToScalarize(BO->getOperand(1), isConstant)))
12248       return true;
12249   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12250     if (CI->hasOneUse() &&
12251         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12252          CheapToScalarize(CI->getOperand(1), isConstant)))
12253       return true;
12254   
12255   return false;
12256 }
12257
12258 /// Read and decode a shufflevector mask.
12259 ///
12260 /// It turns undef elements into values that are larger than the number of
12261 /// elements in the input.
12262 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12263   unsigned NElts = SVI->getType()->getNumElements();
12264   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12265     return std::vector<unsigned>(NElts, 0);
12266   if (isa<UndefValue>(SVI->getOperand(2)))
12267     return std::vector<unsigned>(NElts, 2*NElts);
12268
12269   std::vector<unsigned> Result;
12270   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12271   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12272     if (isa<UndefValue>(*i))
12273       Result.push_back(NElts*2);  // undef -> 8
12274     else
12275       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12276   return Result;
12277 }
12278
12279 /// FindScalarElement - Given a vector and an element number, see if the scalar
12280 /// value is already around as a register, for example if it were inserted then
12281 /// extracted from the vector.
12282 static Value *FindScalarElement(Value *V, unsigned EltNo,
12283                                 LLVMContext *Context) {
12284   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12285   const VectorType *PTy = cast<VectorType>(V->getType());
12286   unsigned Width = PTy->getNumElements();
12287   if (EltNo >= Width)  // Out of range access.
12288     return UndefValue::get(PTy->getElementType());
12289   
12290   if (isa<UndefValue>(V))
12291     return UndefValue::get(PTy->getElementType());
12292   else if (isa<ConstantAggregateZero>(V))
12293     return Constant::getNullValue(PTy->getElementType());
12294   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12295     return CP->getOperand(EltNo);
12296   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12297     // If this is an insert to a variable element, we don't know what it is.
12298     if (!isa<ConstantInt>(III->getOperand(2))) 
12299       return 0;
12300     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12301     
12302     // If this is an insert to the element we are looking for, return the
12303     // inserted value.
12304     if (EltNo == IIElt) 
12305       return III->getOperand(1);
12306     
12307     // Otherwise, the insertelement doesn't modify the value, recurse on its
12308     // vector input.
12309     return FindScalarElement(III->getOperand(0), EltNo, Context);
12310   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12311     unsigned LHSWidth =
12312       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12313     unsigned InEl = getShuffleMask(SVI)[EltNo];
12314     if (InEl < LHSWidth)
12315       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12316     else if (InEl < LHSWidth*2)
12317       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12318     else
12319       return UndefValue::get(PTy->getElementType());
12320   }
12321   
12322   // Otherwise, we don't know.
12323   return 0;
12324 }
12325
12326 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12327   // If vector val is undef, replace extract with scalar undef.
12328   if (isa<UndefValue>(EI.getOperand(0)))
12329     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12330
12331   // If vector val is constant 0, replace extract with scalar 0.
12332   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12333     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12334   
12335   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12336     // If vector val is constant with all elements the same, replace EI with
12337     // that element. When the elements are not identical, we cannot replace yet
12338     // (we do that below, but only when the index is constant).
12339     Constant *op0 = C->getOperand(0);
12340     for (unsigned i = 1; i != C->getNumOperands(); ++i)
12341       if (C->getOperand(i) != op0) {
12342         op0 = 0; 
12343         break;
12344       }
12345     if (op0)
12346       return ReplaceInstUsesWith(EI, op0);
12347   }
12348   
12349   // If extracting a specified index from the vector, see if we can recursively
12350   // find a previously computed scalar that was inserted into the vector.
12351   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12352     unsigned IndexVal = IdxC->getZExtValue();
12353     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12354       
12355     // If this is extracting an invalid index, turn this into undef, to avoid
12356     // crashing the code below.
12357     if (IndexVal >= VectorWidth)
12358       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12359     
12360     // This instruction only demands the single element from the input vector.
12361     // If the input vector has a single use, simplify it based on this use
12362     // property.
12363     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12364       APInt UndefElts(VectorWidth, 0);
12365       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12366       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12367                                                 DemandedMask, UndefElts)) {
12368         EI.setOperand(0, V);
12369         return &EI;
12370       }
12371     }
12372     
12373     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12374       return ReplaceInstUsesWith(EI, Elt);
12375     
12376     // If the this extractelement is directly using a bitcast from a vector of
12377     // the same number of elements, see if we can find the source element from
12378     // it.  In this case, we will end up needing to bitcast the scalars.
12379     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12380       if (const VectorType *VT = 
12381               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12382         if (VT->getNumElements() == VectorWidth)
12383           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12384                                              IndexVal, Context))
12385             return new BitCastInst(Elt, EI.getType());
12386     }
12387   }
12388   
12389   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12390     // Push extractelement into predecessor operation if legal and
12391     // profitable to do so
12392     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12393       if (I->hasOneUse() &&
12394           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12395         Value *newEI0 =
12396           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12397                                         EI.getName()+".lhs");
12398         Value *newEI1 =
12399           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12400                                         EI.getName()+".rhs");
12401         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12402       }
12403     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12404       // Extracting the inserted element?
12405       if (IE->getOperand(2) == EI.getOperand(1))
12406         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12407       // If the inserted and extracted elements are constants, they must not
12408       // be the same value, extract from the pre-inserted value instead.
12409       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12410         Worklist.AddValue(EI.getOperand(0));
12411         EI.setOperand(0, IE->getOperand(0));
12412         return &EI;
12413       }
12414     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12415       // If this is extracting an element from a shufflevector, figure out where
12416       // it came from and extract from the appropriate input element instead.
12417       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12418         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12419         Value *Src;
12420         unsigned LHSWidth =
12421           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12422
12423         if (SrcIdx < LHSWidth)
12424           Src = SVI->getOperand(0);
12425         else if (SrcIdx < LHSWidth*2) {
12426           SrcIdx -= LHSWidth;
12427           Src = SVI->getOperand(1);
12428         } else {
12429           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12430         }
12431         return ExtractElementInst::Create(Src,
12432                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12433                                           false));
12434       }
12435     }
12436     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12437   }
12438   return 0;
12439 }
12440
12441 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12442 /// elements from either LHS or RHS, return the shuffle mask and true. 
12443 /// Otherwise, return false.
12444 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12445                                          std::vector<Constant*> &Mask,
12446                                          LLVMContext *Context) {
12447   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12448          "Invalid CollectSingleShuffleElements");
12449   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12450
12451   if (isa<UndefValue>(V)) {
12452     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12453     return true;
12454   } else if (V == LHS) {
12455     for (unsigned i = 0; i != NumElts; ++i)
12456       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12457     return true;
12458   } else if (V == RHS) {
12459     for (unsigned i = 0; i != NumElts; ++i)
12460       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12461     return true;
12462   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12463     // If this is an insert of an extract from some other vector, include it.
12464     Value *VecOp    = IEI->getOperand(0);
12465     Value *ScalarOp = IEI->getOperand(1);
12466     Value *IdxOp    = IEI->getOperand(2);
12467     
12468     if (!isa<ConstantInt>(IdxOp))
12469       return false;
12470     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12471     
12472     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12473       // Okay, we can handle this if the vector we are insertinting into is
12474       // transitively ok.
12475       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12476         // If so, update the mask to reflect the inserted undef.
12477         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12478         return true;
12479       }      
12480     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12481       if (isa<ConstantInt>(EI->getOperand(1)) &&
12482           EI->getOperand(0)->getType() == V->getType()) {
12483         unsigned ExtractedIdx =
12484           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12485         
12486         // This must be extracting from either LHS or RHS.
12487         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12488           // Okay, we can handle this if the vector we are insertinting into is
12489           // transitively ok.
12490           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12491             // If so, update the mask to reflect the inserted value.
12492             if (EI->getOperand(0) == LHS) {
12493               Mask[InsertedIdx % NumElts] = 
12494                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12495             } else {
12496               assert(EI->getOperand(0) == RHS);
12497               Mask[InsertedIdx % NumElts] = 
12498                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12499               
12500             }
12501             return true;
12502           }
12503         }
12504       }
12505     }
12506   }
12507   // TODO: Handle shufflevector here!
12508   
12509   return false;
12510 }
12511
12512 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12513 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12514 /// that computes V and the LHS value of the shuffle.
12515 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12516                                      Value *&RHS, LLVMContext *Context) {
12517   assert(isa<VectorType>(V->getType()) && 
12518          (RHS == 0 || V->getType() == RHS->getType()) &&
12519          "Invalid shuffle!");
12520   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12521
12522   if (isa<UndefValue>(V)) {
12523     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12524     return V;
12525   } else if (isa<ConstantAggregateZero>(V)) {
12526     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12527     return V;
12528   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12529     // If this is an insert of an extract from some other vector, include it.
12530     Value *VecOp    = IEI->getOperand(0);
12531     Value *ScalarOp = IEI->getOperand(1);
12532     Value *IdxOp    = IEI->getOperand(2);
12533     
12534     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12535       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12536           EI->getOperand(0)->getType() == V->getType()) {
12537         unsigned ExtractedIdx =
12538           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12539         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12540         
12541         // Either the extracted from or inserted into vector must be RHSVec,
12542         // otherwise we'd end up with a shuffle of three inputs.
12543         if (EI->getOperand(0) == RHS || RHS == 0) {
12544           RHS = EI->getOperand(0);
12545           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12546           Mask[InsertedIdx % NumElts] = 
12547             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12548           return V;
12549         }
12550         
12551         if (VecOp == RHS) {
12552           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12553                                             RHS, Context);
12554           // Everything but the extracted element is replaced with the RHS.
12555           for (unsigned i = 0; i != NumElts; ++i) {
12556             if (i != InsertedIdx)
12557               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12558           }
12559           return V;
12560         }
12561         
12562         // If this insertelement is a chain that comes from exactly these two
12563         // vectors, return the vector and the effective shuffle.
12564         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12565                                          Context))
12566           return EI->getOperand(0);
12567         
12568       }
12569     }
12570   }
12571   // TODO: Handle shufflevector here!
12572   
12573   // Otherwise, can't do anything fancy.  Return an identity vector.
12574   for (unsigned i = 0; i != NumElts; ++i)
12575     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12576   return V;
12577 }
12578
12579 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12580   Value *VecOp    = IE.getOperand(0);
12581   Value *ScalarOp = IE.getOperand(1);
12582   Value *IdxOp    = IE.getOperand(2);
12583   
12584   // Inserting an undef or into an undefined place, remove this.
12585   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12586     ReplaceInstUsesWith(IE, VecOp);
12587   
12588   // If the inserted element was extracted from some other vector, and if the 
12589   // indexes are constant, try to turn this into a shufflevector operation.
12590   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12591     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12592         EI->getOperand(0)->getType() == IE.getType()) {
12593       unsigned NumVectorElts = IE.getType()->getNumElements();
12594       unsigned ExtractedIdx =
12595         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12596       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12597       
12598       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12599         return ReplaceInstUsesWith(IE, VecOp);
12600       
12601       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12602         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12603       
12604       // If we are extracting a value from a vector, then inserting it right
12605       // back into the same place, just use the input vector.
12606       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12607         return ReplaceInstUsesWith(IE, VecOp);      
12608       
12609       // If this insertelement isn't used by some other insertelement, turn it
12610       // (and any insertelements it points to), into one big shuffle.
12611       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12612         std::vector<Constant*> Mask;
12613         Value *RHS = 0;
12614         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12615         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12616         // We now have a shuffle of LHS, RHS, Mask.
12617         return new ShuffleVectorInst(LHS, RHS,
12618                                      ConstantVector::get(Mask));
12619       }
12620     }
12621   }
12622
12623   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12624   APInt UndefElts(VWidth, 0);
12625   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12626   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12627     return &IE;
12628
12629   return 0;
12630 }
12631
12632
12633 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12634   Value *LHS = SVI.getOperand(0);
12635   Value *RHS = SVI.getOperand(1);
12636   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12637
12638   bool MadeChange = false;
12639
12640   // Undefined shuffle mask -> undefined value.
12641   if (isa<UndefValue>(SVI.getOperand(2)))
12642     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12643
12644   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12645
12646   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12647     return 0;
12648
12649   APInt UndefElts(VWidth, 0);
12650   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12651   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12652     LHS = SVI.getOperand(0);
12653     RHS = SVI.getOperand(1);
12654     MadeChange = true;
12655   }
12656   
12657   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12658   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12659   if (LHS == RHS || isa<UndefValue>(LHS)) {
12660     if (isa<UndefValue>(LHS) && LHS == RHS) {
12661       // shuffle(undef,undef,mask) -> undef.
12662       return ReplaceInstUsesWith(SVI, LHS);
12663     }
12664     
12665     // Remap any references to RHS to use LHS.
12666     std::vector<Constant*> Elts;
12667     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12668       if (Mask[i] >= 2*e)
12669         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12670       else {
12671         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12672             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12673           Mask[i] = 2*e;     // Turn into undef.
12674           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12675         } else {
12676           Mask[i] = Mask[i] % e;  // Force to LHS.
12677           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12678         }
12679       }
12680     }
12681     SVI.setOperand(0, SVI.getOperand(1));
12682     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12683     SVI.setOperand(2, ConstantVector::get(Elts));
12684     LHS = SVI.getOperand(0);
12685     RHS = SVI.getOperand(1);
12686     MadeChange = true;
12687   }
12688   
12689   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12690   bool isLHSID = true, isRHSID = true;
12691     
12692   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12693     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12694     // Is this an identity shuffle of the LHS value?
12695     isLHSID &= (Mask[i] == i);
12696       
12697     // Is this an identity shuffle of the RHS value?
12698     isRHSID &= (Mask[i]-e == i);
12699   }
12700
12701   // Eliminate identity shuffles.
12702   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12703   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12704   
12705   // If the LHS is a shufflevector itself, see if we can combine it with this
12706   // one without producing an unusual shuffle.  Here we are really conservative:
12707   // we are absolutely afraid of producing a shuffle mask not in the input
12708   // program, because the code gen may not be smart enough to turn a merged
12709   // shuffle into two specific shuffles: it may produce worse code.  As such,
12710   // we only merge two shuffles if the result is one of the two input shuffle
12711   // masks.  In this case, merging the shuffles just removes one instruction,
12712   // which we know is safe.  This is good for things like turning:
12713   // (splat(splat)) -> splat.
12714   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12715     if (isa<UndefValue>(RHS)) {
12716       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12717
12718       std::vector<unsigned> NewMask;
12719       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12720         if (Mask[i] >= 2*e)
12721           NewMask.push_back(2*e);
12722         else
12723           NewMask.push_back(LHSMask[Mask[i]]);
12724       
12725       // If the result mask is equal to the src shuffle or this shuffle mask, do
12726       // the replacement.
12727       if (NewMask == LHSMask || NewMask == Mask) {
12728         unsigned LHSInNElts =
12729           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12730         std::vector<Constant*> Elts;
12731         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12732           if (NewMask[i] >= LHSInNElts*2) {
12733             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12734           } else {
12735             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12736           }
12737         }
12738         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12739                                      LHSSVI->getOperand(1),
12740                                      ConstantVector::get(Elts));
12741       }
12742     }
12743   }
12744
12745   return MadeChange ? &SVI : 0;
12746 }
12747
12748
12749
12750
12751 /// TryToSinkInstruction - Try to move the specified instruction from its
12752 /// current block into the beginning of DestBlock, which can only happen if it's
12753 /// safe to move the instruction past all of the instructions between it and the
12754 /// end of its block.
12755 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12756   assert(I->hasOneUse() && "Invariants didn't hold!");
12757
12758   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12759   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12760     return false;
12761
12762   // Do not sink alloca instructions out of the entry block.
12763   if (isa<AllocaInst>(I) && I->getParent() ==
12764         &DestBlock->getParent()->getEntryBlock())
12765     return false;
12766
12767   // We can only sink load instructions if there is nothing between the load and
12768   // the end of block that could change the value.
12769   if (I->mayReadFromMemory()) {
12770     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12771          Scan != E; ++Scan)
12772       if (Scan->mayWriteToMemory())
12773         return false;
12774   }
12775
12776   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12777
12778   CopyPrecedingStopPoint(I, InsertPos);
12779   I->moveBefore(InsertPos);
12780   ++NumSunkInst;
12781   return true;
12782 }
12783
12784
12785 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12786 /// all reachable code to the worklist.
12787 ///
12788 /// This has a couple of tricks to make the code faster and more powerful.  In
12789 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12790 /// them to the worklist (this significantly speeds up instcombine on code where
12791 /// many instructions are dead or constant).  Additionally, if we find a branch
12792 /// whose condition is a known constant, we only visit the reachable successors.
12793 ///
12794 static bool AddReachableCodeToWorklist(BasicBlock *BB, 
12795                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12796                                        InstCombiner &IC,
12797                                        const TargetData *TD) {
12798   bool MadeIRChange = false;
12799   SmallVector<BasicBlock*, 256> Worklist;
12800   Worklist.push_back(BB);
12801   
12802   std::vector<Instruction*> InstrsForInstCombineWorklist;
12803   InstrsForInstCombineWorklist.reserve(128);
12804
12805   SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
12806   
12807   while (!Worklist.empty()) {
12808     BB = Worklist.back();
12809     Worklist.pop_back();
12810     
12811     // We have now visited this block!  If we've already been here, ignore it.
12812     if (!Visited.insert(BB)) continue;
12813
12814     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12815       Instruction *Inst = BBI++;
12816       
12817       // DCE instruction if trivially dead.
12818       if (isInstructionTriviallyDead(Inst)) {
12819         ++NumDeadInst;
12820         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12821         Inst->eraseFromParent();
12822         continue;
12823       }
12824       
12825       // ConstantProp instruction if trivially constant.
12826       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
12827         if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12828           DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12829                        << *Inst << '\n');
12830           Inst->replaceAllUsesWith(C);
12831           ++NumConstProp;
12832           Inst->eraseFromParent();
12833           continue;
12834         }
12835       
12836       
12837       
12838       if (TD) {
12839         // See if we can constant fold its operands.
12840         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
12841              i != e; ++i) {
12842           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
12843           if (CE == 0) continue;
12844           
12845           // If we already folded this constant, don't try again.
12846           if (!FoldedConstants.insert(CE))
12847             continue;
12848           
12849           Constant *NewC = ConstantFoldConstantExpression(CE, TD);
12850           if (NewC && NewC != CE) {
12851             *i = NewC;
12852             MadeIRChange = true;
12853           }
12854         }
12855       }
12856       
12857
12858       InstrsForInstCombineWorklist.push_back(Inst);
12859     }
12860
12861     // Recursively visit successors.  If this is a branch or switch on a
12862     // constant, only visit the reachable successor.
12863     TerminatorInst *TI = BB->getTerminator();
12864     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12865       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12866         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12867         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12868         Worklist.push_back(ReachableBB);
12869         continue;
12870       }
12871     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12872       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12873         // See if this is an explicit destination.
12874         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12875           if (SI->getCaseValue(i) == Cond) {
12876             BasicBlock *ReachableBB = SI->getSuccessor(i);
12877             Worklist.push_back(ReachableBB);
12878             continue;
12879           }
12880         
12881         // Otherwise it is the default destination.
12882         Worklist.push_back(SI->getSuccessor(0));
12883         continue;
12884       }
12885     }
12886     
12887     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12888       Worklist.push_back(TI->getSuccessor(i));
12889   }
12890   
12891   // Once we've found all of the instructions to add to instcombine's worklist,
12892   // add them in reverse order.  This way instcombine will visit from the top
12893   // of the function down.  This jives well with the way that it adds all uses
12894   // of instructions to the worklist after doing a transformation, thus avoiding
12895   // some N^2 behavior in pathological cases.
12896   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12897                               InstrsForInstCombineWorklist.size());
12898   
12899   return MadeIRChange;
12900 }
12901
12902 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12903   MadeIRChange = false;
12904   
12905   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12906         << F.getNameStr() << "\n");
12907
12908   {
12909     // Do a depth-first traversal of the function, populate the worklist with
12910     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12911     // track of which blocks we visit.
12912     SmallPtrSet<BasicBlock*, 64> Visited;
12913     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12914
12915     // Do a quick scan over the function.  If we find any blocks that are
12916     // unreachable, remove any instructions inside of them.  This prevents
12917     // the instcombine code from having to deal with some bad special cases.
12918     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12919       if (!Visited.count(BB)) {
12920         Instruction *Term = BB->getTerminator();
12921         while (Term != BB->begin()) {   // Remove instrs bottom-up
12922           BasicBlock::iterator I = Term; --I;
12923
12924           DEBUG(errs() << "IC: DCE: " << *I << '\n');
12925           // A debug intrinsic shouldn't force another iteration if we weren't
12926           // going to do one without it.
12927           if (!isa<DbgInfoIntrinsic>(I)) {
12928             ++NumDeadInst;
12929             MadeIRChange = true;
12930           }
12931
12932           // If I is not void type then replaceAllUsesWith undef.
12933           // This allows ValueHandlers and custom metadata to adjust itself.
12934           if (!I->getType()->isVoidTy())
12935             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12936           I->eraseFromParent();
12937         }
12938       }
12939   }
12940
12941   while (!Worklist.isEmpty()) {
12942     Instruction *I = Worklist.RemoveOne();
12943     if (I == 0) continue;  // skip null values.
12944
12945     // Check to see if we can DCE the instruction.
12946     if (isInstructionTriviallyDead(I)) {
12947       DEBUG(errs() << "IC: DCE: " << *I << '\n');
12948       EraseInstFromFunction(*I);
12949       ++NumDeadInst;
12950       MadeIRChange = true;
12951       continue;
12952     }
12953
12954     // Instruction isn't dead, see if we can constant propagate it.
12955     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
12956       if (Constant *C = ConstantFoldInstruction(I, TD)) {
12957         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12958
12959         // Add operands to the worklist.
12960         ReplaceInstUsesWith(*I, C);
12961         ++NumConstProp;
12962         EraseInstFromFunction(*I);
12963         MadeIRChange = true;
12964         continue;
12965       }
12966
12967     // See if we can trivially sink this instruction to a successor basic block.
12968     if (I->hasOneUse()) {
12969       BasicBlock *BB = I->getParent();
12970       Instruction *UserInst = cast<Instruction>(I->use_back());
12971       BasicBlock *UserParent;
12972       
12973       // Get the block the use occurs in.
12974       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
12975         UserParent = PN->getIncomingBlock(I->use_begin().getUse());
12976       else
12977         UserParent = UserInst->getParent();
12978       
12979       if (UserParent != BB) {
12980         bool UserIsSuccessor = false;
12981         // See if the user is one of our successors.
12982         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12983           if (*SI == UserParent) {
12984             UserIsSuccessor = true;
12985             break;
12986           }
12987
12988         // If the user is one of our immediate successors, and if that successor
12989         // only has us as a predecessors (we'd have to split the critical edge
12990         // otherwise), we can keep going.
12991         if (UserIsSuccessor && UserParent->getSinglePredecessor())
12992           // Okay, the CFG is simple enough, try to sink this instruction.
12993           MadeIRChange |= TryToSinkInstruction(I, UserParent);
12994       }
12995     }
12996
12997     // Now that we have an instruction, try combining it to simplify it.
12998     Builder->SetInsertPoint(I->getParent(), I);
12999     
13000 #ifndef NDEBUG
13001     std::string OrigI;
13002 #endif
13003     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
13004     DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13005
13006     if (Instruction *Result = visit(*I)) {
13007       ++NumCombined;
13008       // Should we replace the old instruction with a new one?
13009       if (Result != I) {
13010         DEBUG(errs() << "IC: Old = " << *I << '\n'
13011                      << "    New = " << *Result << '\n');
13012
13013         // Everything uses the new instruction now.
13014         I->replaceAllUsesWith(Result);
13015
13016         // Push the new instruction and any users onto the worklist.
13017         Worklist.Add(Result);
13018         Worklist.AddUsersToWorkList(*Result);
13019
13020         // Move the name to the new instruction first.
13021         Result->takeName(I);
13022
13023         // Insert the new instruction into the basic block...
13024         BasicBlock *InstParent = I->getParent();
13025         BasicBlock::iterator InsertPos = I;
13026
13027         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13028           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13029             ++InsertPos;
13030
13031         InstParent->getInstList().insert(InsertPos, Result);
13032
13033         EraseInstFromFunction(*I);
13034       } else {
13035 #ifndef NDEBUG
13036         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13037                      << "    New = " << *I << '\n');
13038 #endif
13039
13040         // If the instruction was modified, it's possible that it is now dead.
13041         // if so, remove it.
13042         if (isInstructionTriviallyDead(I)) {
13043           EraseInstFromFunction(*I);
13044         } else {
13045           Worklist.Add(I);
13046           Worklist.AddUsersToWorkList(*I);
13047         }
13048       }
13049       MadeIRChange = true;
13050     }
13051   }
13052
13053   Worklist.Zap();
13054   return MadeIRChange;
13055 }
13056
13057
13058 bool InstCombiner::runOnFunction(Function &F) {
13059   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13060   Context = &F.getContext();
13061   TD = getAnalysisIfAvailable<TargetData>();
13062
13063   
13064   /// Builder - This is an IRBuilder that automatically inserts new
13065   /// instructions into the worklist when they are created.
13066   IRBuilder<true, TargetFolder, InstCombineIRInserter> 
13067     TheBuilder(F.getContext(), TargetFolder(TD),
13068                InstCombineIRInserter(Worklist));
13069   Builder = &TheBuilder;
13070   
13071   bool EverMadeChange = false;
13072
13073   // Iterate while there is work to do.
13074   unsigned Iteration = 0;
13075   while (DoOneIteration(F, Iteration++))
13076     EverMadeChange = true;
13077   
13078   Builder = 0;
13079   return EverMadeChange;
13080 }
13081
13082 FunctionPass *llvm::createInstructionCombiningPass() {
13083   return new InstCombiner();
13084 }