Speculatively revert r8644[3-5], they seem to be leading to infinite loops in
[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 /// commonIntCastTransforms - This function implements the common transforms
8293 /// for trunc, zext, and sext.
8294 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8295   if (Instruction *Result = commonCastTransforms(CI))
8296     return Result;
8297
8298   Value *Src = CI.getOperand(0);
8299   const Type *SrcTy = Src->getType();
8300   const Type *DestTy = CI.getType();
8301   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8302   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8303
8304   // See if we can simplify any instructions used by the LHS whose sole 
8305   // purpose is to compute bits we don't care about.
8306   if (SimplifyDemandedInstructionBits(CI))
8307     return &CI;
8308
8309   // If the source isn't an instruction or has more than one use then we
8310   // can't do anything more. 
8311   Instruction *SrcI = dyn_cast<Instruction>(Src);
8312   if (!SrcI || !Src->hasOneUse())
8313     return 0;
8314
8315   // Attempt to propagate the cast into the instruction for int->int casts.
8316   int NumCastsRemoved = 0;
8317   // Only do this if the dest type is a simple type, don't convert the
8318   // expression tree to something weird like i93 unless the source is also
8319   // strange.
8320   if (TD &&
8321       (TD->isLegalInteger(DestTy->getScalarType()->getPrimitiveSizeInBits()) ||
8322        !TD->isLegalInteger((SrcI->getType()->getScalarType()
8323                             ->getPrimitiveSizeInBits()))) &&
8324       CanEvaluateInDifferentType(SrcI, DestTy,
8325                                  CI.getOpcode(), NumCastsRemoved)) {
8326     // If this cast is a truncate, evaluting in a different type always
8327     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8328     // we need to do an AND to maintain the clear top-part of the computation,
8329     // so we require that the input have eliminated at least one cast.  If this
8330     // is a sign extension, we insert two new casts (to do the extension) so we
8331     // require that two casts have been eliminated.
8332     bool DoXForm = false;
8333     bool JustReplace = false;
8334     switch (CI.getOpcode()) {
8335     default:
8336       // All the others use floating point so we shouldn't actually 
8337       // get here because of the check above.
8338       llvm_unreachable("Unknown cast type");
8339     case Instruction::Trunc:
8340       DoXForm = true;
8341       break;
8342     case Instruction::ZExt: {
8343       DoXForm = NumCastsRemoved >= 1;
8344       
8345       if (!DoXForm && 0) {
8346         // If it's unnecessary to issue an AND to clear the high bits, it's
8347         // always profitable to do this xform.
8348         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8349         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8350         if (MaskedValueIsZero(TryRes, Mask))
8351           return ReplaceInstUsesWith(CI, TryRes);
8352         
8353         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8354           if (TryI->use_empty())
8355             EraseInstFromFunction(*TryI);
8356       }
8357       break;
8358     }
8359     case Instruction::SExt: {
8360       DoXForm = NumCastsRemoved >= 2;
8361       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8362         // If we do not have to emit the truncate + sext pair, then it's always
8363         // profitable to do this xform.
8364         //
8365         // It's not safe to eliminate the trunc + sext pair if one of the
8366         // eliminated cast is a truncate. e.g.
8367         // t2 = trunc i32 t1 to i16
8368         // t3 = sext i16 t2 to i32
8369         // !=
8370         // i32 t1
8371         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8372         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8373         if (NumSignBits > (DestBitSize - SrcBitSize))
8374           return ReplaceInstUsesWith(CI, TryRes);
8375         
8376         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8377           if (TryI->use_empty())
8378             EraseInstFromFunction(*TryI);
8379       }
8380       break;
8381     }
8382     }
8383     
8384     if (DoXForm) {
8385       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8386             " to avoid cast: " << CI);
8387       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8388                                            CI.getOpcode() == Instruction::SExt);
8389       if (JustReplace)
8390         // Just replace this cast with the result.
8391         return ReplaceInstUsesWith(CI, Res);
8392
8393       assert(Res->getType() == DestTy);
8394       switch (CI.getOpcode()) {
8395       default: llvm_unreachable("Unknown cast type!");
8396       case Instruction::Trunc:
8397         // Just replace this cast with the result.
8398         return ReplaceInstUsesWith(CI, Res);
8399       case Instruction::ZExt: {
8400         assert(SrcBitSize < DestBitSize && "Not a zext?");
8401
8402         // If the high bits are already zero, just replace this cast with the
8403         // result.
8404         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8405         if (MaskedValueIsZero(Res, Mask))
8406           return ReplaceInstUsesWith(CI, Res);
8407
8408         // We need to emit an AND to clear the high bits.
8409         Constant *C = ConstantInt::get(*Context, 
8410                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8411         return BinaryOperator::CreateAnd(Res, C);
8412       }
8413       case Instruction::SExt: {
8414         // If the high bits are already filled with sign bit, just replace this
8415         // cast with the result.
8416         unsigned NumSignBits = ComputeNumSignBits(Res);
8417         if (NumSignBits > (DestBitSize - SrcBitSize))
8418           return ReplaceInstUsesWith(CI, Res);
8419
8420         // We need to emit a cast to truncate, then a cast to sext.
8421         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8422       }
8423       }
8424     }
8425   }
8426   
8427   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8428   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8429
8430   switch (SrcI->getOpcode()) {
8431   case Instruction::Add:
8432   case Instruction::Mul:
8433   case Instruction::And:
8434   case Instruction::Or:
8435   case Instruction::Xor:
8436     // If we are discarding information, rewrite.
8437     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8438       // Don't insert two casts unless at least one can be eliminated.
8439       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8440           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8441         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8442         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8443         return BinaryOperator::Create(
8444             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8445       }
8446     }
8447
8448     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8449     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8450         SrcI->getOpcode() == Instruction::Xor &&
8451         Op1 == ConstantInt::getTrue(*Context) &&
8452         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8453       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8454       return BinaryOperator::CreateXor(New,
8455                                       ConstantInt::get(CI.getType(), 1));
8456     }
8457     break;
8458
8459   case Instruction::Shl: {
8460     // Canonicalize trunc inside shl, if we can.
8461     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8462     if (CI && DestBitSize < SrcBitSize &&
8463         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8464       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8465       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8466       return BinaryOperator::CreateShl(Op0c, Op1c);
8467     }
8468     break;
8469   }
8470   }
8471   return 0;
8472 }
8473
8474 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8475   if (Instruction *Result = commonIntCastTransforms(CI))
8476     return Result;
8477   
8478   Value *Src = CI.getOperand(0);
8479   const Type *Ty = CI.getType();
8480   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8481   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8482
8483   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8484   if (DestBitWidth == 1) {
8485     Constant *One = ConstantInt::get(Src->getType(), 1);
8486     Src = Builder->CreateAnd(Src, One, "tmp");
8487     Value *Zero = Constant::getNullValue(Src->getType());
8488     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8489   }
8490
8491   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8492   ConstantInt *ShAmtV = 0;
8493   Value *ShiftOp = 0;
8494   if (Src->hasOneUse() &&
8495       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8496     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8497     
8498     // Get a mask for the bits shifting in.
8499     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8500     if (MaskedValueIsZero(ShiftOp, Mask)) {
8501       if (ShAmt >= DestBitWidth)        // All zeros.
8502         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8503       
8504       // Okay, we can shrink this.  Truncate the input, then return a new
8505       // shift.
8506       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8507       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8508       return BinaryOperator::CreateLShr(V1, V2);
8509     }
8510   }
8511   
8512   return 0;
8513 }
8514
8515 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8516 /// in order to eliminate the icmp.
8517 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8518                                              bool DoXform) {
8519   // If we are just checking for a icmp eq of a single bit and zext'ing it
8520   // to an integer, then shift the bit to the appropriate place and then
8521   // cast to integer to avoid the comparison.
8522   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8523     const APInt &Op1CV = Op1C->getValue();
8524       
8525     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8526     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8527     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8528         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8529       if (!DoXform) return ICI;
8530
8531       Value *In = ICI->getOperand(0);
8532       Value *Sh = ConstantInt::get(In->getType(),
8533                                    In->getType()->getScalarSizeInBits()-1);
8534       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8535       if (In->getType() != CI.getType())
8536         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8537
8538       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8539         Constant *One = ConstantInt::get(In->getType(), 1);
8540         In = Builder->CreateXor(In, One, In->getName()+".not");
8541       }
8542
8543       return ReplaceInstUsesWith(CI, In);
8544     }
8545       
8546       
8547       
8548     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8549     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8550     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8551     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8552     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8553     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8554     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8555     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8556     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8557         // This only works for EQ and NE
8558         ICI->isEquality()) {
8559       // If Op1C some other power of two, convert:
8560       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8561       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8562       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8563       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8564         
8565       APInt KnownZeroMask(~KnownZero);
8566       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8567         if (!DoXform) return ICI;
8568
8569         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8570         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8571           // (X&4) == 2 --> false
8572           // (X&4) != 2 --> true
8573           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8574           Res = ConstantExpr::getZExt(Res, CI.getType());
8575           return ReplaceInstUsesWith(CI, Res);
8576         }
8577           
8578         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8579         Value *In = ICI->getOperand(0);
8580         if (ShiftAmt) {
8581           // Perform a logical shr by shiftamt.
8582           // Insert the shift to put the result in the low bit.
8583           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8584                                    In->getName()+".lobit");
8585         }
8586           
8587         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8588           Constant *One = ConstantInt::get(In->getType(), 1);
8589           In = Builder->CreateXor(In, One, "tmp");
8590         }
8591           
8592         if (CI.getType() == In->getType())
8593           return ReplaceInstUsesWith(CI, In);
8594         else
8595           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8596       }
8597     }
8598   }
8599
8600   return 0;
8601 }
8602
8603 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8604   // If one of the common conversion will work ..
8605   if (Instruction *Result = commonIntCastTransforms(CI))
8606     return Result;
8607
8608   Value *Src = CI.getOperand(0);
8609
8610   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8611   // types and if the sizes are just right we can convert this into a logical
8612   // 'and' which will be much cheaper than the pair of casts.
8613   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8614     // Get the sizes of the types involved.  We know that the intermediate type
8615     // will be smaller than A or C, but don't know the relation between A and C.
8616     Value *A = CSrc->getOperand(0);
8617     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8618     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8619     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8620     // If we're actually extending zero bits, then if
8621     // SrcSize <  DstSize: zext(a & mask)
8622     // SrcSize == DstSize: a & mask
8623     // SrcSize  > DstSize: trunc(a) & mask
8624     if (SrcSize < DstSize) {
8625       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8626       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8627       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8628       return new ZExtInst(And, CI.getType());
8629     }
8630     
8631     if (SrcSize == DstSize) {
8632       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8633       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8634                                                            AndValue));
8635     }
8636     if (SrcSize > DstSize) {
8637       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8638       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8639       return BinaryOperator::CreateAnd(Trunc, 
8640                                        ConstantInt::get(Trunc->getType(),
8641                                                                AndValue));
8642     }
8643   }
8644
8645   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8646     return transformZExtICmp(ICI, CI);
8647
8648   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8649   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8650     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8651     // of the (zext icmp) will be transformed.
8652     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8653     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8654     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8655         (transformZExtICmp(LHS, CI, false) ||
8656          transformZExtICmp(RHS, CI, false))) {
8657       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8658       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8659       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8660     }
8661   }
8662
8663   // zext(trunc(t) & C) -> (t & zext(C)).
8664   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8665     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8666       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8667         Value *TI0 = TI->getOperand(0);
8668         if (TI0->getType() == CI.getType())
8669           return
8670             BinaryOperator::CreateAnd(TI0,
8671                                 ConstantExpr::getZExt(C, CI.getType()));
8672       }
8673
8674   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8675   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8676     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8677       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8678         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8679             And->getOperand(1) == C)
8680           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8681             Value *TI0 = TI->getOperand(0);
8682             if (TI0->getType() == CI.getType()) {
8683               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8684               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8685               return BinaryOperator::CreateXor(NewAnd, ZC);
8686             }
8687           }
8688
8689   return 0;
8690 }
8691
8692 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8693   if (Instruction *I = commonIntCastTransforms(CI))
8694     return I;
8695   
8696   Value *Src = CI.getOperand(0);
8697   
8698   // Canonicalize sign-extend from i1 to a select.
8699   if (Src->getType() == Type::getInt1Ty(*Context))
8700     return SelectInst::Create(Src,
8701                               Constant::getAllOnesValue(CI.getType()),
8702                               Constant::getNullValue(CI.getType()));
8703
8704   // See if the value being truncated is already sign extended.  If so, just
8705   // eliminate the trunc/sext pair.
8706   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8707     Value *Op = cast<User>(Src)->getOperand(0);
8708     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8709     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8710     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8711     unsigned NumSignBits = ComputeNumSignBits(Op);
8712
8713     if (OpBits == DestBits) {
8714       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8715       // bits, it is already ready.
8716       if (NumSignBits > DestBits-MidBits)
8717         return ReplaceInstUsesWith(CI, Op);
8718     } else if (OpBits < DestBits) {
8719       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8720       // bits, just sext from i32.
8721       if (NumSignBits > OpBits-MidBits)
8722         return new SExtInst(Op, CI.getType(), "tmp");
8723     } else {
8724       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8725       // bits, just truncate to i32.
8726       if (NumSignBits > OpBits-MidBits)
8727         return new TruncInst(Op, CI.getType(), "tmp");
8728     }
8729   }
8730
8731   // If the input is a shl/ashr pair of a same constant, then this is a sign
8732   // extension from a smaller value.  If we could trust arbitrary bitwidth
8733   // integers, we could turn this into a truncate to the smaller bit and then
8734   // use a sext for the whole extension.  Since we don't, look deeper and check
8735   // for a truncate.  If the source and dest are the same type, eliminate the
8736   // trunc and extend and just do shifts.  For example, turn:
8737   //   %a = trunc i32 %i to i8
8738   //   %b = shl i8 %a, 6
8739   //   %c = ashr i8 %b, 6
8740   //   %d = sext i8 %c to i32
8741   // into:
8742   //   %a = shl i32 %i, 30
8743   //   %d = ashr i32 %a, 30
8744   Value *A = 0;
8745   ConstantInt *BA = 0, *CA = 0;
8746   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8747                         m_ConstantInt(CA))) &&
8748       BA == CA && isa<TruncInst>(A)) {
8749     Value *I = cast<TruncInst>(A)->getOperand(0);
8750     if (I->getType() == CI.getType()) {
8751       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8752       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8753       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8754       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8755       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8756       return BinaryOperator::CreateAShr(I, ShAmtV);
8757     }
8758   }
8759   
8760   return 0;
8761 }
8762
8763 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8764 /// in the specified FP type without changing its value.
8765 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8766                               LLVMContext *Context) {
8767   bool losesInfo;
8768   APFloat F = CFP->getValueAPF();
8769   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8770   if (!losesInfo)
8771     return ConstantFP::get(*Context, F);
8772   return 0;
8773 }
8774
8775 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8776 /// through it until we get the source value.
8777 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8778   if (Instruction *I = dyn_cast<Instruction>(V))
8779     if (I->getOpcode() == Instruction::FPExt)
8780       return LookThroughFPExtensions(I->getOperand(0), Context);
8781   
8782   // If this value is a constant, return the constant in the smallest FP type
8783   // that can accurately represent it.  This allows us to turn
8784   // (float)((double)X+2.0) into x+2.0f.
8785   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8786     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8787       return V;  // No constant folding of this.
8788     // See if the value can be truncated to float and then reextended.
8789     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8790       return V;
8791     if (CFP->getType() == Type::getDoubleTy(*Context))
8792       return V;  // Won't shrink.
8793     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8794       return V;
8795     // Don't try to shrink to various long double types.
8796   }
8797   
8798   return V;
8799 }
8800
8801 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8802   if (Instruction *I = commonCastTransforms(CI))
8803     return I;
8804   
8805   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8806   // smaller than the destination type, we can eliminate the truncate by doing
8807   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8808   // many builtins (sqrt, etc).
8809   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8810   if (OpI && OpI->hasOneUse()) {
8811     switch (OpI->getOpcode()) {
8812     default: break;
8813     case Instruction::FAdd:
8814     case Instruction::FSub:
8815     case Instruction::FMul:
8816     case Instruction::FDiv:
8817     case Instruction::FRem:
8818       const Type *SrcTy = OpI->getType();
8819       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8820       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8821       if (LHSTrunc->getType() != SrcTy && 
8822           RHSTrunc->getType() != SrcTy) {
8823         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8824         // If the source types were both smaller than the destination type of
8825         // the cast, do this xform.
8826         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8827             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8828           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8829           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8830           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8831         }
8832       }
8833       break;  
8834     }
8835   }
8836   return 0;
8837 }
8838
8839 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8840   return commonCastTransforms(CI);
8841 }
8842
8843 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8844   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8845   if (OpI == 0)
8846     return commonCastTransforms(FI);
8847
8848   // fptoui(uitofp(X)) --> X
8849   // fptoui(sitofp(X)) --> X
8850   // This is safe if the intermediate type has enough bits in its mantissa to
8851   // accurately represent all values of X.  For example, do not do this with
8852   // i64->float->i64.  This is also safe for sitofp case, because any negative
8853   // 'X' value would cause an undefined result for the fptoui. 
8854   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8855       OpI->getOperand(0)->getType() == FI.getType() &&
8856       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8857                     OpI->getType()->getFPMantissaWidth())
8858     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8859
8860   return commonCastTransforms(FI);
8861 }
8862
8863 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8864   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8865   if (OpI == 0)
8866     return commonCastTransforms(FI);
8867   
8868   // fptosi(sitofp(X)) --> X
8869   // fptosi(uitofp(X)) --> X
8870   // This is safe if the intermediate type has enough bits in its mantissa to
8871   // accurately represent all values of X.  For example, do not do this with
8872   // i64->float->i64.  This is also safe for sitofp case, because any negative
8873   // 'X' value would cause an undefined result for the fptoui. 
8874   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8875       OpI->getOperand(0)->getType() == FI.getType() &&
8876       (int)FI.getType()->getScalarSizeInBits() <=
8877                     OpI->getType()->getFPMantissaWidth())
8878     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8879   
8880   return commonCastTransforms(FI);
8881 }
8882
8883 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8884   return commonCastTransforms(CI);
8885 }
8886
8887 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8888   return commonCastTransforms(CI);
8889 }
8890
8891 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8892   // If the destination integer type is smaller than the intptr_t type for
8893   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8894   // trunc to be exposed to other transforms.  Don't do this for extending
8895   // ptrtoint's, because we don't know if the target sign or zero extends its
8896   // pointers.
8897   if (TD &&
8898       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8899     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8900                                        TD->getIntPtrType(CI.getContext()),
8901                                        "tmp");
8902     return new TruncInst(P, CI.getType());
8903   }
8904   
8905   return commonPointerCastTransforms(CI);
8906 }
8907
8908 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8909   // If the source integer type is larger than the intptr_t type for
8910   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8911   // allows the trunc to be exposed to other transforms.  Don't do this for
8912   // extending inttoptr's, because we don't know if the target sign or zero
8913   // extends to pointers.
8914   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8915       TD->getPointerSizeInBits()) {
8916     Value *P = Builder->CreateTrunc(CI.getOperand(0),
8917                                     TD->getIntPtrType(CI.getContext()), "tmp");
8918     return new IntToPtrInst(P, CI.getType());
8919   }
8920   
8921   if (Instruction *I = commonCastTransforms(CI))
8922     return I;
8923
8924   return 0;
8925 }
8926
8927 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8928   // If the operands are integer typed then apply the integer transforms,
8929   // otherwise just apply the common ones.
8930   Value *Src = CI.getOperand(0);
8931   const Type *SrcTy = Src->getType();
8932   const Type *DestTy = CI.getType();
8933
8934   if (isa<PointerType>(SrcTy)) {
8935     if (Instruction *I = commonPointerCastTransforms(CI))
8936       return I;
8937   } else {
8938     if (Instruction *Result = commonCastTransforms(CI))
8939       return Result;
8940   }
8941
8942
8943   // Get rid of casts from one type to the same type. These are useless and can
8944   // be replaced by the operand.
8945   if (DestTy == Src->getType())
8946     return ReplaceInstUsesWith(CI, Src);
8947
8948   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8949     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8950     const Type *DstElTy = DstPTy->getElementType();
8951     const Type *SrcElTy = SrcPTy->getElementType();
8952     
8953     // If the address spaces don't match, don't eliminate the bitcast, which is
8954     // required for changing types.
8955     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8956       return 0;
8957     
8958     // If we are casting a alloca to a pointer to a type of the same
8959     // size, rewrite the allocation instruction to allocate the "right" type.
8960     // There is no need to modify malloc calls because it is their bitcast that
8961     // needs to be cleaned up.
8962     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
8963       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8964         return V;
8965     
8966     // If the source and destination are pointers, and this cast is equivalent
8967     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8968     // This can enhance SROA and other transforms that want type-safe pointers.
8969     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8970     unsigned NumZeros = 0;
8971     while (SrcElTy != DstElTy && 
8972            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8973            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8974       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8975       ++NumZeros;
8976     }
8977
8978     // If we found a path from the src to dest, create the getelementptr now.
8979     if (SrcElTy == DstElTy) {
8980       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8981       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8982                                                ((Instruction*) NULL));
8983     }
8984   }
8985
8986   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8987     if (DestVTy->getNumElements() == 1) {
8988       if (!isa<VectorType>(SrcTy)) {
8989         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8990         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8991                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8992       }
8993       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8994     }
8995   }
8996
8997   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8998     if (SrcVTy->getNumElements() == 1) {
8999       if (!isa<VectorType>(DestTy)) {
9000         Value *Elem = 
9001           Builder->CreateExtractElement(Src,
9002                             Constant::getNullValue(Type::getInt32Ty(*Context)));
9003         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9004       }
9005     }
9006   }
9007
9008   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9009     if (SVI->hasOneUse()) {
9010       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9011       // a bitconvert to a vector with the same # elts.
9012       if (isa<VectorType>(DestTy) && 
9013           cast<VectorType>(DestTy)->getNumElements() ==
9014                 SVI->getType()->getNumElements() &&
9015           SVI->getType()->getNumElements() ==
9016             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9017         CastInst *Tmp;
9018         // If either of the operands is a cast from CI.getType(), then
9019         // evaluating the shuffle in the casted destination's type will allow
9020         // us to eliminate at least one cast.
9021         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9022              Tmp->getOperand(0)->getType() == DestTy) ||
9023             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9024              Tmp->getOperand(0)->getType() == DestTy)) {
9025           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9026           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
9027           // Return a new shuffle vector.  Use the same element ID's, as we
9028           // know the vector types match #elts.
9029           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9030         }
9031       }
9032     }
9033   }
9034   return 0;
9035 }
9036
9037 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9038 ///   %C = or %A, %B
9039 ///   %D = select %cond, %C, %A
9040 /// into:
9041 ///   %C = select %cond, %B, 0
9042 ///   %D = or %A, %C
9043 ///
9044 /// Assuming that the specified instruction is an operand to the select, return
9045 /// a bitmask indicating which operands of this instruction are foldable if they
9046 /// equal the other incoming value of the select.
9047 ///
9048 static unsigned GetSelectFoldableOperands(Instruction *I) {
9049   switch (I->getOpcode()) {
9050   case Instruction::Add:
9051   case Instruction::Mul:
9052   case Instruction::And:
9053   case Instruction::Or:
9054   case Instruction::Xor:
9055     return 3;              // Can fold through either operand.
9056   case Instruction::Sub:   // Can only fold on the amount subtracted.
9057   case Instruction::Shl:   // Can only fold on the shift amount.
9058   case Instruction::LShr:
9059   case Instruction::AShr:
9060     return 1;
9061   default:
9062     return 0;              // Cannot fold
9063   }
9064 }
9065
9066 /// GetSelectFoldableConstant - For the same transformation as the previous
9067 /// function, return the identity constant that goes into the select.
9068 static Constant *GetSelectFoldableConstant(Instruction *I,
9069                                            LLVMContext *Context) {
9070   switch (I->getOpcode()) {
9071   default: llvm_unreachable("This cannot happen!");
9072   case Instruction::Add:
9073   case Instruction::Sub:
9074   case Instruction::Or:
9075   case Instruction::Xor:
9076   case Instruction::Shl:
9077   case Instruction::LShr:
9078   case Instruction::AShr:
9079     return Constant::getNullValue(I->getType());
9080   case Instruction::And:
9081     return Constant::getAllOnesValue(I->getType());
9082   case Instruction::Mul:
9083     return ConstantInt::get(I->getType(), 1);
9084   }
9085 }
9086
9087 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9088 /// have the same opcode and only one use each.  Try to simplify this.
9089 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9090                                           Instruction *FI) {
9091   if (TI->getNumOperands() == 1) {
9092     // If this is a non-volatile load or a cast from the same type,
9093     // merge.
9094     if (TI->isCast()) {
9095       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9096         return 0;
9097     } else {
9098       return 0;  // unknown unary op.
9099     }
9100
9101     // Fold this by inserting a select from the input values.
9102     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9103                                           FI->getOperand(0), SI.getName()+".v");
9104     InsertNewInstBefore(NewSI, SI);
9105     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9106                             TI->getType());
9107   }
9108
9109   // Only handle binary operators here.
9110   if (!isa<BinaryOperator>(TI))
9111     return 0;
9112
9113   // Figure out if the operations have any operands in common.
9114   Value *MatchOp, *OtherOpT, *OtherOpF;
9115   bool MatchIsOpZero;
9116   if (TI->getOperand(0) == FI->getOperand(0)) {
9117     MatchOp  = TI->getOperand(0);
9118     OtherOpT = TI->getOperand(1);
9119     OtherOpF = FI->getOperand(1);
9120     MatchIsOpZero = true;
9121   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9122     MatchOp  = TI->getOperand(1);
9123     OtherOpT = TI->getOperand(0);
9124     OtherOpF = FI->getOperand(0);
9125     MatchIsOpZero = false;
9126   } else if (!TI->isCommutative()) {
9127     return 0;
9128   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9129     MatchOp  = TI->getOperand(0);
9130     OtherOpT = TI->getOperand(1);
9131     OtherOpF = FI->getOperand(0);
9132     MatchIsOpZero = true;
9133   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9134     MatchOp  = TI->getOperand(1);
9135     OtherOpT = TI->getOperand(0);
9136     OtherOpF = FI->getOperand(1);
9137     MatchIsOpZero = true;
9138   } else {
9139     return 0;
9140   }
9141
9142   // If we reach here, they do have operations in common.
9143   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9144                                          OtherOpF, SI.getName()+".v");
9145   InsertNewInstBefore(NewSI, SI);
9146
9147   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9148     if (MatchIsOpZero)
9149       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9150     else
9151       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9152   }
9153   llvm_unreachable("Shouldn't get here");
9154   return 0;
9155 }
9156
9157 static bool isSelect01(Constant *C1, Constant *C2) {
9158   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9159   if (!C1I)
9160     return false;
9161   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9162   if (!C2I)
9163     return false;
9164   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9165 }
9166
9167 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9168 /// facilitate further optimization.
9169 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9170                                             Value *FalseVal) {
9171   // See the comment above GetSelectFoldableOperands for a description of the
9172   // transformation we are doing here.
9173   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9174     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9175         !isa<Constant>(FalseVal)) {
9176       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9177         unsigned OpToFold = 0;
9178         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9179           OpToFold = 1;
9180         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9181           OpToFold = 2;
9182         }
9183
9184         if (OpToFold) {
9185           Constant *C = GetSelectFoldableConstant(TVI, Context);
9186           Value *OOp = TVI->getOperand(2-OpToFold);
9187           // Avoid creating select between 2 constants unless it's selecting
9188           // between 0 and 1.
9189           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9190             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9191             InsertNewInstBefore(NewSel, SI);
9192             NewSel->takeName(TVI);
9193             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9194               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9195             llvm_unreachable("Unknown instruction!!");
9196           }
9197         }
9198       }
9199     }
9200   }
9201
9202   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9203     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9204         !isa<Constant>(TrueVal)) {
9205       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9206         unsigned OpToFold = 0;
9207         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9208           OpToFold = 1;
9209         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9210           OpToFold = 2;
9211         }
9212
9213         if (OpToFold) {
9214           Constant *C = GetSelectFoldableConstant(FVI, Context);
9215           Value *OOp = FVI->getOperand(2-OpToFold);
9216           // Avoid creating select between 2 constants unless it's selecting
9217           // between 0 and 1.
9218           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9219             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9220             InsertNewInstBefore(NewSel, SI);
9221             NewSel->takeName(FVI);
9222             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9223               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9224             llvm_unreachable("Unknown instruction!!");
9225           }
9226         }
9227       }
9228     }
9229   }
9230
9231   return 0;
9232 }
9233
9234 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9235 /// ICmpInst as its first operand.
9236 ///
9237 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9238                                                    ICmpInst *ICI) {
9239   bool Changed = false;
9240   ICmpInst::Predicate Pred = ICI->getPredicate();
9241   Value *CmpLHS = ICI->getOperand(0);
9242   Value *CmpRHS = ICI->getOperand(1);
9243   Value *TrueVal = SI.getTrueValue();
9244   Value *FalseVal = SI.getFalseValue();
9245
9246   // Check cases where the comparison is with a constant that
9247   // can be adjusted to fit the min/max idiom. We may edit ICI in
9248   // place here, so make sure the select is the only user.
9249   if (ICI->hasOneUse())
9250     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9251       switch (Pred) {
9252       default: break;
9253       case ICmpInst::ICMP_ULT:
9254       case ICmpInst::ICMP_SLT: {
9255         // X < MIN ? T : F  -->  F
9256         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9257           return ReplaceInstUsesWith(SI, FalseVal);
9258         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9259         Constant *AdjustedRHS = SubOne(CI);
9260         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9261             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9262           Pred = ICmpInst::getSwappedPredicate(Pred);
9263           CmpRHS = AdjustedRHS;
9264           std::swap(FalseVal, TrueVal);
9265           ICI->setPredicate(Pred);
9266           ICI->setOperand(1, CmpRHS);
9267           SI.setOperand(1, TrueVal);
9268           SI.setOperand(2, FalseVal);
9269           Changed = true;
9270         }
9271         break;
9272       }
9273       case ICmpInst::ICMP_UGT:
9274       case ICmpInst::ICMP_SGT: {
9275         // X > MAX ? T : F  -->  F
9276         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9277           return ReplaceInstUsesWith(SI, FalseVal);
9278         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9279         Constant *AdjustedRHS = AddOne(CI);
9280         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9281             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9282           Pred = ICmpInst::getSwappedPredicate(Pred);
9283           CmpRHS = AdjustedRHS;
9284           std::swap(FalseVal, TrueVal);
9285           ICI->setPredicate(Pred);
9286           ICI->setOperand(1, CmpRHS);
9287           SI.setOperand(1, TrueVal);
9288           SI.setOperand(2, FalseVal);
9289           Changed = true;
9290         }
9291         break;
9292       }
9293       }
9294
9295       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9296       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9297       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9298       if (match(TrueVal, m_ConstantInt<-1>()) &&
9299           match(FalseVal, m_ConstantInt<0>()))
9300         Pred = ICI->getPredicate();
9301       else if (match(TrueVal, m_ConstantInt<0>()) &&
9302                match(FalseVal, m_ConstantInt<-1>()))
9303         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9304       
9305       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9306         // If we are just checking for a icmp eq of a single bit and zext'ing it
9307         // to an integer, then shift the bit to the appropriate place and then
9308         // cast to integer to avoid the comparison.
9309         const APInt &Op1CV = CI->getValue();
9310     
9311         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9312         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9313         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9314             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9315           Value *In = ICI->getOperand(0);
9316           Value *Sh = ConstantInt::get(In->getType(),
9317                                        In->getType()->getScalarSizeInBits()-1);
9318           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9319                                                         In->getName()+".lobit"),
9320                                    *ICI);
9321           if (In->getType() != SI.getType())
9322             In = CastInst::CreateIntegerCast(In, SI.getType(),
9323                                              true/*SExt*/, "tmp", ICI);
9324     
9325           if (Pred == ICmpInst::ICMP_SGT)
9326             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9327                                        In->getName()+".not"), *ICI);
9328     
9329           return ReplaceInstUsesWith(SI, In);
9330         }
9331       }
9332     }
9333
9334   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9335     // Transform (X == Y) ? X : Y  -> Y
9336     if (Pred == ICmpInst::ICMP_EQ)
9337       return ReplaceInstUsesWith(SI, FalseVal);
9338     // Transform (X != Y) ? X : Y  -> X
9339     if (Pred == ICmpInst::ICMP_NE)
9340       return ReplaceInstUsesWith(SI, TrueVal);
9341     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9342
9343   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9344     // Transform (X == Y) ? Y : X  -> X
9345     if (Pred == ICmpInst::ICMP_EQ)
9346       return ReplaceInstUsesWith(SI, FalseVal);
9347     // Transform (X != Y) ? Y : X  -> Y
9348     if (Pred == ICmpInst::ICMP_NE)
9349       return ReplaceInstUsesWith(SI, TrueVal);
9350     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9351   }
9352
9353   /// NOTE: if we wanted to, this is where to detect integer ABS
9354
9355   return Changed ? &SI : 0;
9356 }
9357
9358
9359 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9360 /// PHI node (but the two may be in different blocks).  See if the true/false
9361 /// values (V) are live in all of the predecessor blocks of the PHI.  For
9362 /// example, cases like this cannot be mapped:
9363 ///
9364 ///   X = phi [ C1, BB1], [C2, BB2]
9365 ///   Y = add
9366 ///   Z = select X, Y, 0
9367 ///
9368 /// because Y is not live in BB1/BB2.
9369 ///
9370 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9371                                                    const SelectInst &SI) {
9372   // If the value is a non-instruction value like a constant or argument, it
9373   // can always be mapped.
9374   const Instruction *I = dyn_cast<Instruction>(V);
9375   if (I == 0) return true;
9376   
9377   // If V is a PHI node defined in the same block as the condition PHI, we can
9378   // map the arguments.
9379   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9380   
9381   if (const PHINode *VP = dyn_cast<PHINode>(I))
9382     if (VP->getParent() == CondPHI->getParent())
9383       return true;
9384   
9385   // Otherwise, if the PHI and select are defined in the same block and if V is
9386   // defined in a different block, then we can transform it.
9387   if (SI.getParent() == CondPHI->getParent() &&
9388       I->getParent() != CondPHI->getParent())
9389     return true;
9390   
9391   // Otherwise we have a 'hard' case and we can't tell without doing more
9392   // detailed dominator based analysis, punt.
9393   return false;
9394 }
9395
9396 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9397   Value *CondVal = SI.getCondition();
9398   Value *TrueVal = SI.getTrueValue();
9399   Value *FalseVal = SI.getFalseValue();
9400
9401   // select true, X, Y  -> X
9402   // select false, X, Y -> Y
9403   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9404     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9405
9406   // select C, X, X -> X
9407   if (TrueVal == FalseVal)
9408     return ReplaceInstUsesWith(SI, TrueVal);
9409
9410   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9411     return ReplaceInstUsesWith(SI, FalseVal);
9412   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9413     return ReplaceInstUsesWith(SI, TrueVal);
9414   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9415     if (isa<Constant>(TrueVal))
9416       return ReplaceInstUsesWith(SI, TrueVal);
9417     else
9418       return ReplaceInstUsesWith(SI, FalseVal);
9419   }
9420
9421   if (SI.getType() == Type::getInt1Ty(*Context)) {
9422     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9423       if (C->getZExtValue()) {
9424         // Change: A = select B, true, C --> A = or B, C
9425         return BinaryOperator::CreateOr(CondVal, FalseVal);
9426       } else {
9427         // Change: A = select B, false, C --> A = and !B, C
9428         Value *NotCond =
9429           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9430                                              "not."+CondVal->getName()), SI);
9431         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9432       }
9433     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9434       if (C->getZExtValue() == false) {
9435         // Change: A = select B, C, false --> A = and B, C
9436         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9437       } else {
9438         // Change: A = select B, C, true --> A = or !B, C
9439         Value *NotCond =
9440           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9441                                              "not."+CondVal->getName()), SI);
9442         return BinaryOperator::CreateOr(NotCond, TrueVal);
9443       }
9444     }
9445     
9446     // select a, b, a  -> a&b
9447     // select a, a, b  -> a|b
9448     if (CondVal == TrueVal)
9449       return BinaryOperator::CreateOr(CondVal, FalseVal);
9450     else if (CondVal == FalseVal)
9451       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9452   }
9453
9454   // Selecting between two integer constants?
9455   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9456     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9457       // select C, 1, 0 -> zext C to int
9458       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9459         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9460       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9461         // select C, 0, 1 -> zext !C to int
9462         Value *NotCond =
9463           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9464                                                "not."+CondVal->getName()), SI);
9465         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9466       }
9467
9468       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9469         // If one of the constants is zero (we know they can't both be) and we
9470         // have an icmp instruction with zero, and we have an 'and' with the
9471         // non-constant value, eliminate this whole mess.  This corresponds to
9472         // cases like this: ((X & 27) ? 27 : 0)
9473         if (TrueValC->isZero() || FalseValC->isZero())
9474           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9475               cast<Constant>(IC->getOperand(1))->isNullValue())
9476             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9477               if (ICA->getOpcode() == Instruction::And &&
9478                   isa<ConstantInt>(ICA->getOperand(1)) &&
9479                   (ICA->getOperand(1) == TrueValC ||
9480                    ICA->getOperand(1) == FalseValC) &&
9481                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9482                 // Okay, now we know that everything is set up, we just don't
9483                 // know whether we have a icmp_ne or icmp_eq and whether the 
9484                 // true or false val is the zero.
9485                 bool ShouldNotVal = !TrueValC->isZero();
9486                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9487                 Value *V = ICA;
9488                 if (ShouldNotVal)
9489                   V = InsertNewInstBefore(BinaryOperator::Create(
9490                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9491                 return ReplaceInstUsesWith(SI, V);
9492               }
9493       }
9494     }
9495
9496   // See if we are selecting two values based on a comparison of the two values.
9497   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9498     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9499       // Transform (X == Y) ? X : Y  -> Y
9500       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9501         // This is not safe in general for floating point:  
9502         // consider X== -0, Y== +0.
9503         // It becomes safe if either operand is a nonzero constant.
9504         ConstantFP *CFPt, *CFPf;
9505         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9506               !CFPt->getValueAPF().isZero()) ||
9507             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9508              !CFPf->getValueAPF().isZero()))
9509         return ReplaceInstUsesWith(SI, FalseVal);
9510       }
9511       // Transform (X != Y) ? X : Y  -> X
9512       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9513         return ReplaceInstUsesWith(SI, TrueVal);
9514       // NOTE: if we wanted to, this is where to detect MIN/MAX
9515
9516     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9517       // Transform (X == Y) ? Y : X  -> X
9518       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9519         // This is not safe in general for floating point:  
9520         // consider X== -0, Y== +0.
9521         // It becomes safe if either operand is a nonzero constant.
9522         ConstantFP *CFPt, *CFPf;
9523         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9524               !CFPt->getValueAPF().isZero()) ||
9525             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9526              !CFPf->getValueAPF().isZero()))
9527           return ReplaceInstUsesWith(SI, FalseVal);
9528       }
9529       // Transform (X != Y) ? Y : X  -> Y
9530       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9531         return ReplaceInstUsesWith(SI, TrueVal);
9532       // NOTE: if we wanted to, this is where to detect MIN/MAX
9533     }
9534     // NOTE: if we wanted to, this is where to detect ABS
9535   }
9536
9537   // See if we are selecting two values based on a comparison of the two values.
9538   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9539     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9540       return Result;
9541
9542   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9543     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9544       if (TI->hasOneUse() && FI->hasOneUse()) {
9545         Instruction *AddOp = 0, *SubOp = 0;
9546
9547         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9548         if (TI->getOpcode() == FI->getOpcode())
9549           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9550             return IV;
9551
9552         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9553         // even legal for FP.
9554         if ((TI->getOpcode() == Instruction::Sub &&
9555              FI->getOpcode() == Instruction::Add) ||
9556             (TI->getOpcode() == Instruction::FSub &&
9557              FI->getOpcode() == Instruction::FAdd)) {
9558           AddOp = FI; SubOp = TI;
9559         } else if ((FI->getOpcode() == Instruction::Sub &&
9560                     TI->getOpcode() == Instruction::Add) ||
9561                    (FI->getOpcode() == Instruction::FSub &&
9562                     TI->getOpcode() == Instruction::FAdd)) {
9563           AddOp = TI; SubOp = FI;
9564         }
9565
9566         if (AddOp) {
9567           Value *OtherAddOp = 0;
9568           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9569             OtherAddOp = AddOp->getOperand(1);
9570           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9571             OtherAddOp = AddOp->getOperand(0);
9572           }
9573
9574           if (OtherAddOp) {
9575             // So at this point we know we have (Y -> OtherAddOp):
9576             //        select C, (add X, Y), (sub X, Z)
9577             Value *NegVal;  // Compute -Z
9578             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9579               NegVal = ConstantExpr::getNeg(C);
9580             } else {
9581               NegVal = InsertNewInstBefore(
9582                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9583                                               "tmp"), SI);
9584             }
9585
9586             Value *NewTrueOp = OtherAddOp;
9587             Value *NewFalseOp = NegVal;
9588             if (AddOp != TI)
9589               std::swap(NewTrueOp, NewFalseOp);
9590             Instruction *NewSel =
9591               SelectInst::Create(CondVal, NewTrueOp,
9592                                  NewFalseOp, SI.getName() + ".p");
9593
9594             NewSel = InsertNewInstBefore(NewSel, SI);
9595             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9596           }
9597         }
9598       }
9599
9600   // See if we can fold the select into one of our operands.
9601   if (SI.getType()->isInteger()) {
9602     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9603     if (FoldI)
9604       return FoldI;
9605   }
9606
9607   // See if we can fold the select into a phi node if the condition is a select.
9608   if (isa<PHINode>(SI.getCondition())) 
9609     // The true/false values have to be live in the PHI predecessor's blocks.
9610     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9611         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9612       if (Instruction *NV = FoldOpIntoPhi(SI))
9613         return NV;
9614
9615   if (BinaryOperator::isNot(CondVal)) {
9616     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9617     SI.setOperand(1, FalseVal);
9618     SI.setOperand(2, TrueVal);
9619     return &SI;
9620   }
9621
9622   return 0;
9623 }
9624
9625 /// EnforceKnownAlignment - If the specified pointer points to an object that
9626 /// we control, modify the object's alignment to PrefAlign. This isn't
9627 /// often possible though. If alignment is important, a more reliable approach
9628 /// is to simply align all global variables and allocation instructions to
9629 /// their preferred alignment from the beginning.
9630 ///
9631 static unsigned EnforceKnownAlignment(Value *V,
9632                                       unsigned Align, unsigned PrefAlign) {
9633
9634   User *U = dyn_cast<User>(V);
9635   if (!U) return Align;
9636
9637   switch (Operator::getOpcode(U)) {
9638   default: break;
9639   case Instruction::BitCast:
9640     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9641   case Instruction::GetElementPtr: {
9642     // If all indexes are zero, it is just the alignment of the base pointer.
9643     bool AllZeroOperands = true;
9644     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9645       if (!isa<Constant>(*i) ||
9646           !cast<Constant>(*i)->isNullValue()) {
9647         AllZeroOperands = false;
9648         break;
9649       }
9650
9651     if (AllZeroOperands) {
9652       // Treat this like a bitcast.
9653       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9654     }
9655     break;
9656   }
9657   }
9658
9659   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9660     // If there is a large requested alignment and we can, bump up the alignment
9661     // of the global.
9662     if (!GV->isDeclaration()) {
9663       if (GV->getAlignment() >= PrefAlign)
9664         Align = GV->getAlignment();
9665       else {
9666         GV->setAlignment(PrefAlign);
9667         Align = PrefAlign;
9668       }
9669     }
9670   } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9671     // If there is a requested alignment and if this is an alloca, round up.
9672     if (AI->getAlignment() >= PrefAlign)
9673       Align = AI->getAlignment();
9674     else {
9675       AI->setAlignment(PrefAlign);
9676       Align = PrefAlign;
9677     }
9678   }
9679
9680   return Align;
9681 }
9682
9683 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9684 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9685 /// and it is more than the alignment of the ultimate object, see if we can
9686 /// increase the alignment of the ultimate object, making this check succeed.
9687 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9688                                                   unsigned PrefAlign) {
9689   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9690                       sizeof(PrefAlign) * CHAR_BIT;
9691   APInt Mask = APInt::getAllOnesValue(BitWidth);
9692   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9693   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9694   unsigned TrailZ = KnownZero.countTrailingOnes();
9695   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9696
9697   if (PrefAlign > Align)
9698     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9699   
9700     // We don't need to make any adjustment.
9701   return Align;
9702 }
9703
9704 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9705   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9706   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9707   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9708   unsigned CopyAlign = MI->getAlignment();
9709
9710   if (CopyAlign < MinAlign) {
9711     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9712                                              MinAlign, false));
9713     return MI;
9714   }
9715   
9716   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9717   // load/store.
9718   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9719   if (MemOpLength == 0) return 0;
9720   
9721   // Source and destination pointer types are always "i8*" for intrinsic.  See
9722   // if the size is something we can handle with a single primitive load/store.
9723   // A single load+store correctly handles overlapping memory in the memmove
9724   // case.
9725   unsigned Size = MemOpLength->getZExtValue();
9726   if (Size == 0) return MI;  // Delete this mem transfer.
9727   
9728   if (Size > 8 || (Size&(Size-1)))
9729     return 0;  // If not 1/2/4/8 bytes, exit.
9730   
9731   // Use an integer load+store unless we can find something better.
9732   Type *NewPtrTy =
9733                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9734   
9735   // Memcpy forces the use of i8* for the source and destination.  That means
9736   // that if you're using memcpy to move one double around, you'll get a cast
9737   // from double* to i8*.  We'd much rather use a double load+store rather than
9738   // an i64 load+store, here because this improves the odds that the source or
9739   // dest address will be promotable.  See if we can find a better type than the
9740   // integer datatype.
9741   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9742     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9743     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9744       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9745       // down through these levels if so.
9746       while (!SrcETy->isSingleValueType()) {
9747         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9748           if (STy->getNumElements() == 1)
9749             SrcETy = STy->getElementType(0);
9750           else
9751             break;
9752         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9753           if (ATy->getNumElements() == 1)
9754             SrcETy = ATy->getElementType();
9755           else
9756             break;
9757         } else
9758           break;
9759       }
9760       
9761       if (SrcETy->isSingleValueType())
9762         NewPtrTy = PointerType::getUnqual(SrcETy);
9763     }
9764   }
9765   
9766   
9767   // If the memcpy/memmove provides better alignment info than we can
9768   // infer, use it.
9769   SrcAlign = std::max(SrcAlign, CopyAlign);
9770   DstAlign = std::max(DstAlign, CopyAlign);
9771   
9772   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9773   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9774   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9775   InsertNewInstBefore(L, *MI);
9776   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9777
9778   // Set the size of the copy to 0, it will be deleted on the next iteration.
9779   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9780   return MI;
9781 }
9782
9783 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9784   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9785   if (MI->getAlignment() < Alignment) {
9786     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9787                                              Alignment, false));
9788     return MI;
9789   }
9790   
9791   // Extract the length and alignment and fill if they are constant.
9792   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9793   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9794   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9795     return 0;
9796   uint64_t Len = LenC->getZExtValue();
9797   Alignment = MI->getAlignment();
9798   
9799   // If the length is zero, this is a no-op
9800   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9801   
9802   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9803   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9804     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9805     
9806     Value *Dest = MI->getDest();
9807     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9808
9809     // Alignment 0 is identity for alignment 1 for memset, but not store.
9810     if (Alignment == 0) Alignment = 1;
9811     
9812     // Extract the fill value and store.
9813     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9814     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9815                                       Dest, false, Alignment), *MI);
9816     
9817     // Set the size of the copy to 0, it will be deleted on the next iteration.
9818     MI->setLength(Constant::getNullValue(LenC->getType()));
9819     return MI;
9820   }
9821
9822   return 0;
9823 }
9824
9825
9826 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9827 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9828 /// the heavy lifting.
9829 ///
9830 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9831   if (isFreeCall(&CI))
9832     return visitFree(CI);
9833
9834   // If the caller function is nounwind, mark the call as nounwind, even if the
9835   // callee isn't.
9836   if (CI.getParent()->getParent()->doesNotThrow() &&
9837       !CI.doesNotThrow()) {
9838     CI.setDoesNotThrow();
9839     return &CI;
9840   }
9841   
9842   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9843   if (!II) return visitCallSite(&CI);
9844   
9845   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9846   // visitCallSite.
9847   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9848     bool Changed = false;
9849
9850     // memmove/cpy/set of zero bytes is a noop.
9851     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9852       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9853
9854       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9855         if (CI->getZExtValue() == 1) {
9856           // Replace the instruction with just byte operations.  We would
9857           // transform other cases to loads/stores, but we don't know if
9858           // alignment is sufficient.
9859         }
9860     }
9861
9862     // If we have a memmove and the source operation is a constant global,
9863     // then the source and dest pointers can't alias, so we can change this
9864     // into a call to memcpy.
9865     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9866       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9867         if (GVSrc->isConstant()) {
9868           Module *M = CI.getParent()->getParent()->getParent();
9869           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9870           const Type *Tys[1];
9871           Tys[0] = CI.getOperand(3)->getType();
9872           CI.setOperand(0, 
9873                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9874           Changed = true;
9875         }
9876
9877       // memmove(x,x,size) -> noop.
9878       if (MMI->getSource() == MMI->getDest())
9879         return EraseInstFromFunction(CI);
9880     }
9881
9882     // If we can determine a pointer alignment that is bigger than currently
9883     // set, update the alignment.
9884     if (isa<MemTransferInst>(MI)) {
9885       if (Instruction *I = SimplifyMemTransfer(MI))
9886         return I;
9887     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9888       if (Instruction *I = SimplifyMemSet(MSI))
9889         return I;
9890     }
9891           
9892     if (Changed) return II;
9893   }
9894   
9895   switch (II->getIntrinsicID()) {
9896   default: break;
9897   case Intrinsic::bswap:
9898     // bswap(bswap(x)) -> x
9899     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9900       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9901         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9902     break;
9903   case Intrinsic::ppc_altivec_lvx:
9904   case Intrinsic::ppc_altivec_lvxl:
9905   case Intrinsic::x86_sse_loadu_ps:
9906   case Intrinsic::x86_sse2_loadu_pd:
9907   case Intrinsic::x86_sse2_loadu_dq:
9908     // Turn PPC lvx     -> load if the pointer is known aligned.
9909     // Turn X86 loadups -> load if the pointer is known aligned.
9910     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9911       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9912                                          PointerType::getUnqual(II->getType()));
9913       return new LoadInst(Ptr);
9914     }
9915     break;
9916   case Intrinsic::ppc_altivec_stvx:
9917   case Intrinsic::ppc_altivec_stvxl:
9918     // Turn stvx -> store if the pointer is known aligned.
9919     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9920       const Type *OpPtrTy = 
9921         PointerType::getUnqual(II->getOperand(1)->getType());
9922       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9923       return new StoreInst(II->getOperand(1), Ptr);
9924     }
9925     break;
9926   case Intrinsic::x86_sse_storeu_ps:
9927   case Intrinsic::x86_sse2_storeu_pd:
9928   case Intrinsic::x86_sse2_storeu_dq:
9929     // Turn X86 storeu -> store if the pointer is known aligned.
9930     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9931       const Type *OpPtrTy = 
9932         PointerType::getUnqual(II->getOperand(2)->getType());
9933       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9934       return new StoreInst(II->getOperand(2), Ptr);
9935     }
9936     break;
9937     
9938   case Intrinsic::x86_sse_cvttss2si: {
9939     // These intrinsics only demands the 0th element of its input vector.  If
9940     // we can simplify the input based on that, do so now.
9941     unsigned VWidth =
9942       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9943     APInt DemandedElts(VWidth, 1);
9944     APInt UndefElts(VWidth, 0);
9945     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9946                                               UndefElts)) {
9947       II->setOperand(1, V);
9948       return II;
9949     }
9950     break;
9951   }
9952     
9953   case Intrinsic::ppc_altivec_vperm:
9954     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9955     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9956       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9957       
9958       // Check that all of the elements are integer constants or undefs.
9959       bool AllEltsOk = true;
9960       for (unsigned i = 0; i != 16; ++i) {
9961         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9962             !isa<UndefValue>(Mask->getOperand(i))) {
9963           AllEltsOk = false;
9964           break;
9965         }
9966       }
9967       
9968       if (AllEltsOk) {
9969         // Cast the input vectors to byte vectors.
9970         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9971         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9972         Value *Result = UndefValue::get(Op0->getType());
9973         
9974         // Only extract each element once.
9975         Value *ExtractedElts[32];
9976         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9977         
9978         for (unsigned i = 0; i != 16; ++i) {
9979           if (isa<UndefValue>(Mask->getOperand(i)))
9980             continue;
9981           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9982           Idx &= 31;  // Match the hardware behavior.
9983           
9984           if (ExtractedElts[Idx] == 0) {
9985             ExtractedElts[Idx] = 
9986               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
9987                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9988                                             "tmp");
9989           }
9990         
9991           // Insert this value into the result vector.
9992           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9993                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9994                                                 "tmp");
9995         }
9996         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9997       }
9998     }
9999     break;
10000
10001   case Intrinsic::stackrestore: {
10002     // If the save is right next to the restore, remove the restore.  This can
10003     // happen when variable allocas are DCE'd.
10004     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10005       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10006         BasicBlock::iterator BI = SS;
10007         if (&*++BI == II)
10008           return EraseInstFromFunction(CI);
10009       }
10010     }
10011     
10012     // Scan down this block to see if there is another stack restore in the
10013     // same block without an intervening call/alloca.
10014     BasicBlock::iterator BI = II;
10015     TerminatorInst *TI = II->getParent()->getTerminator();
10016     bool CannotRemove = false;
10017     for (++BI; &*BI != TI; ++BI) {
10018       if (isa<AllocaInst>(BI) || isMalloc(BI)) {
10019         CannotRemove = true;
10020         break;
10021       }
10022       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10023         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10024           // If there is a stackrestore below this one, remove this one.
10025           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10026             return EraseInstFromFunction(CI);
10027           // Otherwise, ignore the intrinsic.
10028         } else {
10029           // If we found a non-intrinsic call, we can't remove the stack
10030           // restore.
10031           CannotRemove = true;
10032           break;
10033         }
10034       }
10035     }
10036     
10037     // If the stack restore is in a return/unwind block and if there are no
10038     // allocas or calls between the restore and the return, nuke the restore.
10039     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10040       return EraseInstFromFunction(CI);
10041     break;
10042   }
10043   }
10044
10045   return visitCallSite(II);
10046 }
10047
10048 // InvokeInst simplification
10049 //
10050 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10051   return visitCallSite(&II);
10052 }
10053
10054 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10055 /// passed through the varargs area, we can eliminate the use of the cast.
10056 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10057                                          const CastInst * const CI,
10058                                          const TargetData * const TD,
10059                                          const int ix) {
10060   if (!CI->isLosslessCast())
10061     return false;
10062
10063   // The size of ByVal arguments is derived from the type, so we
10064   // can't change to a type with a different size.  If the size were
10065   // passed explicitly we could avoid this check.
10066   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10067     return true;
10068
10069   const Type* SrcTy = 
10070             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10071   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10072   if (!SrcTy->isSized() || !DstTy->isSized())
10073     return false;
10074   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10075     return false;
10076   return true;
10077 }
10078
10079 // visitCallSite - Improvements for call and invoke instructions.
10080 //
10081 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10082   bool Changed = false;
10083
10084   // If the callee is a constexpr cast of a function, attempt to move the cast
10085   // to the arguments of the call/invoke.
10086   if (transformConstExprCastCall(CS)) return 0;
10087
10088   Value *Callee = CS.getCalledValue();
10089
10090   if (Function *CalleeF = dyn_cast<Function>(Callee))
10091     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10092       Instruction *OldCall = CS.getInstruction();
10093       // If the call and callee calling conventions don't match, this call must
10094       // be unreachable, as the call is undefined.
10095       new StoreInst(ConstantInt::getTrue(*Context),
10096                 UndefValue::get(Type::getInt1PtrTy(*Context)), 
10097                                   OldCall);
10098       // If OldCall dues not return void then replaceAllUsesWith undef.
10099       // This allows ValueHandlers and custom metadata to adjust itself.
10100       if (!OldCall->getType()->isVoidTy())
10101         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10102       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10103         return EraseInstFromFunction(*OldCall);
10104       return 0;
10105     }
10106
10107   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10108     // This instruction is not reachable, just remove it.  We insert a store to
10109     // undef so that we know that this code is not reachable, despite the fact
10110     // that we can't modify the CFG here.
10111     new StoreInst(ConstantInt::getTrue(*Context),
10112                UndefValue::get(Type::getInt1PtrTy(*Context)),
10113                   CS.getInstruction());
10114
10115     // If CS dues not return void then replaceAllUsesWith undef.
10116     // This allows ValueHandlers and custom metadata to adjust itself.
10117     if (!CS.getInstruction()->getType()->isVoidTy())
10118       CS.getInstruction()->
10119         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10120
10121     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10122       // Don't break the CFG, insert a dummy cond branch.
10123       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10124                          ConstantInt::getTrue(*Context), II);
10125     }
10126     return EraseInstFromFunction(*CS.getInstruction());
10127   }
10128
10129   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10130     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10131       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10132         return transformCallThroughTrampoline(CS);
10133
10134   const PointerType *PTy = cast<PointerType>(Callee->getType());
10135   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10136   if (FTy->isVarArg()) {
10137     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10138     // See if we can optimize any arguments passed through the varargs area of
10139     // the call.
10140     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10141            E = CS.arg_end(); I != E; ++I, ++ix) {
10142       CastInst *CI = dyn_cast<CastInst>(*I);
10143       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10144         *I = CI->getOperand(0);
10145         Changed = true;
10146       }
10147     }
10148   }
10149
10150   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10151     // Inline asm calls cannot throw - mark them 'nounwind'.
10152     CS.setDoesNotThrow();
10153     Changed = true;
10154   }
10155
10156   return Changed ? CS.getInstruction() : 0;
10157 }
10158
10159 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10160 // attempt to move the cast to the arguments of the call/invoke.
10161 //
10162 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10163   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10164   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10165   if (CE->getOpcode() != Instruction::BitCast || 
10166       !isa<Function>(CE->getOperand(0)))
10167     return false;
10168   Function *Callee = cast<Function>(CE->getOperand(0));
10169   Instruction *Caller = CS.getInstruction();
10170   const AttrListPtr &CallerPAL = CS.getAttributes();
10171
10172   // Okay, this is a cast from a function to a different type.  Unless doing so
10173   // would cause a type conversion of one of our arguments, change this call to
10174   // be a direct call with arguments casted to the appropriate types.
10175   //
10176   const FunctionType *FT = Callee->getFunctionType();
10177   const Type *OldRetTy = Caller->getType();
10178   const Type *NewRetTy = FT->getReturnType();
10179
10180   if (isa<StructType>(NewRetTy))
10181     return false; // TODO: Handle multiple return values.
10182
10183   // Check to see if we are changing the return type...
10184   if (OldRetTy != NewRetTy) {
10185     if (Callee->isDeclaration() &&
10186         // Conversion is ok if changing from one pointer type to another or from
10187         // a pointer to an integer of the same size.
10188         !((isa<PointerType>(OldRetTy) || !TD ||
10189            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10190           (isa<PointerType>(NewRetTy) || !TD ||
10191            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10192       return false;   // Cannot transform this return value.
10193
10194     if (!Caller->use_empty() &&
10195         // void -> non-void is handled specially
10196         !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
10197       return false;   // Cannot transform this return value.
10198
10199     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10200       Attributes RAttrs = CallerPAL.getRetAttributes();
10201       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10202         return false;   // Attribute not compatible with transformed value.
10203     }
10204
10205     // If the callsite is an invoke instruction, and the return value is used by
10206     // a PHI node in a successor, we cannot change the return type of the call
10207     // because there is no place to put the cast instruction (without breaking
10208     // the critical edge).  Bail out in this case.
10209     if (!Caller->use_empty())
10210       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10211         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10212              UI != E; ++UI)
10213           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10214             if (PN->getParent() == II->getNormalDest() ||
10215                 PN->getParent() == II->getUnwindDest())
10216               return false;
10217   }
10218
10219   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10220   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10221
10222   CallSite::arg_iterator AI = CS.arg_begin();
10223   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10224     const Type *ParamTy = FT->getParamType(i);
10225     const Type *ActTy = (*AI)->getType();
10226
10227     if (!CastInst::isCastable(ActTy, ParamTy))
10228       return false;   // Cannot transform this parameter value.
10229
10230     if (CallerPAL.getParamAttributes(i + 1) 
10231         & Attribute::typeIncompatible(ParamTy))
10232       return false;   // Attribute not compatible with transformed value.
10233
10234     // Converting from one pointer type to another or between a pointer and an
10235     // integer of the same size is safe even if we do not have a body.
10236     bool isConvertible = ActTy == ParamTy ||
10237       (TD && ((isa<PointerType>(ParamTy) ||
10238       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10239               (isa<PointerType>(ActTy) ||
10240               ActTy == TD->getIntPtrType(Caller->getContext()))));
10241     if (Callee->isDeclaration() && !isConvertible) return false;
10242   }
10243
10244   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10245       Callee->isDeclaration())
10246     return false;   // Do not delete arguments unless we have a function body.
10247
10248   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10249       !CallerPAL.isEmpty())
10250     // In this case we have more arguments than the new function type, but we
10251     // won't be dropping them.  Check that these extra arguments have attributes
10252     // that are compatible with being a vararg call argument.
10253     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10254       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10255         break;
10256       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10257       if (PAttrs & Attribute::VarArgsIncompatible)
10258         return false;
10259     }
10260
10261   // Okay, we decided that this is a safe thing to do: go ahead and start
10262   // inserting cast instructions as necessary...
10263   std::vector<Value*> Args;
10264   Args.reserve(NumActualArgs);
10265   SmallVector<AttributeWithIndex, 8> attrVec;
10266   attrVec.reserve(NumCommonArgs);
10267
10268   // Get any return attributes.
10269   Attributes RAttrs = CallerPAL.getRetAttributes();
10270
10271   // If the return value is not being used, the type may not be compatible
10272   // with the existing attributes.  Wipe out any problematic attributes.
10273   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10274
10275   // Add the new return attributes.
10276   if (RAttrs)
10277     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10278
10279   AI = CS.arg_begin();
10280   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10281     const Type *ParamTy = FT->getParamType(i);
10282     if ((*AI)->getType() == ParamTy) {
10283       Args.push_back(*AI);
10284     } else {
10285       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10286           false, ParamTy, false);
10287       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10288     }
10289
10290     // Add any parameter attributes.
10291     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10292       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10293   }
10294
10295   // If the function takes more arguments than the call was taking, add them
10296   // now.
10297   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10298     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10299
10300   // If we are removing arguments to the function, emit an obnoxious warning.
10301   if (FT->getNumParams() < NumActualArgs) {
10302     if (!FT->isVarArg()) {
10303       errs() << "WARNING: While resolving call to function '"
10304              << Callee->getName() << "' arguments were dropped!\n";
10305     } else {
10306       // Add all of the arguments in their promoted form to the arg list.
10307       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10308         const Type *PTy = getPromotedType((*AI)->getType());
10309         if (PTy != (*AI)->getType()) {
10310           // Must promote to pass through va_arg area!
10311           Instruction::CastOps opcode =
10312             CastInst::getCastOpcode(*AI, false, PTy, false);
10313           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10314         } else {
10315           Args.push_back(*AI);
10316         }
10317
10318         // Add any parameter attributes.
10319         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10320           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10321       }
10322     }
10323   }
10324
10325   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10326     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10327
10328   if (NewRetTy->isVoidTy())
10329     Caller->setName("");   // Void type should not have a name.
10330
10331   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10332                                                      attrVec.end());
10333
10334   Instruction *NC;
10335   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10336     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10337                             Args.begin(), Args.end(),
10338                             Caller->getName(), Caller);
10339     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10340     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10341   } else {
10342     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10343                           Caller->getName(), Caller);
10344     CallInst *CI = cast<CallInst>(Caller);
10345     if (CI->isTailCall())
10346       cast<CallInst>(NC)->setTailCall();
10347     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10348     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10349   }
10350
10351   // Insert a cast of the return type as necessary.
10352   Value *NV = NC;
10353   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10354     if (!NV->getType()->isVoidTy()) {
10355       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10356                                                             OldRetTy, false);
10357       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10358
10359       // If this is an invoke instruction, we should insert it after the first
10360       // non-phi, instruction in the normal successor block.
10361       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10362         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10363         InsertNewInstBefore(NC, *I);
10364       } else {
10365         // Otherwise, it's a call, just insert cast right after the call instr
10366         InsertNewInstBefore(NC, *Caller);
10367       }
10368       Worklist.AddUsersToWorkList(*Caller);
10369     } else {
10370       NV = UndefValue::get(Caller->getType());
10371     }
10372   }
10373
10374
10375   if (!Caller->use_empty())
10376     Caller->replaceAllUsesWith(NV);
10377   
10378   EraseInstFromFunction(*Caller);
10379   return true;
10380 }
10381
10382 // transformCallThroughTrampoline - Turn a call to a function created by the
10383 // init_trampoline intrinsic into a direct call to the underlying function.
10384 //
10385 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10386   Value *Callee = CS.getCalledValue();
10387   const PointerType *PTy = cast<PointerType>(Callee->getType());
10388   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10389   const AttrListPtr &Attrs = CS.getAttributes();
10390
10391   // If the call already has the 'nest' attribute somewhere then give up -
10392   // otherwise 'nest' would occur twice after splicing in the chain.
10393   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10394     return 0;
10395
10396   IntrinsicInst *Tramp =
10397     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10398
10399   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10400   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10401   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10402
10403   const AttrListPtr &NestAttrs = NestF->getAttributes();
10404   if (!NestAttrs.isEmpty()) {
10405     unsigned NestIdx = 1;
10406     const Type *NestTy = 0;
10407     Attributes NestAttr = Attribute::None;
10408
10409     // Look for a parameter marked with the 'nest' attribute.
10410     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10411          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10412       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10413         // Record the parameter type and any other attributes.
10414         NestTy = *I;
10415         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10416         break;
10417       }
10418
10419     if (NestTy) {
10420       Instruction *Caller = CS.getInstruction();
10421       std::vector<Value*> NewArgs;
10422       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10423
10424       SmallVector<AttributeWithIndex, 8> NewAttrs;
10425       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10426
10427       // Insert the nest argument into the call argument list, which may
10428       // mean appending it.  Likewise for attributes.
10429
10430       // Add any result attributes.
10431       if (Attributes Attr = Attrs.getRetAttributes())
10432         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10433
10434       {
10435         unsigned Idx = 1;
10436         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10437         do {
10438           if (Idx == NestIdx) {
10439             // Add the chain argument and attributes.
10440             Value *NestVal = Tramp->getOperand(3);
10441             if (NestVal->getType() != NestTy)
10442               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10443             NewArgs.push_back(NestVal);
10444             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10445           }
10446
10447           if (I == E)
10448             break;
10449
10450           // Add the original argument and attributes.
10451           NewArgs.push_back(*I);
10452           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10453             NewAttrs.push_back
10454               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10455
10456           ++Idx, ++I;
10457         } while (1);
10458       }
10459
10460       // Add any function attributes.
10461       if (Attributes Attr = Attrs.getFnAttributes())
10462         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10463
10464       // The trampoline may have been bitcast to a bogus type (FTy).
10465       // Handle this by synthesizing a new function type, equal to FTy
10466       // with the chain parameter inserted.
10467
10468       std::vector<const Type*> NewTypes;
10469       NewTypes.reserve(FTy->getNumParams()+1);
10470
10471       // Insert the chain's type into the list of parameter types, which may
10472       // mean appending it.
10473       {
10474         unsigned Idx = 1;
10475         FunctionType::param_iterator I = FTy->param_begin(),
10476           E = FTy->param_end();
10477
10478         do {
10479           if (Idx == NestIdx)
10480             // Add the chain's type.
10481             NewTypes.push_back(NestTy);
10482
10483           if (I == E)
10484             break;
10485
10486           // Add the original type.
10487           NewTypes.push_back(*I);
10488
10489           ++Idx, ++I;
10490         } while (1);
10491       }
10492
10493       // Replace the trampoline call with a direct call.  Let the generic
10494       // code sort out any function type mismatches.
10495       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10496                                                 FTy->isVarArg());
10497       Constant *NewCallee =
10498         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10499         NestF : ConstantExpr::getBitCast(NestF, 
10500                                          PointerType::getUnqual(NewFTy));
10501       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10502                                                    NewAttrs.end());
10503
10504       Instruction *NewCaller;
10505       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10506         NewCaller = InvokeInst::Create(NewCallee,
10507                                        II->getNormalDest(), II->getUnwindDest(),
10508                                        NewArgs.begin(), NewArgs.end(),
10509                                        Caller->getName(), Caller);
10510         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10511         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10512       } else {
10513         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10514                                      Caller->getName(), Caller);
10515         if (cast<CallInst>(Caller)->isTailCall())
10516           cast<CallInst>(NewCaller)->setTailCall();
10517         cast<CallInst>(NewCaller)->
10518           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10519         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10520       }
10521       if (!Caller->getType()->isVoidTy())
10522         Caller->replaceAllUsesWith(NewCaller);
10523       Caller->eraseFromParent();
10524       Worklist.Remove(Caller);
10525       return 0;
10526     }
10527   }
10528
10529   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10530   // parameter, there is no need to adjust the argument list.  Let the generic
10531   // code sort out any function type mismatches.
10532   Constant *NewCallee =
10533     NestF->getType() == PTy ? NestF : 
10534                               ConstantExpr::getBitCast(NestF, PTy);
10535   CS.setCalledFunction(NewCallee);
10536   return CS.getInstruction();
10537 }
10538
10539 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10540 /// and if a/b/c and the add's all have a single use, turn this into a phi
10541 /// and a single binop.
10542 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10543   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10544   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10545   unsigned Opc = FirstInst->getOpcode();
10546   Value *LHSVal = FirstInst->getOperand(0);
10547   Value *RHSVal = FirstInst->getOperand(1);
10548     
10549   const Type *LHSType = LHSVal->getType();
10550   const Type *RHSType = RHSVal->getType();
10551   
10552   // Scan to see if all operands are the same opcode, and all have one use.
10553   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10554     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10555     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10556         // Verify type of the LHS matches so we don't fold cmp's of different
10557         // types or GEP's with different index types.
10558         I->getOperand(0)->getType() != LHSType ||
10559         I->getOperand(1)->getType() != RHSType)
10560       return 0;
10561
10562     // If they are CmpInst instructions, check their predicates
10563     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10564       if (cast<CmpInst>(I)->getPredicate() !=
10565           cast<CmpInst>(FirstInst)->getPredicate())
10566         return 0;
10567     
10568     // Keep track of which operand needs a phi node.
10569     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10570     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10571   }
10572
10573   // If both LHS and RHS would need a PHI, don't do this transformation,
10574   // because it would increase the number of PHIs entering the block,
10575   // which leads to higher register pressure. This is especially
10576   // bad when the PHIs are in the header of a loop.
10577   if (!LHSVal && !RHSVal)
10578     return 0;
10579   
10580   // Otherwise, this is safe to transform!
10581   
10582   Value *InLHS = FirstInst->getOperand(0);
10583   Value *InRHS = FirstInst->getOperand(1);
10584   PHINode *NewLHS = 0, *NewRHS = 0;
10585   if (LHSVal == 0) {
10586     NewLHS = PHINode::Create(LHSType,
10587                              FirstInst->getOperand(0)->getName() + ".pn");
10588     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10589     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10590     InsertNewInstBefore(NewLHS, PN);
10591     LHSVal = NewLHS;
10592   }
10593   
10594   if (RHSVal == 0) {
10595     NewRHS = PHINode::Create(RHSType,
10596                              FirstInst->getOperand(1)->getName() + ".pn");
10597     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10598     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10599     InsertNewInstBefore(NewRHS, PN);
10600     RHSVal = NewRHS;
10601   }
10602   
10603   // Add all operands to the new PHIs.
10604   if (NewLHS || NewRHS) {
10605     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10606       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10607       if (NewLHS) {
10608         Value *NewInLHS = InInst->getOperand(0);
10609         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10610       }
10611       if (NewRHS) {
10612         Value *NewInRHS = InInst->getOperand(1);
10613         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10614       }
10615     }
10616   }
10617     
10618   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10619     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10620   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10621   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10622                          LHSVal, RHSVal);
10623 }
10624
10625 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10626   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10627   
10628   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10629                                         FirstInst->op_end());
10630   // This is true if all GEP bases are allocas and if all indices into them are
10631   // constants.
10632   bool AllBasePointersAreAllocas = true;
10633
10634   // We don't want to replace this phi if the replacement would require
10635   // more than one phi, which leads to higher register pressure. This is
10636   // especially bad when the PHIs are in the header of a loop.
10637   bool NeededPhi = false;
10638   
10639   // Scan to see if all operands are the same opcode, and all have one use.
10640   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10641     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10642     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10643       GEP->getNumOperands() != FirstInst->getNumOperands())
10644       return 0;
10645
10646     // Keep track of whether or not all GEPs are of alloca pointers.
10647     if (AllBasePointersAreAllocas &&
10648         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10649          !GEP->hasAllConstantIndices()))
10650       AllBasePointersAreAllocas = false;
10651     
10652     // Compare the operand lists.
10653     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10654       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10655         continue;
10656       
10657       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10658       // if one of the PHIs has a constant for the index.  The index may be
10659       // substantially cheaper to compute for the constants, so making it a
10660       // variable index could pessimize the path.  This also handles the case
10661       // for struct indices, which must always be constant.
10662       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10663           isa<ConstantInt>(GEP->getOperand(op)))
10664         return 0;
10665       
10666       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10667         return 0;
10668
10669       // If we already needed a PHI for an earlier operand, and another operand
10670       // also requires a PHI, we'd be introducing more PHIs than we're
10671       // eliminating, which increases register pressure on entry to the PHI's
10672       // block.
10673       if (NeededPhi)
10674         return 0;
10675
10676       FixedOperands[op] = 0;  // Needs a PHI.
10677       NeededPhi = true;
10678     }
10679   }
10680   
10681   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10682   // bother doing this transformation.  At best, this will just save a bit of
10683   // offset calculation, but all the predecessors will have to materialize the
10684   // stack address into a register anyway.  We'd actually rather *clone* the
10685   // load up into the predecessors so that we have a load of a gep of an alloca,
10686   // which can usually all be folded into the load.
10687   if (AllBasePointersAreAllocas)
10688     return 0;
10689   
10690   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10691   // that is variable.
10692   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10693   
10694   bool HasAnyPHIs = false;
10695   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10696     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10697     Value *FirstOp = FirstInst->getOperand(i);
10698     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10699                                      FirstOp->getName()+".pn");
10700     InsertNewInstBefore(NewPN, PN);
10701     
10702     NewPN->reserveOperandSpace(e);
10703     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10704     OperandPhis[i] = NewPN;
10705     FixedOperands[i] = NewPN;
10706     HasAnyPHIs = true;
10707   }
10708
10709   
10710   // Add all operands to the new PHIs.
10711   if (HasAnyPHIs) {
10712     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10713       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10714       BasicBlock *InBB = PN.getIncomingBlock(i);
10715       
10716       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10717         if (PHINode *OpPhi = OperandPhis[op])
10718           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10719     }
10720   }
10721   
10722   Value *Base = FixedOperands[0];
10723   return cast<GEPOperator>(FirstInst)->isInBounds() ?
10724     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10725                                       FixedOperands.end()) :
10726     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10727                               FixedOperands.end());
10728 }
10729
10730
10731 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10732 /// sink the load out of the block that defines it.  This means that it must be
10733 /// obvious the value of the load is not changed from the point of the load to
10734 /// the end of the block it is in.
10735 ///
10736 /// Finally, it is safe, but not profitable, to sink a load targetting a
10737 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10738 /// to a register.
10739 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10740   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10741   
10742   for (++BBI; BBI != E; ++BBI)
10743     if (BBI->mayWriteToMemory())
10744       return false;
10745   
10746   // Check for non-address taken alloca.  If not address-taken already, it isn't
10747   // profitable to do this xform.
10748   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10749     bool isAddressTaken = false;
10750     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10751          UI != E; ++UI) {
10752       if (isa<LoadInst>(UI)) continue;
10753       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10754         // If storing TO the alloca, then the address isn't taken.
10755         if (SI->getOperand(1) == AI) continue;
10756       }
10757       isAddressTaken = true;
10758       break;
10759     }
10760     
10761     if (!isAddressTaken && AI->isStaticAlloca())
10762       return false;
10763   }
10764   
10765   // If this load is a load from a GEP with a constant offset from an alloca,
10766   // then we don't want to sink it.  In its present form, it will be
10767   // load [constant stack offset].  Sinking it will cause us to have to
10768   // materialize the stack addresses in each predecessor in a register only to
10769   // do a shared load from register in the successor.
10770   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10771     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10772       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10773         return false;
10774   
10775   return true;
10776 }
10777
10778 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10779   LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10780   
10781   // When processing loads, we need to propagate two bits of information to the
10782   // sunk load: whether it is volatile, and what its alignment is.  We currently
10783   // don't sink loads when some have their alignment specified and some don't.
10784   // visitLoadInst will propagate an alignment onto the load when TD is around,
10785   // and if TD isn't around, we can't handle the mixed case.
10786   bool isVolatile = FirstLI->isVolatile();
10787   unsigned LoadAlignment = FirstLI->getAlignment();
10788   
10789   // We can't sink the load if the loaded value could be modified between the
10790   // load and the PHI.
10791   if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
10792       !isSafeAndProfitableToSinkLoad(FirstLI))
10793     return 0;
10794   
10795   // If the PHI is of volatile loads and the load block has multiple
10796   // successors, sinking it would remove a load of the volatile value from
10797   // the path through the other successor.
10798   if (isVolatile && 
10799       FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
10800     return 0;
10801   
10802   // Check to see if all arguments are the same operation.
10803   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10804     LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
10805     if (!LI || !LI->hasOneUse())
10806       return 0;
10807     
10808     // We can't sink the load if the loaded value could be modified between 
10809     // the load and the PHI.
10810     if (LI->isVolatile() != isVolatile ||
10811         LI->getParent() != PN.getIncomingBlock(i) ||
10812         !isSafeAndProfitableToSinkLoad(LI))
10813       return 0;
10814       
10815     // If some of the loads have an alignment specified but not all of them,
10816     // we can't do the transformation.
10817     if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
10818       return 0;
10819     
10820     LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
10821     
10822     // If the PHI is of volatile loads and the load block has multiple
10823     // successors, sinking it would remove a load of the volatile value from
10824     // the path through the other successor.
10825     if (isVolatile &&
10826         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10827       return 0;
10828   }
10829   
10830   // Okay, they are all the same operation.  Create a new PHI node of the
10831   // correct type, and PHI together all of the LHS's of the instructions.
10832   PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
10833                                    PN.getName()+".in");
10834   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10835   
10836   Value *InVal = FirstLI->getOperand(0);
10837   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10838   
10839   // Add all operands to the new PHI.
10840   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10841     Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
10842     if (NewInVal != InVal)
10843       InVal = 0;
10844     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10845   }
10846   
10847   Value *PhiVal;
10848   if (InVal) {
10849     // The new PHI unions all of the same values together.  This is really
10850     // common, so we handle it intelligently here for compile-time speed.
10851     PhiVal = InVal;
10852     delete NewPN;
10853   } else {
10854     InsertNewInstBefore(NewPN, PN);
10855     PhiVal = NewPN;
10856   }
10857   
10858   // If this was a volatile load that we are merging, make sure to loop through
10859   // and mark all the input loads as non-volatile.  If we don't do this, we will
10860   // insert a new volatile load and the old ones will not be deletable.
10861   if (isVolatile)
10862     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10863       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10864   
10865   return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
10866 }
10867
10868
10869 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10870 // operator and they all are only used by the PHI, PHI together their
10871 // inputs, and do the operation once, to the result of the PHI.
10872 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10873   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10874
10875   if (isa<GetElementPtrInst>(FirstInst))
10876     return FoldPHIArgGEPIntoPHI(PN);
10877   if (isa<LoadInst>(FirstInst))
10878     return FoldPHIArgLoadIntoPHI(PN);
10879   
10880   // Scan the instruction, looking for input operations that can be folded away.
10881   // If all input operands to the phi are the same instruction (e.g. a cast from
10882   // the same type or "+42") we can pull the operation through the PHI, reducing
10883   // code size and simplifying code.
10884   Constant *ConstantOp = 0;
10885   const Type *CastSrcTy = 0;
10886   
10887   if (isa<CastInst>(FirstInst)) {
10888     CastSrcTy = FirstInst->getOperand(0)->getType();
10889   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10890     // Can fold binop, compare or shift here if the RHS is a constant, 
10891     // otherwise call FoldPHIArgBinOpIntoPHI.
10892     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10893     if (ConstantOp == 0)
10894       return FoldPHIArgBinOpIntoPHI(PN);
10895   } else {
10896     return 0;  // Cannot fold this operation.
10897   }
10898
10899   // Check to see if all arguments are the same operation.
10900   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10901     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10902     if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10903       return 0;
10904     if (CastSrcTy) {
10905       if (I->getOperand(0)->getType() != CastSrcTy)
10906         return 0;  // Cast operation must match.
10907     } else if (I->getOperand(1) != ConstantOp) {
10908       return 0;
10909     }
10910   }
10911
10912   // Okay, they are all the same operation.  Create a new PHI node of the
10913   // correct type, and PHI together all of the LHS's of the instructions.
10914   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10915                                    PN.getName()+".in");
10916   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10917
10918   Value *InVal = FirstInst->getOperand(0);
10919   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10920
10921   // Add all operands to the new PHI.
10922   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10923     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10924     if (NewInVal != InVal)
10925       InVal = 0;
10926     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10927   }
10928
10929   Value *PhiVal;
10930   if (InVal) {
10931     // The new PHI unions all of the same values together.  This is really
10932     // common, so we handle it intelligently here for compile-time speed.
10933     PhiVal = InVal;
10934     delete NewPN;
10935   } else {
10936     InsertNewInstBefore(NewPN, PN);
10937     PhiVal = NewPN;
10938   }
10939
10940   // Insert and return the new operation.
10941   if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
10942     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10943   
10944   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10945     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10946   
10947   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10948   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10949                          PhiVal, ConstantOp);
10950 }
10951
10952 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10953 /// that is dead.
10954 static bool DeadPHICycle(PHINode *PN,
10955                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10956   if (PN->use_empty()) return true;
10957   if (!PN->hasOneUse()) return false;
10958
10959   // Remember this node, and if we find the cycle, return.
10960   if (!PotentiallyDeadPHIs.insert(PN))
10961     return true;
10962   
10963   // Don't scan crazily complex things.
10964   if (PotentiallyDeadPHIs.size() == 16)
10965     return false;
10966
10967   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10968     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10969
10970   return false;
10971 }
10972
10973 /// PHIsEqualValue - Return true if this phi node is always equal to
10974 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10975 ///   z = some value; x = phi (y, z); y = phi (x, z)
10976 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10977                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10978   // See if we already saw this PHI node.
10979   if (!ValueEqualPHIs.insert(PN))
10980     return true;
10981   
10982   // Don't scan crazily complex things.
10983   if (ValueEqualPHIs.size() == 16)
10984     return false;
10985  
10986   // Scan the operands to see if they are either phi nodes or are equal to
10987   // the value.
10988   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10989     Value *Op = PN->getIncomingValue(i);
10990     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10991       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10992         return false;
10993     } else if (Op != NonPhiInVal)
10994       return false;
10995   }
10996   
10997   return true;
10998 }
10999
11000
11001 // PHINode simplification
11002 //
11003 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
11004   // If LCSSA is around, don't mess with Phi nodes
11005   if (MustPreserveLCSSA) return 0;
11006   
11007   if (Value *V = PN.hasConstantValue())
11008     return ReplaceInstUsesWith(PN, V);
11009
11010   // If all PHI operands are the same operation, pull them through the PHI,
11011   // reducing code size.
11012   if (isa<Instruction>(PN.getIncomingValue(0)) &&
11013       isa<Instruction>(PN.getIncomingValue(1)) &&
11014       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11015       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11016       // FIXME: The hasOneUse check will fail for PHIs that use the value more
11017       // than themselves more than once.
11018       PN.getIncomingValue(0)->hasOneUse())
11019     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11020       return Result;
11021
11022   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
11023   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11024   // PHI)... break the cycle.
11025   if (PN.hasOneUse()) {
11026     Instruction *PHIUser = cast<Instruction>(PN.use_back());
11027     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
11028       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
11029       PotentiallyDeadPHIs.insert(&PN);
11030       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
11031         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11032     }
11033    
11034     // If this phi has a single use, and if that use just computes a value for
11035     // the next iteration of a loop, delete the phi.  This occurs with unused
11036     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
11037     // common case here is good because the only other things that catch this
11038     // are induction variable analysis (sometimes) and ADCE, which is only run
11039     // late.
11040     if (PHIUser->hasOneUse() &&
11041         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11042         PHIUser->use_back() == &PN) {
11043       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11044     }
11045   }
11046
11047   // We sometimes end up with phi cycles that non-obviously end up being the
11048   // same value, for example:
11049   //   z = some value; x = phi (y, z); y = phi (x, z)
11050   // where the phi nodes don't necessarily need to be in the same block.  Do a
11051   // quick check to see if the PHI node only contains a single non-phi value, if
11052   // so, scan to see if the phi cycle is actually equal to that value.
11053   {
11054     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11055     // Scan for the first non-phi operand.
11056     while (InValNo != NumOperandVals && 
11057            isa<PHINode>(PN.getIncomingValue(InValNo)))
11058       ++InValNo;
11059
11060     if (InValNo != NumOperandVals) {
11061       Value *NonPhiInVal = PN.getOperand(InValNo);
11062       
11063       // Scan the rest of the operands to see if there are any conflicts, if so
11064       // there is no need to recursively scan other phis.
11065       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11066         Value *OpVal = PN.getIncomingValue(InValNo);
11067         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11068           break;
11069       }
11070       
11071       // If we scanned over all operands, then we have one unique value plus
11072       // phi values.  Scan PHI nodes to see if they all merge in each other or
11073       // the value.
11074       if (InValNo == NumOperandVals) {
11075         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11076         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11077           return ReplaceInstUsesWith(PN, NonPhiInVal);
11078       }
11079     }
11080   }
11081
11082   // If there are multiple PHIs, sort their operands so that they all list
11083   // the blocks in the same order. This will help identical PHIs be eliminated
11084   // by other passes. Other passes shouldn't depend on this for correctness
11085   // however.
11086   PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11087   if (&PN != FirstPN)
11088     for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
11089       BasicBlock *BBA = PN.getIncomingBlock(i);
11090       BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11091       if (BBA != BBB) {
11092         Value *VA = PN.getIncomingValue(i);
11093         unsigned j = PN.getBasicBlockIndex(BBB);
11094         Value *VB = PN.getIncomingValue(j);
11095         PN.setIncomingBlock(i, BBB);
11096         PN.setIncomingValue(i, VB);
11097         PN.setIncomingBlock(j, BBA);
11098         PN.setIncomingValue(j, VA);
11099         // NOTE: Instcombine normally would want us to "return &PN" if we
11100         // modified any of the operands of an instruction.  However, since we
11101         // aren't adding or removing uses (just rearranging them) we don't do
11102         // this in this case.
11103       }
11104     }
11105
11106   return 0;
11107 }
11108
11109 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11110   Value *PtrOp = GEP.getOperand(0);
11111   // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
11112   if (GEP.getNumOperands() == 1)
11113     return ReplaceInstUsesWith(GEP, PtrOp);
11114
11115   if (isa<UndefValue>(GEP.getOperand(0)))
11116     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
11117
11118   bool HasZeroPointerIndex = false;
11119   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11120     HasZeroPointerIndex = C->isNullValue();
11121
11122   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11123     return ReplaceInstUsesWith(GEP, PtrOp);
11124
11125   // Eliminate unneeded casts for indices.
11126   if (TD) {
11127     bool MadeChange = false;
11128     unsigned PtrSize = TD->getPointerSizeInBits();
11129     
11130     gep_type_iterator GTI = gep_type_begin(GEP);
11131     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11132          I != E; ++I, ++GTI) {
11133       if (!isa<SequentialType>(*GTI)) continue;
11134       
11135       // If we are using a wider index than needed for this platform, shrink it
11136       // to what we need.  If narrower, sign-extend it to what we need.  This
11137       // explicit cast can make subsequent optimizations more obvious.
11138       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11139       if (OpBits == PtrSize)
11140         continue;
11141       
11142       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
11143       MadeChange = true;
11144     }
11145     if (MadeChange) return &GEP;
11146   }
11147
11148   // Combine Indices - If the source pointer to this getelementptr instruction
11149   // is a getelementptr instruction, combine the indices of the two
11150   // getelementptr instructions into a single instruction.
11151   //
11152   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11153     // Note that if our source is a gep chain itself that we wait for that
11154     // chain to be resolved before we perform this transformation.  This
11155     // avoids us creating a TON of code in some cases.
11156     //
11157     if (GetElementPtrInst *SrcGEP =
11158           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11159       if (SrcGEP->getNumOperands() == 2)
11160         return 0;   // Wait until our source is folded to completion.
11161
11162     SmallVector<Value*, 8> Indices;
11163
11164     // Find out whether the last index in the source GEP is a sequential idx.
11165     bool EndsWithSequential = false;
11166     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11167          I != E; ++I)
11168       EndsWithSequential = !isa<StructType>(*I);
11169
11170     // Can we combine the two pointer arithmetics offsets?
11171     if (EndsWithSequential) {
11172       // Replace: gep (gep %P, long B), long A, ...
11173       // With:    T = long A+B; gep %P, T, ...
11174       //
11175       Value *Sum;
11176       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11177       Value *GO1 = GEP.getOperand(1);
11178       if (SO1 == Constant::getNullValue(SO1->getType())) {
11179         Sum = GO1;
11180       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11181         Sum = SO1;
11182       } else {
11183         // If they aren't the same type, then the input hasn't been processed
11184         // by the loop above yet (which canonicalizes sequential index types to
11185         // intptr_t).  Just avoid transforming this until the input has been
11186         // normalized.
11187         if (SO1->getType() != GO1->getType())
11188           return 0;
11189         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11190       }
11191
11192       // Update the GEP in place if possible.
11193       if (Src->getNumOperands() == 2) {
11194         GEP.setOperand(0, Src->getOperand(0));
11195         GEP.setOperand(1, Sum);
11196         return &GEP;
11197       }
11198       Indices.append(Src->op_begin()+1, Src->op_end()-1);
11199       Indices.push_back(Sum);
11200       Indices.append(GEP.op_begin()+2, GEP.op_end());
11201     } else if (isa<Constant>(*GEP.idx_begin()) &&
11202                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11203                Src->getNumOperands() != 1) {
11204       // Otherwise we can do the fold if the first index of the GEP is a zero
11205       Indices.append(Src->op_begin()+1, Src->op_end());
11206       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
11207     }
11208
11209     if (!Indices.empty())
11210       return (cast<GEPOperator>(&GEP)->isInBounds() &&
11211               Src->isInBounds()) ?
11212         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11213                                           Indices.end(), GEP.getName()) :
11214         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11215                                   Indices.end(), GEP.getName());
11216   }
11217   
11218   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11219   if (Value *X = getBitCastOperand(PtrOp)) {
11220     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11221
11222     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
11223     // want to change the gep until the bitcasts are eliminated.
11224     if (getBitCastOperand(X)) {
11225       Worklist.AddValue(PtrOp);
11226       return 0;
11227     }
11228     
11229     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11230     // into     : GEP [10 x i8]* X, i32 0, ...
11231     //
11232     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11233     //           into     : GEP i8* X, ...
11234     // 
11235     // This occurs when the program declares an array extern like "int X[];"
11236     if (HasZeroPointerIndex) {
11237       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11238       const PointerType *XTy = cast<PointerType>(X->getType());
11239       if (const ArrayType *CATy =
11240           dyn_cast<ArrayType>(CPTy->getElementType())) {
11241         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11242         if (CATy->getElementType() == XTy->getElementType()) {
11243           // -> GEP i8* X, ...
11244           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11245           return cast<GEPOperator>(&GEP)->isInBounds() ?
11246             GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11247                                               GEP.getName()) :
11248             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11249                                       GEP.getName());
11250         }
11251         
11252         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11253           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11254           if (CATy->getElementType() == XATy->getElementType()) {
11255             // -> GEP [10 x i8]* X, i32 0, ...
11256             // At this point, we know that the cast source type is a pointer
11257             // to an array of the same type as the destination pointer
11258             // array.  Because the array type is never stepped over (there
11259             // is a leading zero) we can fold the cast into this GEP.
11260             GEP.setOperand(0, X);
11261             return &GEP;
11262           }
11263         }
11264       }
11265     } else if (GEP.getNumOperands() == 2) {
11266       // Transform things like:
11267       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11268       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11269       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11270       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11271       if (TD && isa<ArrayType>(SrcElTy) &&
11272           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11273           TD->getTypeAllocSize(ResElTy)) {
11274         Value *Idx[2];
11275         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11276         Idx[1] = GEP.getOperand(1);
11277         Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11278           Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11279           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11280         // V and GEP are both pointer types --> BitCast
11281         return new BitCastInst(NewGEP, GEP.getType());
11282       }
11283       
11284       // Transform things like:
11285       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11286       //   (where tmp = 8*tmp2) into:
11287       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11288       
11289       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11290         uint64_t ArrayEltSize =
11291             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11292         
11293         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11294         // allow either a mul, shift, or constant here.
11295         Value *NewIdx = 0;
11296         ConstantInt *Scale = 0;
11297         if (ArrayEltSize == 1) {
11298           NewIdx = GEP.getOperand(1);
11299           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11300         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11301           NewIdx = ConstantInt::get(CI->getType(), 1);
11302           Scale = CI;
11303         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11304           if (Inst->getOpcode() == Instruction::Shl &&
11305               isa<ConstantInt>(Inst->getOperand(1))) {
11306             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11307             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11308             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11309                                      1ULL << ShAmtVal);
11310             NewIdx = Inst->getOperand(0);
11311           } else if (Inst->getOpcode() == Instruction::Mul &&
11312                      isa<ConstantInt>(Inst->getOperand(1))) {
11313             Scale = cast<ConstantInt>(Inst->getOperand(1));
11314             NewIdx = Inst->getOperand(0);
11315           }
11316         }
11317         
11318         // If the index will be to exactly the right offset with the scale taken
11319         // out, perform the transformation. Note, we don't know whether Scale is
11320         // signed or not. We'll use unsigned version of division/modulo
11321         // operation after making sure Scale doesn't have the sign bit set.
11322         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11323             Scale->getZExtValue() % ArrayEltSize == 0) {
11324           Scale = ConstantInt::get(Scale->getType(),
11325                                    Scale->getZExtValue() / ArrayEltSize);
11326           if (Scale->getZExtValue() != 1) {
11327             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11328                                                        false /*ZExt*/);
11329             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11330           }
11331
11332           // Insert the new GEP instruction.
11333           Value *Idx[2];
11334           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11335           Idx[1] = NewIdx;
11336           Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11337             Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11338             Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11339           // The NewGEP must be pointer typed, so must the old one -> BitCast
11340           return new BitCastInst(NewGEP, GEP.getType());
11341         }
11342       }
11343     }
11344   }
11345   
11346   /// See if we can simplify:
11347   ///   X = bitcast A* to B*
11348   ///   Y = gep X, <...constant indices...>
11349   /// into a gep of the original struct.  This is important for SROA and alias
11350   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11351   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11352     if (TD &&
11353         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11354       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11355       // a constant back from EmitGEPOffset.
11356       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
11357       int64_t Offset = OffsetV->getSExtValue();
11358       
11359       // If this GEP instruction doesn't move the pointer, just replace the GEP
11360       // with a bitcast of the real input to the dest type.
11361       if (Offset == 0) {
11362         // If the bitcast is of an allocation, and the allocation will be
11363         // converted to match the type of the cast, don't touch this.
11364         if (isa<AllocaInst>(BCI->getOperand(0)) ||
11365             isMalloc(BCI->getOperand(0))) {
11366           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11367           if (Instruction *I = visitBitCast(*BCI)) {
11368             if (I != BCI) {
11369               I->takeName(BCI);
11370               BCI->getParent()->getInstList().insert(BCI, I);
11371               ReplaceInstUsesWith(*BCI, I);
11372             }
11373             return &GEP;
11374           }
11375         }
11376         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11377       }
11378       
11379       // Otherwise, if the offset is non-zero, we need to find out if there is a
11380       // field at Offset in 'A's type.  If so, we can pull the cast through the
11381       // GEP.
11382       SmallVector<Value*, 8> NewIndices;
11383       const Type *InTy =
11384         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11385       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11386         Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11387           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11388                                      NewIndices.end()) :
11389           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11390                              NewIndices.end());
11391         
11392         if (NGEP->getType() == GEP.getType())
11393           return ReplaceInstUsesWith(GEP, NGEP);
11394         NGEP->takeName(&GEP);
11395         return new BitCastInst(NGEP, GEP.getType());
11396       }
11397     }
11398   }    
11399     
11400   return 0;
11401 }
11402
11403 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
11404   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
11405   if (AI.isArrayAllocation()) {  // Check C != 1
11406     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11407       const Type *NewTy = 
11408         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11409       assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11410       AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11411       New->setAlignment(AI.getAlignment());
11412
11413       // Scan to the end of the allocation instructions, to skip over a block of
11414       // allocas if possible...also skip interleaved debug info
11415       //
11416       BasicBlock::iterator It = New;
11417       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11418
11419       // Now that I is pointing to the first non-allocation-inst in the block,
11420       // insert our getelementptr instruction...
11421       //
11422       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11423       Value *Idx[2];
11424       Idx[0] = NullIdx;
11425       Idx[1] = NullIdx;
11426       Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11427                                                    New->getName()+".sub", It);
11428
11429       // Now make everything use the getelementptr instead of the original
11430       // allocation.
11431       return ReplaceInstUsesWith(AI, V);
11432     } else if (isa<UndefValue>(AI.getArraySize())) {
11433       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11434     }
11435   }
11436
11437   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11438     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11439     // Note that we only do this for alloca's, because malloc should allocate
11440     // and return a unique pointer, even for a zero byte allocation.
11441     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11442       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11443
11444     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11445     if (AI.getAlignment() == 0)
11446       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11447   }
11448
11449   return 0;
11450 }
11451
11452 Instruction *InstCombiner::visitFree(Instruction &FI) {
11453   Value *Op = FI.getOperand(1);
11454
11455   // free undef -> unreachable.
11456   if (isa<UndefValue>(Op)) {
11457     // Insert a new store to null because we cannot modify the CFG here.
11458     new StoreInst(ConstantInt::getTrue(*Context),
11459            UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11460     return EraseInstFromFunction(FI);
11461   }
11462   
11463   // If we have 'free null' delete the instruction.  This can happen in stl code
11464   // when lots of inlining happens.
11465   if (isa<ConstantPointerNull>(Op))
11466     return EraseInstFromFunction(FI);
11467
11468   // If we have a malloc call whose only use is a free call, delete both.
11469   if (isMalloc(Op)) {
11470     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11471       if (Op->hasOneUse() && CI->hasOneUse()) {
11472         EraseInstFromFunction(FI);
11473         EraseInstFromFunction(*CI);
11474         return EraseInstFromFunction(*cast<Instruction>(Op));
11475       }
11476     } else {
11477       // Op is a call to malloc
11478       if (Op->hasOneUse()) {
11479         EraseInstFromFunction(FI);
11480         return EraseInstFromFunction(*cast<Instruction>(Op));
11481       }
11482     }
11483   }
11484
11485   return 0;
11486 }
11487
11488 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11489 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11490                                         const TargetData *TD) {
11491   User *CI = cast<User>(LI.getOperand(0));
11492   Value *CastOp = CI->getOperand(0);
11493   LLVMContext *Context = IC.getContext();
11494
11495   const PointerType *DestTy = cast<PointerType>(CI->getType());
11496   const Type *DestPTy = DestTy->getElementType();
11497   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11498
11499     // If the address spaces don't match, don't eliminate the cast.
11500     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11501       return 0;
11502
11503     const Type *SrcPTy = SrcTy->getElementType();
11504
11505     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11506          isa<VectorType>(DestPTy)) {
11507       // If the source is an array, the code below will not succeed.  Check to
11508       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11509       // constants.
11510       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11511         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11512           if (ASrcTy->getNumElements() != 0) {
11513             Value *Idxs[2];
11514             Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11515             Idxs[1] = Idxs[0];
11516             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11517             SrcTy = cast<PointerType>(CastOp->getType());
11518             SrcPTy = SrcTy->getElementType();
11519           }
11520
11521       if (IC.getTargetData() &&
11522           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11523             isa<VectorType>(SrcPTy)) &&
11524           // Do not allow turning this into a load of an integer, which is then
11525           // casted to a pointer, this pessimizes pointer analysis a lot.
11526           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11527           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11528                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11529
11530         // Okay, we are casting from one integer or pointer type to another of
11531         // the same size.  Instead of casting the pointer before the load, cast
11532         // the result of the loaded value.
11533         Value *NewLoad = 
11534           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11535         // Now cast the result of the load.
11536         return new BitCastInst(NewLoad, LI.getType());
11537       }
11538     }
11539   }
11540   return 0;
11541 }
11542
11543 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11544   Value *Op = LI.getOperand(0);
11545
11546   // Attempt to improve the alignment.
11547   if (TD) {
11548     unsigned KnownAlign =
11549       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11550     if (KnownAlign >
11551         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11552                                   LI.getAlignment()))
11553       LI.setAlignment(KnownAlign);
11554   }
11555
11556   // load (cast X) --> cast (load X) iff safe.
11557   if (isa<CastInst>(Op))
11558     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11559       return Res;
11560
11561   // None of the following transforms are legal for volatile loads.
11562   if (LI.isVolatile()) return 0;
11563   
11564   // Do really simple store-to-load forwarding and load CSE, to catch cases
11565   // where there are several consequtive memory accesses to the same location,
11566   // separated by a few arithmetic operations.
11567   BasicBlock::iterator BBI = &LI;
11568   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11569     return ReplaceInstUsesWith(LI, AvailableVal);
11570
11571   // load(gep null, ...) -> unreachable
11572   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11573     const Value *GEPI0 = GEPI->getOperand(0);
11574     // TODO: Consider a target hook for valid address spaces for this xform.
11575     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11576       // Insert a new store to null instruction before the load to indicate
11577       // that this code is not reachable.  We do this instead of inserting
11578       // an unreachable instruction directly because we cannot modify the
11579       // CFG.
11580       new StoreInst(UndefValue::get(LI.getType()),
11581                     Constant::getNullValue(Op->getType()), &LI);
11582       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11583     }
11584   } 
11585
11586   // load null/undef -> unreachable
11587   // TODO: Consider a target hook for valid address spaces for this xform.
11588   if (isa<UndefValue>(Op) ||
11589       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11590     // Insert a new store to null instruction before the load to indicate that
11591     // this code is not reachable.  We do this instead of inserting an
11592     // unreachable instruction directly because we cannot modify the CFG.
11593     new StoreInst(UndefValue::get(LI.getType()),
11594                   Constant::getNullValue(Op->getType()), &LI);
11595     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11596   }
11597
11598   // Instcombine load (constantexpr_cast global) -> cast (load global)
11599   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11600     if (CE->isCast())
11601       if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11602         return Res;
11603   
11604   if (Op->hasOneUse()) {
11605     // Change select and PHI nodes to select values instead of addresses: this
11606     // helps alias analysis out a lot, allows many others simplifications, and
11607     // exposes redundancy in the code.
11608     //
11609     // Note that we cannot do the transformation unless we know that the
11610     // introduced loads cannot trap!  Something like this is valid as long as
11611     // the condition is always false: load (select bool %C, int* null, int* %G),
11612     // but it would not be valid if we transformed it to load from null
11613     // unconditionally.
11614     //
11615     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11616       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11617       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11618           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11619         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11620                                         SI->getOperand(1)->getName()+".val");
11621         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11622                                         SI->getOperand(2)->getName()+".val");
11623         return SelectInst::Create(SI->getCondition(), V1, V2);
11624       }
11625
11626       // load (select (cond, null, P)) -> load P
11627       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11628         if (C->isNullValue()) {
11629           LI.setOperand(0, SI->getOperand(2));
11630           return &LI;
11631         }
11632
11633       // load (select (cond, P, null)) -> load P
11634       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11635         if (C->isNullValue()) {
11636           LI.setOperand(0, SI->getOperand(1));
11637           return &LI;
11638         }
11639     }
11640   }
11641   return 0;
11642 }
11643
11644 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11645 /// when possible.  This makes it generally easy to do alias analysis and/or
11646 /// SROA/mem2reg of the memory object.
11647 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11648   User *CI = cast<User>(SI.getOperand(1));
11649   Value *CastOp = CI->getOperand(0);
11650
11651   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11652   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11653   if (SrcTy == 0) return 0;
11654   
11655   const Type *SrcPTy = SrcTy->getElementType();
11656
11657   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11658     return 0;
11659   
11660   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11661   /// to its first element.  This allows us to handle things like:
11662   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11663   /// on 32-bit hosts.
11664   SmallVector<Value*, 4> NewGEPIndices;
11665   
11666   // If the source is an array, the code below will not succeed.  Check to
11667   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11668   // constants.
11669   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11670     // Index through pointer.
11671     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11672     NewGEPIndices.push_back(Zero);
11673     
11674     while (1) {
11675       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11676         if (!STy->getNumElements()) /* Struct can be empty {} */
11677           break;
11678         NewGEPIndices.push_back(Zero);
11679         SrcPTy = STy->getElementType(0);
11680       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11681         NewGEPIndices.push_back(Zero);
11682         SrcPTy = ATy->getElementType();
11683       } else {
11684         break;
11685       }
11686     }
11687     
11688     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11689   }
11690
11691   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11692     return 0;
11693   
11694   // If the pointers point into different address spaces or if they point to
11695   // values with different sizes, we can't do the transformation.
11696   if (!IC.getTargetData() ||
11697       SrcTy->getAddressSpace() != 
11698         cast<PointerType>(CI->getType())->getAddressSpace() ||
11699       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11700       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11701     return 0;
11702
11703   // Okay, we are casting from one integer or pointer type to another of
11704   // the same size.  Instead of casting the pointer before 
11705   // the store, cast the value to be stored.
11706   Value *NewCast;
11707   Value *SIOp0 = SI.getOperand(0);
11708   Instruction::CastOps opcode = Instruction::BitCast;
11709   const Type* CastSrcTy = SIOp0->getType();
11710   const Type* CastDstTy = SrcPTy;
11711   if (isa<PointerType>(CastDstTy)) {
11712     if (CastSrcTy->isInteger())
11713       opcode = Instruction::IntToPtr;
11714   } else if (isa<IntegerType>(CastDstTy)) {
11715     if (isa<PointerType>(SIOp0->getType()))
11716       opcode = Instruction::PtrToInt;
11717   }
11718   
11719   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11720   // emit a GEP to index into its first field.
11721   if (!NewGEPIndices.empty())
11722     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11723                                            NewGEPIndices.end());
11724   
11725   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11726                                    SIOp0->getName()+".c");
11727   return new StoreInst(NewCast, CastOp);
11728 }
11729
11730 /// equivalentAddressValues - Test if A and B will obviously have the same
11731 /// value. This includes recognizing that %t0 and %t1 will have the same
11732 /// value in code like this:
11733 ///   %t0 = getelementptr \@a, 0, 3
11734 ///   store i32 0, i32* %t0
11735 ///   %t1 = getelementptr \@a, 0, 3
11736 ///   %t2 = load i32* %t1
11737 ///
11738 static bool equivalentAddressValues(Value *A, Value *B) {
11739   // Test if the values are trivially equivalent.
11740   if (A == B) return true;
11741   
11742   // Test if the values come form identical arithmetic instructions.
11743   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11744   // its only used to compare two uses within the same basic block, which
11745   // means that they'll always either have the same value or one of them
11746   // will have an undefined value.
11747   if (isa<BinaryOperator>(A) ||
11748       isa<CastInst>(A) ||
11749       isa<PHINode>(A) ||
11750       isa<GetElementPtrInst>(A))
11751     if (Instruction *BI = dyn_cast<Instruction>(B))
11752       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11753         return true;
11754   
11755   // Otherwise they may not be equivalent.
11756   return false;
11757 }
11758
11759 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11760 // return the llvm.dbg.declare.
11761 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11762   if (!V->hasNUses(2))
11763     return 0;
11764   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11765        UI != E; ++UI) {
11766     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11767       return DI;
11768     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11769       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11770         return DI;
11771       }
11772   }
11773   return 0;
11774 }
11775
11776 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11777   Value *Val = SI.getOperand(0);
11778   Value *Ptr = SI.getOperand(1);
11779
11780   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11781     EraseInstFromFunction(SI);
11782     ++NumCombined;
11783     return 0;
11784   }
11785   
11786   // If the RHS is an alloca with a single use, zapify the store, making the
11787   // alloca dead.
11788   // If the RHS is an alloca with a two uses, the other one being a 
11789   // llvm.dbg.declare, zapify the store and the declare, making the
11790   // alloca dead.  We must do this to prevent declare's from affecting
11791   // codegen.
11792   if (!SI.isVolatile()) {
11793     if (Ptr->hasOneUse()) {
11794       if (isa<AllocaInst>(Ptr)) {
11795         EraseInstFromFunction(SI);
11796         ++NumCombined;
11797         return 0;
11798       }
11799       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11800         if (isa<AllocaInst>(GEP->getOperand(0))) {
11801           if (GEP->getOperand(0)->hasOneUse()) {
11802             EraseInstFromFunction(SI);
11803             ++NumCombined;
11804             return 0;
11805           }
11806           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11807             EraseInstFromFunction(*DI);
11808             EraseInstFromFunction(SI);
11809             ++NumCombined;
11810             return 0;
11811           }
11812         }
11813       }
11814     }
11815     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11816       EraseInstFromFunction(*DI);
11817       EraseInstFromFunction(SI);
11818       ++NumCombined;
11819       return 0;
11820     }
11821   }
11822
11823   // Attempt to improve the alignment.
11824   if (TD) {
11825     unsigned KnownAlign =
11826       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11827     if (KnownAlign >
11828         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11829                                   SI.getAlignment()))
11830       SI.setAlignment(KnownAlign);
11831   }
11832
11833   // Do really simple DSE, to catch cases where there are several consecutive
11834   // stores to the same location, separated by a few arithmetic operations. This
11835   // situation often occurs with bitfield accesses.
11836   BasicBlock::iterator BBI = &SI;
11837   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11838        --ScanInsts) {
11839     --BBI;
11840     // Don't count debug info directives, lest they affect codegen,
11841     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11842     // It is necessary for correctness to skip those that feed into a
11843     // llvm.dbg.declare, as these are not present when debugging is off.
11844     if (isa<DbgInfoIntrinsic>(BBI) ||
11845         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11846       ScanInsts++;
11847       continue;
11848     }    
11849     
11850     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11851       // Prev store isn't volatile, and stores to the same location?
11852       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11853                                                           SI.getOperand(1))) {
11854         ++NumDeadStore;
11855         ++BBI;
11856         EraseInstFromFunction(*PrevSI);
11857         continue;
11858       }
11859       break;
11860     }
11861     
11862     // If this is a load, we have to stop.  However, if the loaded value is from
11863     // the pointer we're loading and is producing the pointer we're storing,
11864     // then *this* store is dead (X = load P; store X -> P).
11865     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11866       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11867           !SI.isVolatile()) {
11868         EraseInstFromFunction(SI);
11869         ++NumCombined;
11870         return 0;
11871       }
11872       // Otherwise, this is a load from some other location.  Stores before it
11873       // may not be dead.
11874       break;
11875     }
11876     
11877     // Don't skip over loads or things that can modify memory.
11878     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11879       break;
11880   }
11881   
11882   
11883   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11884
11885   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11886   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11887     if (!isa<UndefValue>(Val)) {
11888       SI.setOperand(0, UndefValue::get(Val->getType()));
11889       if (Instruction *U = dyn_cast<Instruction>(Val))
11890         Worklist.Add(U);  // Dropped a use.
11891       ++NumCombined;
11892     }
11893     return 0;  // Do not modify these!
11894   }
11895
11896   // store undef, Ptr -> noop
11897   if (isa<UndefValue>(Val)) {
11898     EraseInstFromFunction(SI);
11899     ++NumCombined;
11900     return 0;
11901   }
11902
11903   // If the pointer destination is a cast, see if we can fold the cast into the
11904   // source instead.
11905   if (isa<CastInst>(Ptr))
11906     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11907       return Res;
11908   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11909     if (CE->isCast())
11910       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11911         return Res;
11912
11913   
11914   // If this store is the last instruction in the basic block (possibly
11915   // excepting debug info instructions and the pointer bitcasts that feed
11916   // into them), and if the block ends with an unconditional branch, try
11917   // to move it to the successor block.
11918   BBI = &SI; 
11919   do {
11920     ++BBI;
11921   } while (isa<DbgInfoIntrinsic>(BBI) ||
11922            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11923   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11924     if (BI->isUnconditional())
11925       if (SimplifyStoreAtEndOfBlock(SI))
11926         return 0;  // xform done!
11927   
11928   return 0;
11929 }
11930
11931 /// SimplifyStoreAtEndOfBlock - Turn things like:
11932 ///   if () { *P = v1; } else { *P = v2 }
11933 /// into a phi node with a store in the successor.
11934 ///
11935 /// Simplify things like:
11936 ///   *P = v1; if () { *P = v2; }
11937 /// into a phi node with a store in the successor.
11938 ///
11939 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11940   BasicBlock *StoreBB = SI.getParent();
11941   
11942   // Check to see if the successor block has exactly two incoming edges.  If
11943   // so, see if the other predecessor contains a store to the same location.
11944   // if so, insert a PHI node (if needed) and move the stores down.
11945   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11946   
11947   // Determine whether Dest has exactly two predecessors and, if so, compute
11948   // the other predecessor.
11949   pred_iterator PI = pred_begin(DestBB);
11950   BasicBlock *OtherBB = 0;
11951   if (*PI != StoreBB)
11952     OtherBB = *PI;
11953   ++PI;
11954   if (PI == pred_end(DestBB))
11955     return false;
11956   
11957   if (*PI != StoreBB) {
11958     if (OtherBB)
11959       return false;
11960     OtherBB = *PI;
11961   }
11962   if (++PI != pred_end(DestBB))
11963     return false;
11964
11965   // Bail out if all the relevant blocks aren't distinct (this can happen,
11966   // for example, if SI is in an infinite loop)
11967   if (StoreBB == DestBB || OtherBB == DestBB)
11968     return false;
11969
11970   // Verify that the other block ends in a branch and is not otherwise empty.
11971   BasicBlock::iterator BBI = OtherBB->getTerminator();
11972   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11973   if (!OtherBr || BBI == OtherBB->begin())
11974     return false;
11975   
11976   // If the other block ends in an unconditional branch, check for the 'if then
11977   // else' case.  there is an instruction before the branch.
11978   StoreInst *OtherStore = 0;
11979   if (OtherBr->isUnconditional()) {
11980     --BBI;
11981     // Skip over debugging info.
11982     while (isa<DbgInfoIntrinsic>(BBI) ||
11983            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11984       if (BBI==OtherBB->begin())
11985         return false;
11986       --BBI;
11987     }
11988     // If this isn't a store, isn't a store to the same location, or if the
11989     // alignments differ, bail out.
11990     OtherStore = dyn_cast<StoreInst>(BBI);
11991     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
11992         OtherStore->getAlignment() != SI.getAlignment())
11993       return false;
11994   } else {
11995     // Otherwise, the other block ended with a conditional branch. If one of the
11996     // destinations is StoreBB, then we have the if/then case.
11997     if (OtherBr->getSuccessor(0) != StoreBB && 
11998         OtherBr->getSuccessor(1) != StoreBB)
11999       return false;
12000     
12001     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12002     // if/then triangle.  See if there is a store to the same ptr as SI that
12003     // lives in OtherBB.
12004     for (;; --BBI) {
12005       // Check to see if we find the matching store.
12006       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12007         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12008             OtherStore->getAlignment() != SI.getAlignment())
12009           return false;
12010         break;
12011       }
12012       // If we find something that may be using or overwriting the stored
12013       // value, or if we run out of instructions, we can't do the xform.
12014       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12015           BBI == OtherBB->begin())
12016         return false;
12017     }
12018     
12019     // In order to eliminate the store in OtherBr, we have to
12020     // make sure nothing reads or overwrites the stored value in
12021     // StoreBB.
12022     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12023       // FIXME: This should really be AA driven.
12024       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12025         return false;
12026     }
12027   }
12028   
12029   // Insert a PHI node now if we need it.
12030   Value *MergedVal = OtherStore->getOperand(0);
12031   if (MergedVal != SI.getOperand(0)) {
12032     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12033     PN->reserveOperandSpace(2);
12034     PN->addIncoming(SI.getOperand(0), SI.getParent());
12035     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12036     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12037   }
12038   
12039   // Advance to a place where it is safe to insert the new store and
12040   // insert it.
12041   BBI = DestBB->getFirstNonPHI();
12042   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12043                                     OtherStore->isVolatile(),
12044                                     SI.getAlignment()), *BBI);
12045   
12046   // Nuke the old stores.
12047   EraseInstFromFunction(SI);
12048   EraseInstFromFunction(*OtherStore);
12049   ++NumCombined;
12050   return true;
12051 }
12052
12053
12054 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12055   // Change br (not X), label True, label False to: br X, label False, True
12056   Value *X = 0;
12057   BasicBlock *TrueDest;
12058   BasicBlock *FalseDest;
12059   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12060       !isa<Constant>(X)) {
12061     // Swap Destinations and condition...
12062     BI.setCondition(X);
12063     BI.setSuccessor(0, FalseDest);
12064     BI.setSuccessor(1, TrueDest);
12065     return &BI;
12066   }
12067
12068   // Cannonicalize fcmp_one -> fcmp_oeq
12069   FCmpInst::Predicate FPred; Value *Y;
12070   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12071                              TrueDest, FalseDest)) &&
12072       BI.getCondition()->hasOneUse())
12073     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12074         FPred == FCmpInst::FCMP_OGE) {
12075       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12076       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12077       
12078       // Swap Destinations and condition.
12079       BI.setSuccessor(0, FalseDest);
12080       BI.setSuccessor(1, TrueDest);
12081       Worklist.Add(Cond);
12082       return &BI;
12083     }
12084
12085   // Cannonicalize icmp_ne -> icmp_eq
12086   ICmpInst::Predicate IPred;
12087   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12088                       TrueDest, FalseDest)) &&
12089       BI.getCondition()->hasOneUse())
12090     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12091         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12092         IPred == ICmpInst::ICMP_SGE) {
12093       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12094       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12095       // Swap Destinations and condition.
12096       BI.setSuccessor(0, FalseDest);
12097       BI.setSuccessor(1, TrueDest);
12098       Worklist.Add(Cond);
12099       return &BI;
12100     }
12101
12102   return 0;
12103 }
12104
12105 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12106   Value *Cond = SI.getCondition();
12107   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12108     if (I->getOpcode() == Instruction::Add)
12109       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12110         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12111         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12112           SI.setOperand(i,
12113                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12114                                                 AddRHS));
12115         SI.setOperand(0, I->getOperand(0));
12116         Worklist.Add(I);
12117         return &SI;
12118       }
12119   }
12120   return 0;
12121 }
12122
12123 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12124   Value *Agg = EV.getAggregateOperand();
12125
12126   if (!EV.hasIndices())
12127     return ReplaceInstUsesWith(EV, Agg);
12128
12129   if (Constant *C = dyn_cast<Constant>(Agg)) {
12130     if (isa<UndefValue>(C))
12131       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12132       
12133     if (isa<ConstantAggregateZero>(C))
12134       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12135
12136     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12137       // Extract the element indexed by the first index out of the constant
12138       Value *V = C->getOperand(*EV.idx_begin());
12139       if (EV.getNumIndices() > 1)
12140         // Extract the remaining indices out of the constant indexed by the
12141         // first index
12142         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12143       else
12144         return ReplaceInstUsesWith(EV, V);
12145     }
12146     return 0; // Can't handle other constants
12147   } 
12148   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12149     // We're extracting from an insertvalue instruction, compare the indices
12150     const unsigned *exti, *exte, *insi, *inse;
12151     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12152          exte = EV.idx_end(), inse = IV->idx_end();
12153          exti != exte && insi != inse;
12154          ++exti, ++insi) {
12155       if (*insi != *exti)
12156         // The insert and extract both reference distinctly different elements.
12157         // This means the extract is not influenced by the insert, and we can
12158         // replace the aggregate operand of the extract with the aggregate
12159         // operand of the insert. i.e., replace
12160         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12161         // %E = extractvalue { i32, { i32 } } %I, 0
12162         // with
12163         // %E = extractvalue { i32, { i32 } } %A, 0
12164         return ExtractValueInst::Create(IV->getAggregateOperand(),
12165                                         EV.idx_begin(), EV.idx_end());
12166     }
12167     if (exti == exte && insi == inse)
12168       // Both iterators are at the end: Index lists are identical. Replace
12169       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12170       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12171       // with "i32 42"
12172       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12173     if (exti == exte) {
12174       // The extract list is a prefix of the insert list. i.e. replace
12175       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12176       // %E = extractvalue { i32, { i32 } } %I, 1
12177       // with
12178       // %X = extractvalue { i32, { i32 } } %A, 1
12179       // %E = insertvalue { i32 } %X, i32 42, 0
12180       // by switching the order of the insert and extract (though the
12181       // insertvalue should be left in, since it may have other uses).
12182       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12183                                                  EV.idx_begin(), EV.idx_end());
12184       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12185                                      insi, inse);
12186     }
12187     if (insi == inse)
12188       // The insert list is a prefix of the extract list
12189       // We can simply remove the common indices from the extract and make it
12190       // operate on the inserted value instead of the insertvalue result.
12191       // i.e., replace
12192       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12193       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12194       // with
12195       // %E extractvalue { i32 } { i32 42 }, 0
12196       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12197                                       exti, exte);
12198   }
12199   // Can't simplify extracts from other values. Note that nested extracts are
12200   // already simplified implicitely by the above (extract ( extract (insert) )
12201   // will be translated into extract ( insert ( extract ) ) first and then just
12202   // the value inserted, if appropriate).
12203   return 0;
12204 }
12205
12206 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12207 /// is to leave as a vector operation.
12208 static bool CheapToScalarize(Value *V, bool isConstant) {
12209   if (isa<ConstantAggregateZero>(V)) 
12210     return true;
12211   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12212     if (isConstant) return true;
12213     // If all elts are the same, we can extract.
12214     Constant *Op0 = C->getOperand(0);
12215     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12216       if (C->getOperand(i) != Op0)
12217         return false;
12218     return true;
12219   }
12220   Instruction *I = dyn_cast<Instruction>(V);
12221   if (!I) return false;
12222   
12223   // Insert element gets simplified to the inserted element or is deleted if
12224   // this is constant idx extract element and its a constant idx insertelt.
12225   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12226       isa<ConstantInt>(I->getOperand(2)))
12227     return true;
12228   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12229     return true;
12230   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12231     if (BO->hasOneUse() &&
12232         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12233          CheapToScalarize(BO->getOperand(1), isConstant)))
12234       return true;
12235   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12236     if (CI->hasOneUse() &&
12237         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12238          CheapToScalarize(CI->getOperand(1), isConstant)))
12239       return true;
12240   
12241   return false;
12242 }
12243
12244 /// Read and decode a shufflevector mask.
12245 ///
12246 /// It turns undef elements into values that are larger than the number of
12247 /// elements in the input.
12248 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12249   unsigned NElts = SVI->getType()->getNumElements();
12250   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12251     return std::vector<unsigned>(NElts, 0);
12252   if (isa<UndefValue>(SVI->getOperand(2)))
12253     return std::vector<unsigned>(NElts, 2*NElts);
12254
12255   std::vector<unsigned> Result;
12256   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12257   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12258     if (isa<UndefValue>(*i))
12259       Result.push_back(NElts*2);  // undef -> 8
12260     else
12261       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12262   return Result;
12263 }
12264
12265 /// FindScalarElement - Given a vector and an element number, see if the scalar
12266 /// value is already around as a register, for example if it were inserted then
12267 /// extracted from the vector.
12268 static Value *FindScalarElement(Value *V, unsigned EltNo,
12269                                 LLVMContext *Context) {
12270   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12271   const VectorType *PTy = cast<VectorType>(V->getType());
12272   unsigned Width = PTy->getNumElements();
12273   if (EltNo >= Width)  // Out of range access.
12274     return UndefValue::get(PTy->getElementType());
12275   
12276   if (isa<UndefValue>(V))
12277     return UndefValue::get(PTy->getElementType());
12278   else if (isa<ConstantAggregateZero>(V))
12279     return Constant::getNullValue(PTy->getElementType());
12280   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12281     return CP->getOperand(EltNo);
12282   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12283     // If this is an insert to a variable element, we don't know what it is.
12284     if (!isa<ConstantInt>(III->getOperand(2))) 
12285       return 0;
12286     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12287     
12288     // If this is an insert to the element we are looking for, return the
12289     // inserted value.
12290     if (EltNo == IIElt) 
12291       return III->getOperand(1);
12292     
12293     // Otherwise, the insertelement doesn't modify the value, recurse on its
12294     // vector input.
12295     return FindScalarElement(III->getOperand(0), EltNo, Context);
12296   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12297     unsigned LHSWidth =
12298       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12299     unsigned InEl = getShuffleMask(SVI)[EltNo];
12300     if (InEl < LHSWidth)
12301       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12302     else if (InEl < LHSWidth*2)
12303       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12304     else
12305       return UndefValue::get(PTy->getElementType());
12306   }
12307   
12308   // Otherwise, we don't know.
12309   return 0;
12310 }
12311
12312 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12313   // If vector val is undef, replace extract with scalar undef.
12314   if (isa<UndefValue>(EI.getOperand(0)))
12315     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12316
12317   // If vector val is constant 0, replace extract with scalar 0.
12318   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12319     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12320   
12321   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12322     // If vector val is constant with all elements the same, replace EI with
12323     // that element. When the elements are not identical, we cannot replace yet
12324     // (we do that below, but only when the index is constant).
12325     Constant *op0 = C->getOperand(0);
12326     for (unsigned i = 1; i != C->getNumOperands(); ++i)
12327       if (C->getOperand(i) != op0) {
12328         op0 = 0; 
12329         break;
12330       }
12331     if (op0)
12332       return ReplaceInstUsesWith(EI, op0);
12333   }
12334   
12335   // If extracting a specified index from the vector, see if we can recursively
12336   // find a previously computed scalar that was inserted into the vector.
12337   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12338     unsigned IndexVal = IdxC->getZExtValue();
12339     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12340       
12341     // If this is extracting an invalid index, turn this into undef, to avoid
12342     // crashing the code below.
12343     if (IndexVal >= VectorWidth)
12344       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12345     
12346     // This instruction only demands the single element from the input vector.
12347     // If the input vector has a single use, simplify it based on this use
12348     // property.
12349     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12350       APInt UndefElts(VectorWidth, 0);
12351       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12352       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12353                                                 DemandedMask, UndefElts)) {
12354         EI.setOperand(0, V);
12355         return &EI;
12356       }
12357     }
12358     
12359     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12360       return ReplaceInstUsesWith(EI, Elt);
12361     
12362     // If the this extractelement is directly using a bitcast from a vector of
12363     // the same number of elements, see if we can find the source element from
12364     // it.  In this case, we will end up needing to bitcast the scalars.
12365     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12366       if (const VectorType *VT = 
12367               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12368         if (VT->getNumElements() == VectorWidth)
12369           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12370                                              IndexVal, Context))
12371             return new BitCastInst(Elt, EI.getType());
12372     }
12373   }
12374   
12375   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12376     // Push extractelement into predecessor operation if legal and
12377     // profitable to do so
12378     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12379       if (I->hasOneUse() &&
12380           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12381         Value *newEI0 =
12382           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12383                                         EI.getName()+".lhs");
12384         Value *newEI1 =
12385           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12386                                         EI.getName()+".rhs");
12387         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12388       }
12389     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12390       // Extracting the inserted element?
12391       if (IE->getOperand(2) == EI.getOperand(1))
12392         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12393       // If the inserted and extracted elements are constants, they must not
12394       // be the same value, extract from the pre-inserted value instead.
12395       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12396         Worklist.AddValue(EI.getOperand(0));
12397         EI.setOperand(0, IE->getOperand(0));
12398         return &EI;
12399       }
12400     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12401       // If this is extracting an element from a shufflevector, figure out where
12402       // it came from and extract from the appropriate input element instead.
12403       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12404         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12405         Value *Src;
12406         unsigned LHSWidth =
12407           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12408
12409         if (SrcIdx < LHSWidth)
12410           Src = SVI->getOperand(0);
12411         else if (SrcIdx < LHSWidth*2) {
12412           SrcIdx -= LHSWidth;
12413           Src = SVI->getOperand(1);
12414         } else {
12415           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12416         }
12417         return ExtractElementInst::Create(Src,
12418                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12419                                           false));
12420       }
12421     }
12422     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12423   }
12424   return 0;
12425 }
12426
12427 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12428 /// elements from either LHS or RHS, return the shuffle mask and true. 
12429 /// Otherwise, return false.
12430 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12431                                          std::vector<Constant*> &Mask,
12432                                          LLVMContext *Context) {
12433   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12434          "Invalid CollectSingleShuffleElements");
12435   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12436
12437   if (isa<UndefValue>(V)) {
12438     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12439     return true;
12440   } else if (V == LHS) {
12441     for (unsigned i = 0; i != NumElts; ++i)
12442       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12443     return true;
12444   } else if (V == RHS) {
12445     for (unsigned i = 0; i != NumElts; ++i)
12446       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12447     return true;
12448   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12449     // If this is an insert of an extract from some other vector, include it.
12450     Value *VecOp    = IEI->getOperand(0);
12451     Value *ScalarOp = IEI->getOperand(1);
12452     Value *IdxOp    = IEI->getOperand(2);
12453     
12454     if (!isa<ConstantInt>(IdxOp))
12455       return false;
12456     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12457     
12458     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12459       // Okay, we can handle this if the vector we are insertinting into is
12460       // transitively ok.
12461       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12462         // If so, update the mask to reflect the inserted undef.
12463         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12464         return true;
12465       }      
12466     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12467       if (isa<ConstantInt>(EI->getOperand(1)) &&
12468           EI->getOperand(0)->getType() == V->getType()) {
12469         unsigned ExtractedIdx =
12470           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12471         
12472         // This must be extracting from either LHS or RHS.
12473         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12474           // Okay, we can handle this if the vector we are insertinting into is
12475           // transitively ok.
12476           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12477             // If so, update the mask to reflect the inserted value.
12478             if (EI->getOperand(0) == LHS) {
12479               Mask[InsertedIdx % NumElts] = 
12480                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12481             } else {
12482               assert(EI->getOperand(0) == RHS);
12483               Mask[InsertedIdx % NumElts] = 
12484                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12485               
12486             }
12487             return true;
12488           }
12489         }
12490       }
12491     }
12492   }
12493   // TODO: Handle shufflevector here!
12494   
12495   return false;
12496 }
12497
12498 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12499 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12500 /// that computes V and the LHS value of the shuffle.
12501 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12502                                      Value *&RHS, LLVMContext *Context) {
12503   assert(isa<VectorType>(V->getType()) && 
12504          (RHS == 0 || V->getType() == RHS->getType()) &&
12505          "Invalid shuffle!");
12506   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12507
12508   if (isa<UndefValue>(V)) {
12509     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12510     return V;
12511   } else if (isa<ConstantAggregateZero>(V)) {
12512     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12513     return V;
12514   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12515     // If this is an insert of an extract from some other vector, include it.
12516     Value *VecOp    = IEI->getOperand(0);
12517     Value *ScalarOp = IEI->getOperand(1);
12518     Value *IdxOp    = IEI->getOperand(2);
12519     
12520     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12521       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12522           EI->getOperand(0)->getType() == V->getType()) {
12523         unsigned ExtractedIdx =
12524           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12525         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12526         
12527         // Either the extracted from or inserted into vector must be RHSVec,
12528         // otherwise we'd end up with a shuffle of three inputs.
12529         if (EI->getOperand(0) == RHS || RHS == 0) {
12530           RHS = EI->getOperand(0);
12531           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12532           Mask[InsertedIdx % NumElts] = 
12533             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12534           return V;
12535         }
12536         
12537         if (VecOp == RHS) {
12538           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12539                                             RHS, Context);
12540           // Everything but the extracted element is replaced with the RHS.
12541           for (unsigned i = 0; i != NumElts; ++i) {
12542             if (i != InsertedIdx)
12543               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12544           }
12545           return V;
12546         }
12547         
12548         // If this insertelement is a chain that comes from exactly these two
12549         // vectors, return the vector and the effective shuffle.
12550         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12551                                          Context))
12552           return EI->getOperand(0);
12553         
12554       }
12555     }
12556   }
12557   // TODO: Handle shufflevector here!
12558   
12559   // Otherwise, can't do anything fancy.  Return an identity vector.
12560   for (unsigned i = 0; i != NumElts; ++i)
12561     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12562   return V;
12563 }
12564
12565 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12566   Value *VecOp    = IE.getOperand(0);
12567   Value *ScalarOp = IE.getOperand(1);
12568   Value *IdxOp    = IE.getOperand(2);
12569   
12570   // Inserting an undef or into an undefined place, remove this.
12571   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12572     ReplaceInstUsesWith(IE, VecOp);
12573   
12574   // If the inserted element was extracted from some other vector, and if the 
12575   // indexes are constant, try to turn this into a shufflevector operation.
12576   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12577     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12578         EI->getOperand(0)->getType() == IE.getType()) {
12579       unsigned NumVectorElts = IE.getType()->getNumElements();
12580       unsigned ExtractedIdx =
12581         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12582       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12583       
12584       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12585         return ReplaceInstUsesWith(IE, VecOp);
12586       
12587       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12588         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12589       
12590       // If we are extracting a value from a vector, then inserting it right
12591       // back into the same place, just use the input vector.
12592       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12593         return ReplaceInstUsesWith(IE, VecOp);      
12594       
12595       // If this insertelement isn't used by some other insertelement, turn it
12596       // (and any insertelements it points to), into one big shuffle.
12597       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12598         std::vector<Constant*> Mask;
12599         Value *RHS = 0;
12600         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12601         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12602         // We now have a shuffle of LHS, RHS, Mask.
12603         return new ShuffleVectorInst(LHS, RHS,
12604                                      ConstantVector::get(Mask));
12605       }
12606     }
12607   }
12608
12609   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12610   APInt UndefElts(VWidth, 0);
12611   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12612   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12613     return &IE;
12614
12615   return 0;
12616 }
12617
12618
12619 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12620   Value *LHS = SVI.getOperand(0);
12621   Value *RHS = SVI.getOperand(1);
12622   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12623
12624   bool MadeChange = false;
12625
12626   // Undefined shuffle mask -> undefined value.
12627   if (isa<UndefValue>(SVI.getOperand(2)))
12628     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12629
12630   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12631
12632   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12633     return 0;
12634
12635   APInt UndefElts(VWidth, 0);
12636   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12637   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12638     LHS = SVI.getOperand(0);
12639     RHS = SVI.getOperand(1);
12640     MadeChange = true;
12641   }
12642   
12643   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12644   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12645   if (LHS == RHS || isa<UndefValue>(LHS)) {
12646     if (isa<UndefValue>(LHS) && LHS == RHS) {
12647       // shuffle(undef,undef,mask) -> undef.
12648       return ReplaceInstUsesWith(SVI, LHS);
12649     }
12650     
12651     // Remap any references to RHS to use LHS.
12652     std::vector<Constant*> Elts;
12653     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12654       if (Mask[i] >= 2*e)
12655         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12656       else {
12657         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12658             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12659           Mask[i] = 2*e;     // Turn into undef.
12660           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12661         } else {
12662           Mask[i] = Mask[i] % e;  // Force to LHS.
12663           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12664         }
12665       }
12666     }
12667     SVI.setOperand(0, SVI.getOperand(1));
12668     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12669     SVI.setOperand(2, ConstantVector::get(Elts));
12670     LHS = SVI.getOperand(0);
12671     RHS = SVI.getOperand(1);
12672     MadeChange = true;
12673   }
12674   
12675   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12676   bool isLHSID = true, isRHSID = true;
12677     
12678   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12679     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12680     // Is this an identity shuffle of the LHS value?
12681     isLHSID &= (Mask[i] == i);
12682       
12683     // Is this an identity shuffle of the RHS value?
12684     isRHSID &= (Mask[i]-e == i);
12685   }
12686
12687   // Eliminate identity shuffles.
12688   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12689   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12690   
12691   // If the LHS is a shufflevector itself, see if we can combine it with this
12692   // one without producing an unusual shuffle.  Here we are really conservative:
12693   // we are absolutely afraid of producing a shuffle mask not in the input
12694   // program, because the code gen may not be smart enough to turn a merged
12695   // shuffle into two specific shuffles: it may produce worse code.  As such,
12696   // we only merge two shuffles if the result is one of the two input shuffle
12697   // masks.  In this case, merging the shuffles just removes one instruction,
12698   // which we know is safe.  This is good for things like turning:
12699   // (splat(splat)) -> splat.
12700   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12701     if (isa<UndefValue>(RHS)) {
12702       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12703
12704       std::vector<unsigned> NewMask;
12705       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12706         if (Mask[i] >= 2*e)
12707           NewMask.push_back(2*e);
12708         else
12709           NewMask.push_back(LHSMask[Mask[i]]);
12710       
12711       // If the result mask is equal to the src shuffle or this shuffle mask, do
12712       // the replacement.
12713       if (NewMask == LHSMask || NewMask == Mask) {
12714         unsigned LHSInNElts =
12715           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12716         std::vector<Constant*> Elts;
12717         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12718           if (NewMask[i] >= LHSInNElts*2) {
12719             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12720           } else {
12721             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12722           }
12723         }
12724         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12725                                      LHSSVI->getOperand(1),
12726                                      ConstantVector::get(Elts));
12727       }
12728     }
12729   }
12730
12731   return MadeChange ? &SVI : 0;
12732 }
12733
12734
12735
12736
12737 /// TryToSinkInstruction - Try to move the specified instruction from its
12738 /// current block into the beginning of DestBlock, which can only happen if it's
12739 /// safe to move the instruction past all of the instructions between it and the
12740 /// end of its block.
12741 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12742   assert(I->hasOneUse() && "Invariants didn't hold!");
12743
12744   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12745   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12746     return false;
12747
12748   // Do not sink alloca instructions out of the entry block.
12749   if (isa<AllocaInst>(I) && I->getParent() ==
12750         &DestBlock->getParent()->getEntryBlock())
12751     return false;
12752
12753   // We can only sink load instructions if there is nothing between the load and
12754   // the end of block that could change the value.
12755   if (I->mayReadFromMemory()) {
12756     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12757          Scan != E; ++Scan)
12758       if (Scan->mayWriteToMemory())
12759         return false;
12760   }
12761
12762   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12763
12764   CopyPrecedingStopPoint(I, InsertPos);
12765   I->moveBefore(InsertPos);
12766   ++NumSunkInst;
12767   return true;
12768 }
12769
12770
12771 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12772 /// all reachable code to the worklist.
12773 ///
12774 /// This has a couple of tricks to make the code faster and more powerful.  In
12775 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12776 /// them to the worklist (this significantly speeds up instcombine on code where
12777 /// many instructions are dead or constant).  Additionally, if we find a branch
12778 /// whose condition is a known constant, we only visit the reachable successors.
12779 ///
12780 static bool AddReachableCodeToWorklist(BasicBlock *BB, 
12781                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12782                                        InstCombiner &IC,
12783                                        const TargetData *TD) {
12784   bool MadeIRChange = false;
12785   SmallVector<BasicBlock*, 256> Worklist;
12786   Worklist.push_back(BB);
12787   
12788   std::vector<Instruction*> InstrsForInstCombineWorklist;
12789   InstrsForInstCombineWorklist.reserve(128);
12790
12791   SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
12792   
12793   while (!Worklist.empty()) {
12794     BB = Worklist.back();
12795     Worklist.pop_back();
12796     
12797     // We have now visited this block!  If we've already been here, ignore it.
12798     if (!Visited.insert(BB)) continue;
12799
12800     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12801       Instruction *Inst = BBI++;
12802       
12803       // DCE instruction if trivially dead.
12804       if (isInstructionTriviallyDead(Inst)) {
12805         ++NumDeadInst;
12806         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12807         Inst->eraseFromParent();
12808         continue;
12809       }
12810       
12811       // ConstantProp instruction if trivially constant.
12812       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
12813         if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12814           DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12815                        << *Inst << '\n');
12816           Inst->replaceAllUsesWith(C);
12817           ++NumConstProp;
12818           Inst->eraseFromParent();
12819           continue;
12820         }
12821       
12822       
12823       
12824       if (TD) {
12825         // See if we can constant fold its operands.
12826         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
12827              i != e; ++i) {
12828           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
12829           if (CE == 0) continue;
12830           
12831           // If we already folded this constant, don't try again.
12832           if (!FoldedConstants.insert(CE))
12833             continue;
12834           
12835           Constant *NewC = ConstantFoldConstantExpression(CE, TD);
12836           if (NewC && NewC != CE) {
12837             *i = NewC;
12838             MadeIRChange = true;
12839           }
12840         }
12841       }
12842       
12843
12844       InstrsForInstCombineWorklist.push_back(Inst);
12845     }
12846
12847     // Recursively visit successors.  If this is a branch or switch on a
12848     // constant, only visit the reachable successor.
12849     TerminatorInst *TI = BB->getTerminator();
12850     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12851       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12852         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12853         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12854         Worklist.push_back(ReachableBB);
12855         continue;
12856       }
12857     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12858       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12859         // See if this is an explicit destination.
12860         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12861           if (SI->getCaseValue(i) == Cond) {
12862             BasicBlock *ReachableBB = SI->getSuccessor(i);
12863             Worklist.push_back(ReachableBB);
12864             continue;
12865           }
12866         
12867         // Otherwise it is the default destination.
12868         Worklist.push_back(SI->getSuccessor(0));
12869         continue;
12870       }
12871     }
12872     
12873     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12874       Worklist.push_back(TI->getSuccessor(i));
12875   }
12876   
12877   // Once we've found all of the instructions to add to instcombine's worklist,
12878   // add them in reverse order.  This way instcombine will visit from the top
12879   // of the function down.  This jives well with the way that it adds all uses
12880   // of instructions to the worklist after doing a transformation, thus avoiding
12881   // some N^2 behavior in pathological cases.
12882   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12883                               InstrsForInstCombineWorklist.size());
12884   
12885   return MadeIRChange;
12886 }
12887
12888 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12889   MadeIRChange = false;
12890   
12891   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12892         << F.getNameStr() << "\n");
12893
12894   {
12895     // Do a depth-first traversal of the function, populate the worklist with
12896     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12897     // track of which blocks we visit.
12898     SmallPtrSet<BasicBlock*, 64> Visited;
12899     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12900
12901     // Do a quick scan over the function.  If we find any blocks that are
12902     // unreachable, remove any instructions inside of them.  This prevents
12903     // the instcombine code from having to deal with some bad special cases.
12904     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12905       if (!Visited.count(BB)) {
12906         Instruction *Term = BB->getTerminator();
12907         while (Term != BB->begin()) {   // Remove instrs bottom-up
12908           BasicBlock::iterator I = Term; --I;
12909
12910           DEBUG(errs() << "IC: DCE: " << *I << '\n');
12911           // A debug intrinsic shouldn't force another iteration if we weren't
12912           // going to do one without it.
12913           if (!isa<DbgInfoIntrinsic>(I)) {
12914             ++NumDeadInst;
12915             MadeIRChange = true;
12916           }
12917
12918           // If I is not void type then replaceAllUsesWith undef.
12919           // This allows ValueHandlers and custom metadata to adjust itself.
12920           if (!I->getType()->isVoidTy())
12921             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12922           I->eraseFromParent();
12923         }
12924       }
12925   }
12926
12927   while (!Worklist.isEmpty()) {
12928     Instruction *I = Worklist.RemoveOne();
12929     if (I == 0) continue;  // skip null values.
12930
12931     // Check to see if we can DCE the instruction.
12932     if (isInstructionTriviallyDead(I)) {
12933       DEBUG(errs() << "IC: DCE: " << *I << '\n');
12934       EraseInstFromFunction(*I);
12935       ++NumDeadInst;
12936       MadeIRChange = true;
12937       continue;
12938     }
12939
12940     // Instruction isn't dead, see if we can constant propagate it.
12941     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
12942       if (Constant *C = ConstantFoldInstruction(I, TD)) {
12943         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12944
12945         // Add operands to the worklist.
12946         ReplaceInstUsesWith(*I, C);
12947         ++NumConstProp;
12948         EraseInstFromFunction(*I);
12949         MadeIRChange = true;
12950         continue;
12951       }
12952
12953     // See if we can trivially sink this instruction to a successor basic block.
12954     if (I->hasOneUse()) {
12955       BasicBlock *BB = I->getParent();
12956       Instruction *UserInst = cast<Instruction>(I->use_back());
12957       BasicBlock *UserParent;
12958       
12959       // Get the block the use occurs in.
12960       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
12961         UserParent = PN->getIncomingBlock(I->use_begin().getUse());
12962       else
12963         UserParent = UserInst->getParent();
12964       
12965       if (UserParent != BB) {
12966         bool UserIsSuccessor = false;
12967         // See if the user is one of our successors.
12968         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12969           if (*SI == UserParent) {
12970             UserIsSuccessor = true;
12971             break;
12972           }
12973
12974         // If the user is one of our immediate successors, and if that successor
12975         // only has us as a predecessors (we'd have to split the critical edge
12976         // otherwise), we can keep going.
12977         if (UserIsSuccessor && UserParent->getSinglePredecessor())
12978           // Okay, the CFG is simple enough, try to sink this instruction.
12979           MadeIRChange |= TryToSinkInstruction(I, UserParent);
12980       }
12981     }
12982
12983     // Now that we have an instruction, try combining it to simplify it.
12984     Builder->SetInsertPoint(I->getParent(), I);
12985     
12986 #ifndef NDEBUG
12987     std::string OrigI;
12988 #endif
12989     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12990     DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12991
12992     if (Instruction *Result = visit(*I)) {
12993       ++NumCombined;
12994       // Should we replace the old instruction with a new one?
12995       if (Result != I) {
12996         DEBUG(errs() << "IC: Old = " << *I << '\n'
12997                      << "    New = " << *Result << '\n');
12998
12999         // Everything uses the new instruction now.
13000         I->replaceAllUsesWith(Result);
13001
13002         // Push the new instruction and any users onto the worklist.
13003         Worklist.Add(Result);
13004         Worklist.AddUsersToWorkList(*Result);
13005
13006         // Move the name to the new instruction first.
13007         Result->takeName(I);
13008
13009         // Insert the new instruction into the basic block...
13010         BasicBlock *InstParent = I->getParent();
13011         BasicBlock::iterator InsertPos = I;
13012
13013         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13014           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13015             ++InsertPos;
13016
13017         InstParent->getInstList().insert(InsertPos, Result);
13018
13019         EraseInstFromFunction(*I);
13020       } else {
13021 #ifndef NDEBUG
13022         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13023                      << "    New = " << *I << '\n');
13024 #endif
13025
13026         // If the instruction was modified, it's possible that it is now dead.
13027         // if so, remove it.
13028         if (isInstructionTriviallyDead(I)) {
13029           EraseInstFromFunction(*I);
13030         } else {
13031           Worklist.Add(I);
13032           Worklist.AddUsersToWorkList(*I);
13033         }
13034       }
13035       MadeIRChange = true;
13036     }
13037   }
13038
13039   Worklist.Zap();
13040   return MadeIRChange;
13041 }
13042
13043
13044 bool InstCombiner::runOnFunction(Function &F) {
13045   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13046   Context = &F.getContext();
13047   TD = getAnalysisIfAvailable<TargetData>();
13048
13049   
13050   /// Builder - This is an IRBuilder that automatically inserts new
13051   /// instructions into the worklist when they are created.
13052   IRBuilder<true, TargetFolder, InstCombineIRInserter> 
13053     TheBuilder(F.getContext(), TargetFolder(TD),
13054                InstCombineIRInserter(Worklist));
13055   Builder = &TheBuilder;
13056   
13057   bool EverMadeChange = false;
13058
13059   // Iterate while there is work to do.
13060   unsigned Iteration = 0;
13061   while (DoOneIteration(F, Iteration++))
13062     EverMadeChange = true;
13063   
13064   Builder = 0;
13065   return EverMadeChange;
13066 }
13067
13068 FunctionPass *llvm::createInstructionCombiningPass() {
13069   return new InstCombiner();
13070 }