add testcases for the foo_with_overflow op xforms added recently and
[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/InstructionSimplify.h"
46 #include "llvm/Analysis/MemoryBuiltins.h"
47 #include "llvm/Analysis/ValueTracking.h"
48 #include "llvm/Target/TargetData.h"
49 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
50 #include "llvm/Transforms/Utils/Local.h"
51 #include "llvm/Support/CallSite.h"
52 #include "llvm/Support/ConstantRange.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/GetElementPtrTypeIterator.h"
56 #include "llvm/Support/InstVisitor.h"
57 #include "llvm/Support/IRBuilder.h"
58 #include "llvm/Support/MathExtras.h"
59 #include "llvm/Support/PatternMatch.h"
60 #include "llvm/Support/TargetFolder.h"
61 #include "llvm/Support/raw_ostream.h"
62 #include "llvm/ADT/DenseMap.h"
63 #include "llvm/ADT/SmallVector.h"
64 #include "llvm/ADT/SmallPtrSet.h"
65 #include "llvm/ADT/Statistic.h"
66 #include "llvm/ADT/STLExtras.h"
67 #include <algorithm>
68 #include <climits>
69 using namespace llvm;
70 using namespace llvm::PatternMatch;
71
72 STATISTIC(NumCombined , "Number of insts combined");
73 STATISTIC(NumConstProp, "Number of constant folds");
74 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
75 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
76 STATISTIC(NumSunkInst , "Number of instructions sunk");
77
78 namespace {
79   /// InstCombineWorklist - This is the worklist management logic for
80   /// InstCombine.
81   class InstCombineWorklist {
82     SmallVector<Instruction*, 256> Worklist;
83     DenseMap<Instruction*, unsigned> WorklistMap;
84     
85     void operator=(const InstCombineWorklist&RHS);   // DO NOT IMPLEMENT
86     InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
87   public:
88     InstCombineWorklist() {}
89     
90     bool isEmpty() const { return Worklist.empty(); }
91     
92     /// Add - Add the specified instruction to the worklist if it isn't already
93     /// in it.
94     void Add(Instruction *I) {
95       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
96         DEBUG(errs() << "IC: ADD: " << *I << '\n');
97         Worklist.push_back(I);
98       }
99     }
100     
101     void AddValue(Value *V) {
102       if (Instruction *I = dyn_cast<Instruction>(V))
103         Add(I);
104     }
105     
106     /// AddInitialGroup - Add the specified batch of stuff in reverse order.
107     /// which should only be done when the worklist is empty and when the group
108     /// has no duplicates.
109     void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
110       assert(Worklist.empty() && "Worklist must be empty to add initial group");
111       Worklist.reserve(NumEntries+16);
112       DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
113       for (; NumEntries; --NumEntries) {
114         Instruction *I = List[NumEntries-1];
115         WorklistMap.insert(std::make_pair(I, Worklist.size()));
116         Worklist.push_back(I);
117       }
118     }
119     
120     // Remove - remove I from the worklist if it exists.
121     void Remove(Instruction *I) {
122       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
123       if (It == WorklistMap.end()) return; // Not in worklist.
124       
125       // Don't bother moving everything down, just null out the slot.
126       Worklist[It->second] = 0;
127       
128       WorklistMap.erase(It);
129     }
130     
131     Instruction *RemoveOne() {
132       Instruction *I = Worklist.back();
133       Worklist.pop_back();
134       WorklistMap.erase(I);
135       return I;
136     }
137
138     /// AddUsersToWorkList - When an instruction is simplified, add all users of
139     /// the instruction to the work lists because they might get more simplified
140     /// now.
141     ///
142     void AddUsersToWorkList(Instruction &I) {
143       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
144            UI != UE; ++UI)
145         Add(cast<Instruction>(*UI));
146     }
147     
148     
149     /// Zap - check that the worklist is empty and nuke the backing store for
150     /// the map if it is large.
151     void Zap() {
152       assert(WorklistMap.empty() && "Worklist empty, but map not?");
153       
154       // Do an explicit clear, this shrinks the map if needed.
155       WorklistMap.clear();
156     }
157   };
158 } // end anonymous namespace.
159
160
161 namespace {
162   /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
163   /// just like the normal insertion helper, but also adds any new instructions
164   /// to the instcombine worklist.
165   class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
166     InstCombineWorklist &Worklist;
167   public:
168     InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
169     
170     void InsertHelper(Instruction *I, const Twine &Name,
171                       BasicBlock *BB, BasicBlock::iterator InsertPt) const {
172       IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
173       Worklist.Add(I);
174     }
175   };
176 } // end anonymous namespace
177
178
179 namespace {
180   class InstCombiner : public FunctionPass,
181                        public InstVisitor<InstCombiner, Instruction*> {
182     TargetData *TD;
183     bool MustPreserveLCSSA;
184     bool MadeIRChange;
185   public:
186     /// Worklist - All of the instructions that need to be simplified.
187     InstCombineWorklist Worklist;
188
189     /// Builder - This is an IRBuilder that automatically inserts new
190     /// instructions into the worklist when they are created.
191     typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
192     BuilderTy *Builder;
193         
194     static char ID; // Pass identification, replacement for typeid
195     InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
196
197     LLVMContext *Context;
198     LLVMContext *getContext() const { return Context; }
199
200   public:
201     virtual bool runOnFunction(Function &F);
202     
203     bool DoOneIteration(Function &F, unsigned ItNum);
204
205     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
206       AU.addPreservedID(LCSSAID);
207       AU.setPreservesCFG();
208     }
209
210     TargetData *getTargetData() const { return TD; }
211
212     // Visitation implementation - Implement instruction combining for different
213     // instruction types.  The semantics are as follows:
214     // Return Value:
215     //    null        - No change was made
216     //     I          - Change was made, I is still valid, I may be dead though
217     //   otherwise    - Change was made, replace I with returned instruction
218     //
219     Instruction *visitAdd(BinaryOperator &I);
220     Instruction *visitFAdd(BinaryOperator &I);
221     Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
222     Instruction *visitSub(BinaryOperator &I);
223     Instruction *visitFSub(BinaryOperator &I);
224     Instruction *visitMul(BinaryOperator &I);
225     Instruction *visitFMul(BinaryOperator &I);
226     Instruction *visitURem(BinaryOperator &I);
227     Instruction *visitSRem(BinaryOperator &I);
228     Instruction *visitFRem(BinaryOperator &I);
229     bool SimplifyDivRemOfSelect(BinaryOperator &I);
230     Instruction *commonRemTransforms(BinaryOperator &I);
231     Instruction *commonIRemTransforms(BinaryOperator &I);
232     Instruction *commonDivTransforms(BinaryOperator &I);
233     Instruction *commonIDivTransforms(BinaryOperator &I);
234     Instruction *visitUDiv(BinaryOperator &I);
235     Instruction *visitSDiv(BinaryOperator &I);
236     Instruction *visitFDiv(BinaryOperator &I);
237     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
238     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
239     Instruction *visitAnd(BinaryOperator &I);
240     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
241     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
242     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
243                                      Value *A, Value *B, Value *C);
244     Instruction *visitOr (BinaryOperator &I);
245     Instruction *visitXor(BinaryOperator &I);
246     Instruction *visitShl(BinaryOperator &I);
247     Instruction *visitAShr(BinaryOperator &I);
248     Instruction *visitLShr(BinaryOperator &I);
249     Instruction *commonShiftTransforms(BinaryOperator &I);
250     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
251                                       Constant *RHSC);
252     Instruction *visitFCmpInst(FCmpInst &I);
253     Instruction *visitICmpInst(ICmpInst &I);
254     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
255     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
256                                                 Instruction *LHS,
257                                                 ConstantInt *RHS);
258     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
259                                 ConstantInt *DivRHS);
260
261     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
262                              ICmpInst::Predicate Cond, Instruction &I);
263     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
264                                      BinaryOperator &I);
265     Instruction *commonCastTransforms(CastInst &CI);
266     Instruction *commonIntCastTransforms(CastInst &CI);
267     Instruction *commonPointerCastTransforms(CastInst &CI);
268     Instruction *visitTrunc(TruncInst &CI);
269     Instruction *visitZExt(ZExtInst &CI);
270     Instruction *visitSExt(SExtInst &CI);
271     Instruction *visitFPTrunc(FPTruncInst &CI);
272     Instruction *visitFPExt(CastInst &CI);
273     Instruction *visitFPToUI(FPToUIInst &FI);
274     Instruction *visitFPToSI(FPToSIInst &FI);
275     Instruction *visitUIToFP(CastInst &CI);
276     Instruction *visitSIToFP(CastInst &CI);
277     Instruction *visitPtrToInt(PtrToIntInst &CI);
278     Instruction *visitIntToPtr(IntToPtrInst &CI);
279     Instruction *visitBitCast(BitCastInst &CI);
280     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
281                                 Instruction *FI);
282     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
283     Instruction *visitSelectInst(SelectInst &SI);
284     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
285     Instruction *visitCallInst(CallInst &CI);
286     Instruction *visitInvokeInst(InvokeInst &II);
287
288     Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
289     Instruction *visitPHINode(PHINode &PN);
290     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
291     Instruction *visitAllocaInst(AllocaInst &AI);
292     Instruction *visitFree(Instruction &FI);
293     Instruction *visitLoadInst(LoadInst &LI);
294     Instruction *visitStoreInst(StoreInst &SI);
295     Instruction *visitBranchInst(BranchInst &BI);
296     Instruction *visitSwitchInst(SwitchInst &SI);
297     Instruction *visitInsertElementInst(InsertElementInst &IE);
298     Instruction *visitExtractElementInst(ExtractElementInst &EI);
299     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
300     Instruction *visitExtractValueInst(ExtractValueInst &EV);
301
302     // visitInstruction - Specify what to return for unhandled instructions...
303     Instruction *visitInstruction(Instruction &I) { return 0; }
304
305   private:
306     Instruction *visitCallSite(CallSite CS);
307     bool transformConstExprCastCall(CallSite CS);
308     Instruction *transformCallThroughTrampoline(CallSite CS);
309     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
310                                    bool DoXform = true);
311     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
312     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
313
314
315   public:
316     // InsertNewInstBefore - insert an instruction New before instruction Old
317     // in the program.  Add the new instruction to the worklist.
318     //
319     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
320       assert(New && New->getParent() == 0 &&
321              "New instruction already inserted into a basic block!");
322       BasicBlock *BB = Old.getParent();
323       BB->getInstList().insert(&Old, New);  // Insert inst
324       Worklist.Add(New);
325       return New;
326     }
327         
328     // ReplaceInstUsesWith - This method is to be used when an instruction is
329     // found to be dead, replacable with another preexisting expression.  Here
330     // we add all uses of I to the worklist, replace all uses of I with the new
331     // value, then return I, so that the inst combiner will know that I was
332     // modified.
333     //
334     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
335       Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
336       
337       // If we are replacing the instruction with itself, this must be in a
338       // segment of unreachable code, so just clobber the instruction.
339       if (&I == V) 
340         V = UndefValue::get(I.getType());
341         
342       I.replaceAllUsesWith(V);
343       return &I;
344     }
345
346     // EraseInstFromFunction - When dealing with an instruction that has side
347     // effects or produces a void value, we can't rely on DCE to delete the
348     // instruction.  Instead, visit methods should return the value returned by
349     // this function.
350     Instruction *EraseInstFromFunction(Instruction &I) {
351       DEBUG(errs() << "IC: ERASE " << I << '\n');
352
353       assert(I.use_empty() && "Cannot erase instruction that is used!");
354       // Make sure that we reprocess all operands now that we reduced their
355       // use counts.
356       if (I.getNumOperands() < 8) {
357         for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
358           if (Instruction *Op = dyn_cast<Instruction>(*i))
359             Worklist.Add(Op);
360       }
361       Worklist.Remove(&I);
362       I.eraseFromParent();
363       MadeIRChange = true;
364       return 0;  // Don't do anything with FI
365     }
366         
367     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
368                            APInt &KnownOne, unsigned Depth = 0) const {
369       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
370     }
371     
372     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
373                            unsigned Depth = 0) const {
374       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
375     }
376     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
377       return llvm::ComputeNumSignBits(Op, TD, Depth);
378     }
379
380   private:
381
382     /// SimplifyCommutative - This performs a few simplifications for 
383     /// commutative operators.
384     bool SimplifyCommutative(BinaryOperator &I);
385
386     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
387     /// based on the demanded bits.
388     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
389                                    APInt& KnownZero, APInt& KnownOne,
390                                    unsigned Depth);
391     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
392                               APInt& KnownZero, APInt& KnownOne,
393                               unsigned Depth=0);
394         
395     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
396     /// SimplifyDemandedBits knows about.  See if the instruction has any
397     /// properties that allow us to simplify its operands.
398     bool SimplifyDemandedInstructionBits(Instruction &Inst);
399         
400     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
401                                       APInt& UndefElts, unsigned Depth = 0);
402       
403     // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
404     // which has a PHI node as operand #0, see if we can fold the instruction
405     // into the PHI (which is only possible if all operands to the PHI are
406     // constants).
407     //
408     // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
409     // that would normally be unprofitable because they strongly encourage jump
410     // threading.
411     Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
412
413     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
414     // operator and they all are only used by the PHI, PHI together their
415     // inputs, and do the operation once, to the result of the PHI.
416     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
417     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
418     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
419     Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
420
421     
422     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
423                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
424     
425     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
426                               bool isSub, Instruction &I);
427     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
428                                  bool isSigned, bool Inside, Instruction &IB);
429     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
430     Instruction *MatchBSwap(BinaryOperator &I);
431     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
432     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
433     Instruction *SimplifyMemSet(MemSetInst *MI);
434
435
436     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
437
438     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
439                                     unsigned CastOpc, int &NumCastsRemoved);
440     unsigned GetOrEnforceKnownAlignment(Value *V,
441                                         unsigned PrefAlign = 0);
442
443   };
444 } // end anonymous namespace
445
446 char InstCombiner::ID = 0;
447 static RegisterPass<InstCombiner>
448 X("instcombine", "Combine redundant instructions");
449
450 // getComplexity:  Assign a complexity or rank value to LLVM Values...
451 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
452 static unsigned getComplexity(Value *V) {
453   if (isa<Instruction>(V)) {
454     if (BinaryOperator::isNeg(V) ||
455         BinaryOperator::isFNeg(V) ||
456         BinaryOperator::isNot(V))
457       return 3;
458     return 4;
459   }
460   if (isa<Argument>(V)) return 3;
461   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
462 }
463
464 // isOnlyUse - Return true if this instruction will be deleted if we stop using
465 // it.
466 static bool isOnlyUse(Value *V) {
467   return V->hasOneUse() || isa<Constant>(V);
468 }
469
470 // getPromotedType - Return the specified type promoted as it would be to pass
471 // though a va_arg area...
472 static const Type *getPromotedType(const Type *Ty) {
473   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
474     if (ITy->getBitWidth() < 32)
475       return Type::getInt32Ty(Ty->getContext());
476   }
477   return Ty;
478 }
479
480 /// ShouldChangeType - Return true if it is desirable to convert a computation
481 /// from 'From' to 'To'.  We don't want to convert from a legal to an illegal
482 /// type for example, or from a smaller to a larger illegal type.
483 static bool ShouldChangeType(const Type *From, const Type *To,
484                              const TargetData *TD) {
485   assert(isa<IntegerType>(From) && isa<IntegerType>(To));
486   
487   // If we don't have TD, we don't know if the source/dest are legal.
488   if (!TD) return false;
489   
490   unsigned FromWidth = From->getPrimitiveSizeInBits();
491   unsigned ToWidth = To->getPrimitiveSizeInBits();
492   bool FromLegal = TD->isLegalInteger(FromWidth);
493   bool ToLegal = TD->isLegalInteger(ToWidth);
494   
495   // If this is a legal integer from type, and the result would be an illegal
496   // type, don't do the transformation.
497   if (FromLegal && !ToLegal)
498     return false;
499   
500   // Otherwise, if both are illegal, do not increase the size of the result. We
501   // do allow things like i160 -> i64, but not i64 -> i160.
502   if (!FromLegal && !ToLegal && ToWidth > FromWidth)
503     return false;
504   
505   return true;
506 }
507
508 /// getBitCastOperand - If the specified operand is a CastInst, a constant
509 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
510 /// operand value, otherwise return null.
511 static Value *getBitCastOperand(Value *V) {
512   if (Operator *O = dyn_cast<Operator>(V)) {
513     if (O->getOpcode() == Instruction::BitCast)
514       return O->getOperand(0);
515     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
516       if (GEP->hasAllZeroIndices())
517         return GEP->getPointerOperand();
518   }
519   return 0;
520 }
521
522 /// This function is a wrapper around CastInst::isEliminableCastPair. It
523 /// simply extracts arguments and returns what that function returns.
524 static Instruction::CastOps 
525 isEliminableCastPair(
526   const CastInst *CI, ///< The first cast instruction
527   unsigned opcode,       ///< The opcode of the second cast instruction
528   const Type *DstTy,     ///< The target type for the second cast instruction
529   TargetData *TD         ///< The target data for pointer size
530 ) {
531
532   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
533   const Type *MidTy = CI->getType();                  // B from above
534
535   // Get the opcodes of the two Cast instructions
536   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
537   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
538
539   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
540                                                 DstTy,
541                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
542   
543   // We don't want to form an inttoptr or ptrtoint that converts to an integer
544   // type that differs from the pointer size.
545   if ((Res == Instruction::IntToPtr &&
546           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
547       (Res == Instruction::PtrToInt &&
548           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
549     Res = 0;
550   
551   return Instruction::CastOps(Res);
552 }
553
554 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
555 /// in any code being generated.  It does not require codegen if V is simple
556 /// enough or if the cast can be folded into other casts.
557 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
558                               const Type *Ty, TargetData *TD) {
559   if (V->getType() == Ty || isa<Constant>(V)) return false;
560   
561   // If this is another cast that can be eliminated, it isn't codegen either.
562   if (const CastInst *CI = dyn_cast<CastInst>(V))
563     if (isEliminableCastPair(CI, opcode, Ty, TD))
564       return false;
565   return true;
566 }
567
568 // SimplifyCommutative - This performs a few simplifications for commutative
569 // operators:
570 //
571 //  1. Order operands such that they are listed from right (least complex) to
572 //     left (most complex).  This puts constants before unary operators before
573 //     binary operators.
574 //
575 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
576 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
577 //
578 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
579   bool Changed = false;
580   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
581     Changed = !I.swapOperands();
582
583   if (!I.isAssociative()) return Changed;
584   Instruction::BinaryOps Opcode = I.getOpcode();
585   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
586     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
587       if (isa<Constant>(I.getOperand(1))) {
588         Constant *Folded = ConstantExpr::get(I.getOpcode(),
589                                              cast<Constant>(I.getOperand(1)),
590                                              cast<Constant>(Op->getOperand(1)));
591         I.setOperand(0, Op->getOperand(0));
592         I.setOperand(1, Folded);
593         return true;
594       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
595         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
596             isOnlyUse(Op) && isOnlyUse(Op1)) {
597           Constant *C1 = cast<Constant>(Op->getOperand(1));
598           Constant *C2 = cast<Constant>(Op1->getOperand(1));
599
600           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
601           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
602           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
603                                                     Op1->getOperand(0),
604                                                     Op1->getName(), &I);
605           Worklist.Add(New);
606           I.setOperand(0, New);
607           I.setOperand(1, Folded);
608           return true;
609         }
610     }
611   return Changed;
612 }
613
614 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
615 // if the LHS is a constant zero (which is the 'negate' form).
616 //
617 static inline Value *dyn_castNegVal(Value *V) {
618   if (BinaryOperator::isNeg(V))
619     return BinaryOperator::getNegArgument(V);
620
621   // Constants can be considered to be negated values if they can be folded.
622   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
623     return ConstantExpr::getNeg(C);
624
625   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
626     if (C->getType()->getElementType()->isInteger())
627       return ConstantExpr::getNeg(C);
628
629   return 0;
630 }
631
632 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
633 // instruction if the LHS is a constant negative zero (which is the 'negate'
634 // form).
635 //
636 static inline Value *dyn_castFNegVal(Value *V) {
637   if (BinaryOperator::isFNeg(V))
638     return BinaryOperator::getFNegArgument(V);
639
640   // Constants can be considered to be negated values if they can be folded.
641   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
642     return ConstantExpr::getFNeg(C);
643
644   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
645     if (C->getType()->getElementType()->isFloatingPoint())
646       return ConstantExpr::getFNeg(C);
647
648   return 0;
649 }
650
651 /// isFreeToInvert - Return true if the specified value is free to invert (apply
652 /// ~ to).  This happens in cases where the ~ can be eliminated.
653 static inline bool isFreeToInvert(Value *V) {
654   // ~(~(X)) -> X.
655   if (BinaryOperator::isNot(V))
656     return true;
657   
658   // Constants can be considered to be not'ed values.
659   if (isa<ConstantInt>(V))
660     return true;
661   
662   // Compares can be inverted if they have a single use.
663   if (CmpInst *CI = dyn_cast<CmpInst>(V))
664     return CI->hasOneUse();
665   
666   return false;
667 }
668
669 static inline Value *dyn_castNotVal(Value *V) {
670   // If this is not(not(x)) don't return that this is a not: we want the two
671   // not's to be folded first.
672   if (BinaryOperator::isNot(V)) {
673     Value *Operand = BinaryOperator::getNotArgument(V);
674     if (!isFreeToInvert(Operand))
675       return Operand;
676   }
677
678   // Constants can be considered to be not'ed values...
679   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
680     return ConstantInt::get(C->getType(), ~C->getValue());
681   return 0;
682 }
683
684
685
686 // dyn_castFoldableMul - If this value is a multiply that can be folded into
687 // other computations (because it has a constant operand), return the
688 // non-constant operand of the multiply, and set CST to point to the multiplier.
689 // Otherwise, return null.
690 //
691 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
692   if (V->hasOneUse() && V->getType()->isInteger())
693     if (Instruction *I = dyn_cast<Instruction>(V)) {
694       if (I->getOpcode() == Instruction::Mul)
695         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
696           return I->getOperand(0);
697       if (I->getOpcode() == Instruction::Shl)
698         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
699           // The multiplier is really 1 << CST.
700           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
701           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
702           CST = ConstantInt::get(V->getType()->getContext(),
703                                  APInt(BitWidth, 1).shl(CSTVal));
704           return I->getOperand(0);
705         }
706     }
707   return 0;
708 }
709
710 /// AddOne - Add one to a ConstantInt
711 static Constant *AddOne(Constant *C) {
712   return ConstantExpr::getAdd(C, 
713     ConstantInt::get(C->getType(), 1));
714 }
715 /// SubOne - Subtract one from a ConstantInt
716 static Constant *SubOne(ConstantInt *C) {
717   return ConstantExpr::getSub(C, 
718     ConstantInt::get(C->getType(), 1));
719 }
720 /// MultiplyOverflows - True if the multiply can not be expressed in an int
721 /// this size.
722 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
723   uint32_t W = C1->getBitWidth();
724   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
725   if (sign) {
726     LHSExt.sext(W * 2);
727     RHSExt.sext(W * 2);
728   } else {
729     LHSExt.zext(W * 2);
730     RHSExt.zext(W * 2);
731   }
732
733   APInt MulExt = LHSExt * RHSExt;
734
735   if (sign) {
736     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
737     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
738     return MulExt.slt(Min) || MulExt.sgt(Max);
739   } else 
740     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
741 }
742
743
744 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
745 /// specified instruction is a constant integer.  If so, check to see if there
746 /// are any bits set in the constant that are not demanded.  If so, shrink the
747 /// constant and return true.
748 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
749                                    APInt Demanded) {
750   assert(I && "No instruction?");
751   assert(OpNo < I->getNumOperands() && "Operand index too large");
752
753   // If the operand is not a constant integer, nothing to do.
754   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
755   if (!OpC) return false;
756
757   // If there are no bits set that aren't demanded, nothing to do.
758   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
759   if ((~Demanded & OpC->getValue()) == 0)
760     return false;
761
762   // This instruction is producing bits that are not demanded. Shrink the RHS.
763   Demanded &= OpC->getValue();
764   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
765   return true;
766 }
767
768 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
769 // set of known zero and one bits, compute the maximum and minimum values that
770 // could have the specified known zero and known one bits, returning them in
771 // min/max.
772 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
773                                                    const APInt& KnownOne,
774                                                    APInt& Min, APInt& Max) {
775   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
776          KnownZero.getBitWidth() == Min.getBitWidth() &&
777          KnownZero.getBitWidth() == Max.getBitWidth() &&
778          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
779   APInt UnknownBits = ~(KnownZero|KnownOne);
780
781   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
782   // bit if it is unknown.
783   Min = KnownOne;
784   Max = KnownOne|UnknownBits;
785   
786   if (UnknownBits.isNegative()) { // Sign bit is unknown
787     Min.set(Min.getBitWidth()-1);
788     Max.clear(Max.getBitWidth()-1);
789   }
790 }
791
792 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
793 // a set of known zero and one bits, compute the maximum and minimum values that
794 // could have the specified known zero and known one bits, returning them in
795 // min/max.
796 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
797                                                      const APInt &KnownOne,
798                                                      APInt &Min, APInt &Max) {
799   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
800          KnownZero.getBitWidth() == Min.getBitWidth() &&
801          KnownZero.getBitWidth() == Max.getBitWidth() &&
802          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
803   APInt UnknownBits = ~(KnownZero|KnownOne);
804   
805   // The minimum value is when the unknown bits are all zeros.
806   Min = KnownOne;
807   // The maximum value is when the unknown bits are all ones.
808   Max = KnownOne|UnknownBits;
809 }
810
811 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
812 /// SimplifyDemandedBits knows about.  See if the instruction has any
813 /// properties that allow us to simplify its operands.
814 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
815   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
816   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
817   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
818   
819   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
820                                      KnownZero, KnownOne, 0);
821   if (V == 0) return false;
822   if (V == &Inst) return true;
823   ReplaceInstUsesWith(Inst, V);
824   return true;
825 }
826
827 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
828 /// specified instruction operand if possible, updating it in place.  It returns
829 /// true if it made any change and false otherwise.
830 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
831                                         APInt &KnownZero, APInt &KnownOne,
832                                         unsigned Depth) {
833   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
834                                           KnownZero, KnownOne, Depth);
835   if (NewVal == 0) return false;
836   U = NewVal;
837   return true;
838 }
839
840
841 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
842 /// value based on the demanded bits.  When this function is called, it is known
843 /// that only the bits set in DemandedMask of the result of V are ever used
844 /// downstream. Consequently, depending on the mask and V, it may be possible
845 /// to replace V with a constant or one of its operands. In such cases, this
846 /// function does the replacement and returns true. In all other cases, it
847 /// returns false after analyzing the expression and setting KnownOne and known
848 /// to be one in the expression.  KnownZero contains all the bits that are known
849 /// to be zero in the expression. These are provided to potentially allow the
850 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
851 /// the expression. KnownOne and KnownZero always follow the invariant that 
852 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
853 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
854 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
855 /// and KnownOne must all be the same.
856 ///
857 /// This returns null if it did not change anything and it permits no
858 /// simplification.  This returns V itself if it did some simplification of V's
859 /// operands based on the information about what bits are demanded. This returns
860 /// some other non-null value if it found out that V is equal to another value
861 /// in the context where the specified bits are demanded, but not for all users.
862 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
863                                              APInt &KnownZero, APInt &KnownOne,
864                                              unsigned Depth) {
865   assert(V != 0 && "Null pointer of Value???");
866   assert(Depth <= 6 && "Limit Search Depth");
867   uint32_t BitWidth = DemandedMask.getBitWidth();
868   const Type *VTy = V->getType();
869   assert((TD || !isa<PointerType>(VTy)) &&
870          "SimplifyDemandedBits needs to know bit widths!");
871   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
872          (!VTy->isIntOrIntVector() ||
873           VTy->getScalarSizeInBits() == BitWidth) &&
874          KnownZero.getBitWidth() == BitWidth &&
875          KnownOne.getBitWidth() == BitWidth &&
876          "Value *V, DemandedMask, KnownZero and KnownOne "
877          "must have same BitWidth");
878   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
879     // We know all of the bits for a constant!
880     KnownOne = CI->getValue() & DemandedMask;
881     KnownZero = ~KnownOne & DemandedMask;
882     return 0;
883   }
884   if (isa<ConstantPointerNull>(V)) {
885     // We know all of the bits for a constant!
886     KnownOne.clear();
887     KnownZero = DemandedMask;
888     return 0;
889   }
890
891   KnownZero.clear();
892   KnownOne.clear();
893   if (DemandedMask == 0) {   // Not demanding any bits from V.
894     if (isa<UndefValue>(V))
895       return 0;
896     return UndefValue::get(VTy);
897   }
898   
899   if (Depth == 6)        // Limit search depth.
900     return 0;
901   
902   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
903   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
904
905   Instruction *I = dyn_cast<Instruction>(V);
906   if (!I) {
907     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
908     return 0;        // Only analyze instructions.
909   }
910
911   // If there are multiple uses of this value and we aren't at the root, then
912   // we can't do any simplifications of the operands, because DemandedMask
913   // only reflects the bits demanded by *one* of the users.
914   if (Depth != 0 && !I->hasOneUse()) {
915     // Despite the fact that we can't simplify this instruction in all User's
916     // context, we can at least compute the knownzero/knownone bits, and we can
917     // do simplifications that apply to *just* the one user if we know that
918     // this instruction has a simpler value in that context.
919     if (I->getOpcode() == Instruction::And) {
920       // If either the LHS or the RHS are Zero, the result is zero.
921       ComputeMaskedBits(I->getOperand(1), DemandedMask,
922                         RHSKnownZero, RHSKnownOne, Depth+1);
923       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
924                         LHSKnownZero, LHSKnownOne, Depth+1);
925       
926       // If all of the demanded bits are known 1 on one side, return the other.
927       // These bits cannot contribute to the result of the 'and' in this
928       // context.
929       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
930           (DemandedMask & ~LHSKnownZero))
931         return I->getOperand(0);
932       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
933           (DemandedMask & ~RHSKnownZero))
934         return I->getOperand(1);
935       
936       // If all of the demanded bits in the inputs are known zeros, return zero.
937       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
938         return Constant::getNullValue(VTy);
939       
940     } else if (I->getOpcode() == Instruction::Or) {
941       // We can simplify (X|Y) -> X or Y in the user's context if we know that
942       // only bits from X or Y are demanded.
943       
944       // If either the LHS or the RHS are One, the result is One.
945       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
946                         RHSKnownZero, RHSKnownOne, Depth+1);
947       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
948                         LHSKnownZero, LHSKnownOne, Depth+1);
949       
950       // If all of the demanded bits are known zero on one side, return the
951       // other.  These bits cannot contribute to the result of the 'or' in this
952       // context.
953       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
954           (DemandedMask & ~LHSKnownOne))
955         return I->getOperand(0);
956       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
957           (DemandedMask & ~RHSKnownOne))
958         return I->getOperand(1);
959       
960       // If all of the potentially set bits on one side are known to be set on
961       // the other side, just use the 'other' side.
962       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
963           (DemandedMask & (~RHSKnownZero)))
964         return I->getOperand(0);
965       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
966           (DemandedMask & (~LHSKnownZero)))
967         return I->getOperand(1);
968     }
969     
970     // Compute the KnownZero/KnownOne bits to simplify things downstream.
971     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
972     return 0;
973   }
974   
975   // If this is the root being simplified, allow it to have multiple uses,
976   // just set the DemandedMask to all bits so that we can try to simplify the
977   // operands.  This allows visitTruncInst (for example) to simplify the
978   // operand of a trunc without duplicating all the logic below.
979   if (Depth == 0 && !V->hasOneUse())
980     DemandedMask = APInt::getAllOnesValue(BitWidth);
981   
982   switch (I->getOpcode()) {
983   default:
984     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
985     break;
986   case Instruction::And:
987     // If either the LHS or the RHS are Zero, the result is zero.
988     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
989                              RHSKnownZero, RHSKnownOne, Depth+1) ||
990         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
991                              LHSKnownZero, LHSKnownOne, Depth+1))
992       return I;
993     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
994     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
995
996     // If all of the demanded bits are known 1 on one side, return the other.
997     // These bits cannot contribute to the result of the 'and'.
998     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
999         (DemandedMask & ~LHSKnownZero))
1000       return I->getOperand(0);
1001     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
1002         (DemandedMask & ~RHSKnownZero))
1003       return I->getOperand(1);
1004     
1005     // If all of the demanded bits in the inputs are known zeros, return zero.
1006     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1007       return Constant::getNullValue(VTy);
1008       
1009     // If the RHS is a constant, see if we can simplify it.
1010     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1011       return I;
1012       
1013     // Output known-1 bits are only known if set in both the LHS & RHS.
1014     RHSKnownOne &= LHSKnownOne;
1015     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1016     RHSKnownZero |= LHSKnownZero;
1017     break;
1018   case Instruction::Or:
1019     // If either the LHS or the RHS are One, the result is One.
1020     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1021                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1022         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
1023                              LHSKnownZero, LHSKnownOne, Depth+1))
1024       return I;
1025     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1026     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1027     
1028     // If all of the demanded bits are known zero on one side, return the other.
1029     // These bits cannot contribute to the result of the 'or'.
1030     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1031         (DemandedMask & ~LHSKnownOne))
1032       return I->getOperand(0);
1033     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1034         (DemandedMask & ~RHSKnownOne))
1035       return I->getOperand(1);
1036
1037     // If all of the potentially set bits on one side are known to be set on
1038     // the other side, just use the 'other' side.
1039     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1040         (DemandedMask & (~RHSKnownZero)))
1041       return I->getOperand(0);
1042     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1043         (DemandedMask & (~LHSKnownZero)))
1044       return I->getOperand(1);
1045         
1046     // If the RHS is a constant, see if we can simplify it.
1047     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1048       return I;
1049           
1050     // Output known-0 bits are only known if clear in both the LHS & RHS.
1051     RHSKnownZero &= LHSKnownZero;
1052     // Output known-1 are known to be set if set in either the LHS | RHS.
1053     RHSKnownOne |= LHSKnownOne;
1054     break;
1055   case Instruction::Xor: {
1056     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1057                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1058         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1059                              LHSKnownZero, LHSKnownOne, Depth+1))
1060       return I;
1061     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1062     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1063     
1064     // If all of the demanded bits are known zero on one side, return the other.
1065     // These bits cannot contribute to the result of the 'xor'.
1066     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1067       return I->getOperand(0);
1068     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1069       return I->getOperand(1);
1070     
1071     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1072     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1073                          (RHSKnownOne & LHSKnownOne);
1074     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1075     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1076                         (RHSKnownOne & LHSKnownZero);
1077     
1078     // If all of the demanded bits are known to be zero on one side or the
1079     // other, turn this into an *inclusive* or.
1080     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1081     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1082       Instruction *Or = 
1083         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1084                                  I->getName());
1085       return InsertNewInstBefore(Or, *I);
1086     }
1087     
1088     // If all of the demanded bits on one side are known, and all of the set
1089     // bits on that side are also known to be set on the other side, turn this
1090     // into an AND, as we know the bits will be cleared.
1091     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1092     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1093       // all known
1094       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1095         Constant *AndC = Constant::getIntegerValue(VTy,
1096                                                    ~RHSKnownOne & DemandedMask);
1097         Instruction *And = 
1098           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1099         return InsertNewInstBefore(And, *I);
1100       }
1101     }
1102     
1103     // If the RHS is a constant, see if we can simplify it.
1104     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1105     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1106       return I;
1107     
1108     // If our LHS is an 'and' and if it has one use, and if any of the bits we
1109     // are flipping are known to be set, then the xor is just resetting those
1110     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
1111     // simplifying both of them.
1112     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1113       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1114           isa<ConstantInt>(I->getOperand(1)) &&
1115           isa<ConstantInt>(LHSInst->getOperand(1)) &&
1116           (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1117         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1118         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1119         APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1120         
1121         Constant *AndC =
1122           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1123         Instruction *NewAnd = 
1124           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1125         InsertNewInstBefore(NewAnd, *I);
1126         
1127         Constant *XorC =
1128           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1129         Instruction *NewXor =
1130           BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1131         return InsertNewInstBefore(NewXor, *I);
1132       }
1133           
1134           
1135     RHSKnownZero = KnownZeroOut;
1136     RHSKnownOne  = KnownOneOut;
1137     break;
1138   }
1139   case Instruction::Select:
1140     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1141                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1142         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1143                              LHSKnownZero, LHSKnownOne, Depth+1))
1144       return I;
1145     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1146     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1147     
1148     // If the operands are constants, see if we can simplify them.
1149     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1150         ShrinkDemandedConstant(I, 2, DemandedMask))
1151       return I;
1152     
1153     // Only known if known in both the LHS and RHS.
1154     RHSKnownOne &= LHSKnownOne;
1155     RHSKnownZero &= LHSKnownZero;
1156     break;
1157   case Instruction::Trunc: {
1158     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1159     DemandedMask.zext(truncBf);
1160     RHSKnownZero.zext(truncBf);
1161     RHSKnownOne.zext(truncBf);
1162     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1163                              RHSKnownZero, RHSKnownOne, Depth+1))
1164       return I;
1165     DemandedMask.trunc(BitWidth);
1166     RHSKnownZero.trunc(BitWidth);
1167     RHSKnownOne.trunc(BitWidth);
1168     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1169     break;
1170   }
1171   case Instruction::BitCast:
1172     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1173       return false;  // vector->int or fp->int?
1174
1175     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1176       if (const VectorType *SrcVTy =
1177             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1178         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1179           // Don't touch a bitcast between vectors of different element counts.
1180           return false;
1181       } else
1182         // Don't touch a scalar-to-vector bitcast.
1183         return false;
1184     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1185       // Don't touch a vector-to-scalar bitcast.
1186       return false;
1187
1188     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1189                              RHSKnownZero, RHSKnownOne, Depth+1))
1190       return I;
1191     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1192     break;
1193   case Instruction::ZExt: {
1194     // Compute the bits in the result that are not present in the input.
1195     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1196     
1197     DemandedMask.trunc(SrcBitWidth);
1198     RHSKnownZero.trunc(SrcBitWidth);
1199     RHSKnownOne.trunc(SrcBitWidth);
1200     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1201                              RHSKnownZero, RHSKnownOne, Depth+1))
1202       return I;
1203     DemandedMask.zext(BitWidth);
1204     RHSKnownZero.zext(BitWidth);
1205     RHSKnownOne.zext(BitWidth);
1206     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1207     // The top bits are known to be zero.
1208     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1209     break;
1210   }
1211   case Instruction::SExt: {
1212     // Compute the bits in the result that are not present in the input.
1213     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1214     
1215     APInt InputDemandedBits = DemandedMask & 
1216                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1217
1218     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1219     // If any of the sign extended bits are demanded, we know that the sign
1220     // bit is demanded.
1221     if ((NewBits & DemandedMask) != 0)
1222       InputDemandedBits.set(SrcBitWidth-1);
1223       
1224     InputDemandedBits.trunc(SrcBitWidth);
1225     RHSKnownZero.trunc(SrcBitWidth);
1226     RHSKnownOne.trunc(SrcBitWidth);
1227     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1228                              RHSKnownZero, RHSKnownOne, Depth+1))
1229       return I;
1230     InputDemandedBits.zext(BitWidth);
1231     RHSKnownZero.zext(BitWidth);
1232     RHSKnownOne.zext(BitWidth);
1233     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1234       
1235     // If the sign bit of the input is known set or clear, then we know the
1236     // top bits of the result.
1237
1238     // If the input sign bit is known zero, or if the NewBits are not demanded
1239     // convert this into a zero extension.
1240     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1241       // Convert to ZExt cast
1242       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1243       return InsertNewInstBefore(NewCast, *I);
1244     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1245       RHSKnownOne |= NewBits;
1246     }
1247     break;
1248   }
1249   case Instruction::Add: {
1250     // Figure out what the input bits are.  If the top bits of the and result
1251     // are not demanded, then the add doesn't demand them from its input
1252     // either.
1253     unsigned NLZ = DemandedMask.countLeadingZeros();
1254       
1255     // If there is a constant on the RHS, there are a variety of xformations
1256     // we can do.
1257     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1258       // If null, this should be simplified elsewhere.  Some of the xforms here
1259       // won't work if the RHS is zero.
1260       if (RHS->isZero())
1261         break;
1262       
1263       // If the top bit of the output is demanded, demand everything from the
1264       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1265       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1266
1267       // Find information about known zero/one bits in the input.
1268       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1269                                LHSKnownZero, LHSKnownOne, Depth+1))
1270         return I;
1271
1272       // If the RHS of the add has bits set that can't affect the input, reduce
1273       // the constant.
1274       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1275         return I;
1276       
1277       // Avoid excess work.
1278       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1279         break;
1280       
1281       // Turn it into OR if input bits are zero.
1282       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1283         Instruction *Or =
1284           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1285                                    I->getName());
1286         return InsertNewInstBefore(Or, *I);
1287       }
1288       
1289       // We can say something about the output known-zero and known-one bits,
1290       // depending on potential carries from the input constant and the
1291       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1292       // bits set and the RHS constant is 0x01001, then we know we have a known
1293       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1294       
1295       // To compute this, we first compute the potential carry bits.  These are
1296       // the bits which may be modified.  I'm not aware of a better way to do
1297       // this scan.
1298       const APInt &RHSVal = RHS->getValue();
1299       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1300       
1301       // Now that we know which bits have carries, compute the known-1/0 sets.
1302       
1303       // Bits are known one if they are known zero in one operand and one in the
1304       // other, and there is no input carry.
1305       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1306                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1307       
1308       // Bits are known zero if they are known zero in both operands and there
1309       // is no input carry.
1310       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1311     } else {
1312       // If the high-bits of this ADD 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 ADD to demand the most
1316         // significant bit and all those below it.
1317         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1318         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1319                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1320             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1321                                  LHSKnownZero, LHSKnownOne, Depth+1))
1322           return I;
1323       }
1324     }
1325     break;
1326   }
1327   case Instruction::Sub:
1328     // If the high-bits of this SUB are not demanded, then it does not demand
1329     // the high bits of its LHS or RHS.
1330     if (DemandedMask[BitWidth-1] == 0) {
1331       // Right fill the mask of bits for this SUB to demand the most
1332       // significant bit and all those below it.
1333       uint32_t NLZ = DemandedMask.countLeadingZeros();
1334       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1335       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1336                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1337           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1338                                LHSKnownZero, LHSKnownOne, Depth+1))
1339         return I;
1340     }
1341     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1342     // the known zeros and ones.
1343     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1344     break;
1345   case Instruction::Shl:
1346     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1347       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1348       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1349       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1350                                RHSKnownZero, RHSKnownOne, Depth+1))
1351         return I;
1352       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1353       RHSKnownZero <<= ShiftAmt;
1354       RHSKnownOne  <<= ShiftAmt;
1355       // low bits known zero.
1356       if (ShiftAmt)
1357         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1358     }
1359     break;
1360   case Instruction::LShr:
1361     // For a logical shift right
1362     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1363       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1364       
1365       // Unsigned shift right.
1366       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1367       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1368                                RHSKnownZero, RHSKnownOne, Depth+1))
1369         return I;
1370       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1371       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1372       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1373       if (ShiftAmt) {
1374         // Compute the new bits that are at the top now.
1375         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1376         RHSKnownZero |= HighBits;  // high bits known zero.
1377       }
1378     }
1379     break;
1380   case Instruction::AShr:
1381     // If this is an arithmetic shift right and only the low-bit is set, we can
1382     // always convert this into a logical shr, even if the shift amount is
1383     // variable.  The low bit of the shift cannot be an input sign bit unless
1384     // the shift amount is >= the size of the datatype, which is undefined.
1385     if (DemandedMask == 1) {
1386       // Perform the logical shift right.
1387       Instruction *NewVal = BinaryOperator::CreateLShr(
1388                         I->getOperand(0), I->getOperand(1), I->getName());
1389       return InsertNewInstBefore(NewVal, *I);
1390     }    
1391
1392     // If the sign bit is the only bit demanded by this ashr, then there is no
1393     // need to do it, the shift doesn't change the high bit.
1394     if (DemandedMask.isSignBit())
1395       return I->getOperand(0);
1396     
1397     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1398       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1399       
1400       // Signed shift right.
1401       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1402       // If any of the "high bits" are demanded, we should set the sign bit as
1403       // demanded.
1404       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1405         DemandedMaskIn.set(BitWidth-1);
1406       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1407                                RHSKnownZero, RHSKnownOne, Depth+1))
1408         return I;
1409       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1410       // Compute the new bits that are at the top now.
1411       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1412       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1413       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1414         
1415       // Handle the sign bits.
1416       APInt SignBit(APInt::getSignBit(BitWidth));
1417       // Adjust to where it is now in the mask.
1418       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1419         
1420       // If the input sign bit is known to be zero, or if none of the top bits
1421       // are demanded, turn this into an unsigned shift right.
1422       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1423           (HighBits & ~DemandedMask) == HighBits) {
1424         // Perform the logical shift right.
1425         Instruction *NewVal = BinaryOperator::CreateLShr(
1426                           I->getOperand(0), SA, I->getName());
1427         return InsertNewInstBefore(NewVal, *I);
1428       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1429         RHSKnownOne |= HighBits;
1430       }
1431     }
1432     break;
1433   case Instruction::SRem:
1434     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1435       APInt RA = Rem->getValue().abs();
1436       if (RA.isPowerOf2()) {
1437         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1438           return I->getOperand(0);
1439
1440         APInt LowBits = RA - 1;
1441         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1442         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1443                                  LHSKnownZero, LHSKnownOne, Depth+1))
1444           return I;
1445
1446         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1447           LHSKnownZero |= ~LowBits;
1448
1449         KnownZero |= LHSKnownZero & DemandedMask;
1450
1451         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1452       }
1453     }
1454     break;
1455   case Instruction::URem: {
1456     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1457     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1458     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1459                              KnownZero2, KnownOne2, Depth+1) ||
1460         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1461                              KnownZero2, KnownOne2, Depth+1))
1462       return I;
1463
1464     unsigned Leaders = KnownZero2.countLeadingOnes();
1465     Leaders = std::max(Leaders,
1466                        KnownZero2.countLeadingOnes());
1467     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1468     break;
1469   }
1470   case Instruction::Call:
1471     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1472       switch (II->getIntrinsicID()) {
1473       default: break;
1474       case Intrinsic::bswap: {
1475         // If the only bits demanded come from one byte of the bswap result,
1476         // just shift the input byte into position to eliminate the bswap.
1477         unsigned NLZ = DemandedMask.countLeadingZeros();
1478         unsigned NTZ = DemandedMask.countTrailingZeros();
1479           
1480         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1481         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1482         // have 14 leading zeros, round to 8.
1483         NLZ &= ~7;
1484         NTZ &= ~7;
1485         // If we need exactly one byte, we can do this transformation.
1486         if (BitWidth-NLZ-NTZ == 8) {
1487           unsigned ResultBit = NTZ;
1488           unsigned InputBit = BitWidth-NTZ-8;
1489           
1490           // Replace this with either a left or right shift to get the byte into
1491           // the right place.
1492           Instruction *NewVal;
1493           if (InputBit > ResultBit)
1494             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1495                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1496           else
1497             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1498                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1499           NewVal->takeName(I);
1500           return InsertNewInstBefore(NewVal, *I);
1501         }
1502           
1503         // TODO: Could compute known zero/one bits based on the input.
1504         break;
1505       }
1506       }
1507     }
1508     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1509     break;
1510   }
1511   
1512   // If the client is only demanding bits that we know, return the known
1513   // constant.
1514   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1515     return Constant::getIntegerValue(VTy, RHSKnownOne);
1516   return false;
1517 }
1518
1519
1520 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1521 /// any number of elements. DemandedElts contains the set of elements that are
1522 /// actually used by the caller.  This method analyzes which elements of the
1523 /// operand are undef and returns that information in UndefElts.
1524 ///
1525 /// If the information about demanded elements can be used to simplify the
1526 /// operation, the operation is simplified, then the resultant value is
1527 /// returned.  This returns null if no change was made.
1528 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1529                                                 APInt& UndefElts,
1530                                                 unsigned Depth) {
1531   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1532   APInt EltMask(APInt::getAllOnesValue(VWidth));
1533   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1534
1535   if (isa<UndefValue>(V)) {
1536     // If the entire vector is undefined, just return this info.
1537     UndefElts = EltMask;
1538     return 0;
1539   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1540     UndefElts = EltMask;
1541     return UndefValue::get(V->getType());
1542   }
1543
1544   UndefElts = 0;
1545   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1546     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1547     Constant *Undef = UndefValue::get(EltTy);
1548
1549     std::vector<Constant*> Elts;
1550     for (unsigned i = 0; i != VWidth; ++i)
1551       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1552         Elts.push_back(Undef);
1553         UndefElts.set(i);
1554       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1555         Elts.push_back(Undef);
1556         UndefElts.set(i);
1557       } else {                               // Otherwise, defined.
1558         Elts.push_back(CP->getOperand(i));
1559       }
1560
1561     // If we changed the constant, return it.
1562     Constant *NewCP = ConstantVector::get(Elts);
1563     return NewCP != CP ? NewCP : 0;
1564   } else if (isa<ConstantAggregateZero>(V)) {
1565     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1566     // set to undef.
1567     
1568     // Check if this is identity. If so, return 0 since we are not simplifying
1569     // anything.
1570     if (DemandedElts == ((1ULL << VWidth) -1))
1571       return 0;
1572     
1573     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1574     Constant *Zero = Constant::getNullValue(EltTy);
1575     Constant *Undef = UndefValue::get(EltTy);
1576     std::vector<Constant*> Elts;
1577     for (unsigned i = 0; i != VWidth; ++i) {
1578       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1579       Elts.push_back(Elt);
1580     }
1581     UndefElts = DemandedElts ^ EltMask;
1582     return ConstantVector::get(Elts);
1583   }
1584   
1585   // Limit search depth.
1586   if (Depth == 10)
1587     return 0;
1588
1589   // If multiple users are using the root value, procede with
1590   // simplification conservatively assuming that all elements
1591   // are needed.
1592   if (!V->hasOneUse()) {
1593     // Quit if we find multiple users of a non-root value though.
1594     // They'll be handled when it's their turn to be visited by
1595     // the main instcombine process.
1596     if (Depth != 0)
1597       // TODO: Just compute the UndefElts information recursively.
1598       return 0;
1599
1600     // Conservatively assume that all elements are needed.
1601     DemandedElts = EltMask;
1602   }
1603   
1604   Instruction *I = dyn_cast<Instruction>(V);
1605   if (!I) return 0;        // Only analyze instructions.
1606   
1607   bool MadeChange = false;
1608   APInt UndefElts2(VWidth, 0);
1609   Value *TmpV;
1610   switch (I->getOpcode()) {
1611   default: break;
1612     
1613   case Instruction::InsertElement: {
1614     // If this is a variable index, we don't know which element it overwrites.
1615     // demand exactly the same input as we produce.
1616     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1617     if (Idx == 0) {
1618       // Note that we can't propagate undef elt info, because we don't know
1619       // which elt is getting updated.
1620       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1621                                         UndefElts2, Depth+1);
1622       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1623       break;
1624     }
1625     
1626     // If this is inserting an element that isn't demanded, remove this
1627     // insertelement.
1628     unsigned IdxNo = Idx->getZExtValue();
1629     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1630       Worklist.Add(I);
1631       return I->getOperand(0);
1632     }
1633     
1634     // Otherwise, the element inserted overwrites whatever was there, so the
1635     // input demanded set is simpler than the output set.
1636     APInt DemandedElts2 = DemandedElts;
1637     DemandedElts2.clear(IdxNo);
1638     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1639                                       UndefElts, Depth+1);
1640     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1641
1642     // The inserted element is defined.
1643     UndefElts.clear(IdxNo);
1644     break;
1645   }
1646   case Instruction::ShuffleVector: {
1647     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1648     uint64_t LHSVWidth =
1649       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1650     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1651     for (unsigned i = 0; i < VWidth; i++) {
1652       if (DemandedElts[i]) {
1653         unsigned MaskVal = Shuffle->getMaskValue(i);
1654         if (MaskVal != -1u) {
1655           assert(MaskVal < LHSVWidth * 2 &&
1656                  "shufflevector mask index out of range!");
1657           if (MaskVal < LHSVWidth)
1658             LeftDemanded.set(MaskVal);
1659           else
1660             RightDemanded.set(MaskVal - LHSVWidth);
1661         }
1662       }
1663     }
1664
1665     APInt UndefElts4(LHSVWidth, 0);
1666     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1667                                       UndefElts4, Depth+1);
1668     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1669
1670     APInt UndefElts3(LHSVWidth, 0);
1671     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1672                                       UndefElts3, Depth+1);
1673     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1674
1675     bool NewUndefElts = false;
1676     for (unsigned i = 0; i < VWidth; i++) {
1677       unsigned MaskVal = Shuffle->getMaskValue(i);
1678       if (MaskVal == -1u) {
1679         UndefElts.set(i);
1680       } else if (MaskVal < LHSVWidth) {
1681         if (UndefElts4[MaskVal]) {
1682           NewUndefElts = true;
1683           UndefElts.set(i);
1684         }
1685       } else {
1686         if (UndefElts3[MaskVal - LHSVWidth]) {
1687           NewUndefElts = true;
1688           UndefElts.set(i);
1689         }
1690       }
1691     }
1692
1693     if (NewUndefElts) {
1694       // Add additional discovered undefs.
1695       std::vector<Constant*> Elts;
1696       for (unsigned i = 0; i < VWidth; ++i) {
1697         if (UndefElts[i])
1698           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1699         else
1700           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1701                                           Shuffle->getMaskValue(i)));
1702       }
1703       I->setOperand(2, ConstantVector::get(Elts));
1704       MadeChange = true;
1705     }
1706     break;
1707   }
1708   case Instruction::BitCast: {
1709     // Vector->vector casts only.
1710     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1711     if (!VTy) break;
1712     unsigned InVWidth = VTy->getNumElements();
1713     APInt InputDemandedElts(InVWidth, 0);
1714     unsigned Ratio;
1715
1716     if (VWidth == InVWidth) {
1717       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1718       // elements as are demanded of us.
1719       Ratio = 1;
1720       InputDemandedElts = DemandedElts;
1721     } else if (VWidth > InVWidth) {
1722       // Untested so far.
1723       break;
1724       
1725       // If there are more elements in the result than there are in the source,
1726       // then an input element is live if any of the corresponding output
1727       // elements are live.
1728       Ratio = VWidth/InVWidth;
1729       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1730         if (DemandedElts[OutIdx])
1731           InputDemandedElts.set(OutIdx/Ratio);
1732       }
1733     } else {
1734       // Untested so far.
1735       break;
1736       
1737       // If there are more elements in the source than there are in the result,
1738       // then an input element is live if the corresponding output element is
1739       // live.
1740       Ratio = InVWidth/VWidth;
1741       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1742         if (DemandedElts[InIdx/Ratio])
1743           InputDemandedElts.set(InIdx);
1744     }
1745     
1746     // div/rem demand all inputs, because they don't want divide by zero.
1747     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1748                                       UndefElts2, Depth+1);
1749     if (TmpV) {
1750       I->setOperand(0, TmpV);
1751       MadeChange = true;
1752     }
1753     
1754     UndefElts = UndefElts2;
1755     if (VWidth > InVWidth) {
1756       llvm_unreachable("Unimp");
1757       // If there are more elements in the result than there are in the source,
1758       // then an output element is undef if the corresponding input element is
1759       // undef.
1760       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1761         if (UndefElts2[OutIdx/Ratio])
1762           UndefElts.set(OutIdx);
1763     } else if (VWidth < InVWidth) {
1764       llvm_unreachable("Unimp");
1765       // If there are more elements in the source than there are in the result,
1766       // then a result element is undef if all of the corresponding input
1767       // elements are undef.
1768       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1769       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1770         if (!UndefElts2[InIdx])            // Not undef?
1771           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1772     }
1773     break;
1774   }
1775   case Instruction::And:
1776   case Instruction::Or:
1777   case Instruction::Xor:
1778   case Instruction::Add:
1779   case Instruction::Sub:
1780   case Instruction::Mul:
1781     // div/rem demand all inputs, because they don't want divide by zero.
1782     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1783                                       UndefElts, Depth+1);
1784     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1785     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1786                                       UndefElts2, Depth+1);
1787     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1788       
1789     // Output elements are undefined if both are undefined.  Consider things
1790     // like undef&0.  The result is known zero, not undef.
1791     UndefElts &= UndefElts2;
1792     break;
1793     
1794   case Instruction::Call: {
1795     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1796     if (!II) break;
1797     switch (II->getIntrinsicID()) {
1798     default: break;
1799       
1800     // Binary vector operations that work column-wise.  A dest element is a
1801     // function of the corresponding input elements from the two inputs.
1802     case Intrinsic::x86_sse_sub_ss:
1803     case Intrinsic::x86_sse_mul_ss:
1804     case Intrinsic::x86_sse_min_ss:
1805     case Intrinsic::x86_sse_max_ss:
1806     case Intrinsic::x86_sse2_sub_sd:
1807     case Intrinsic::x86_sse2_mul_sd:
1808     case Intrinsic::x86_sse2_min_sd:
1809     case Intrinsic::x86_sse2_max_sd:
1810       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1811                                         UndefElts, Depth+1);
1812       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1813       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1814                                         UndefElts2, Depth+1);
1815       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1816
1817       // If only the low elt is demanded and this is a scalarizable intrinsic,
1818       // scalarize it now.
1819       if (DemandedElts == 1) {
1820         switch (II->getIntrinsicID()) {
1821         default: break;
1822         case Intrinsic::x86_sse_sub_ss:
1823         case Intrinsic::x86_sse_mul_ss:
1824         case Intrinsic::x86_sse2_sub_sd:
1825         case Intrinsic::x86_sse2_mul_sd:
1826           // TODO: Lower MIN/MAX/ABS/etc
1827           Value *LHS = II->getOperand(1);
1828           Value *RHS = II->getOperand(2);
1829           // Extract the element as scalars.
1830           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1831             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1832           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1833             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1834           
1835           switch (II->getIntrinsicID()) {
1836           default: llvm_unreachable("Case stmts out of sync!");
1837           case Intrinsic::x86_sse_sub_ss:
1838           case Intrinsic::x86_sse2_sub_sd:
1839             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1840                                                         II->getName()), *II);
1841             break;
1842           case Intrinsic::x86_sse_mul_ss:
1843           case Intrinsic::x86_sse2_mul_sd:
1844             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1845                                                          II->getName()), *II);
1846             break;
1847           }
1848           
1849           Instruction *New =
1850             InsertElementInst::Create(
1851               UndefValue::get(II->getType()), TmpV,
1852               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1853           InsertNewInstBefore(New, *II);
1854           return New;
1855         }            
1856       }
1857         
1858       // Output elements are undefined if both are undefined.  Consider things
1859       // like undef&0.  The result is known zero, not undef.
1860       UndefElts &= UndefElts2;
1861       break;
1862     }
1863     break;
1864   }
1865   }
1866   return MadeChange ? I : 0;
1867 }
1868
1869
1870 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1871 /// function is designed to check a chain of associative operators for a
1872 /// potential to apply a certain optimization.  Since the optimization may be
1873 /// applicable if the expression was reassociated, this checks the chain, then
1874 /// reassociates the expression as necessary to expose the optimization
1875 /// opportunity.  This makes use of a special Functor, which must define
1876 /// 'shouldApply' and 'apply' methods.
1877 ///
1878 template<typename Functor>
1879 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1880   unsigned Opcode = Root.getOpcode();
1881   Value *LHS = Root.getOperand(0);
1882
1883   // Quick check, see if the immediate LHS matches...
1884   if (F.shouldApply(LHS))
1885     return F.apply(Root);
1886
1887   // Otherwise, if the LHS is not of the same opcode as the root, return.
1888   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1889   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1890     // Should we apply this transform to the RHS?
1891     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1892
1893     // If not to the RHS, check to see if we should apply to the LHS...
1894     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1895       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1896       ShouldApply = true;
1897     }
1898
1899     // If the functor wants to apply the optimization to the RHS of LHSI,
1900     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1901     if (ShouldApply) {
1902       // Now all of the instructions are in the current basic block, go ahead
1903       // and perform the reassociation.
1904       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1905
1906       // First move the selected RHS to the LHS of the root...
1907       Root.setOperand(0, LHSI->getOperand(1));
1908
1909       // Make what used to be the LHS of the root be the user of the root...
1910       Value *ExtraOperand = TmpLHSI->getOperand(1);
1911       if (&Root == TmpLHSI) {
1912         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1913         return 0;
1914       }
1915       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1916       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1917       BasicBlock::iterator ARI = &Root; ++ARI;
1918       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1919       ARI = Root;
1920
1921       // Now propagate the ExtraOperand down the chain of instructions until we
1922       // get to LHSI.
1923       while (TmpLHSI != LHSI) {
1924         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1925         // Move the instruction to immediately before the chain we are
1926         // constructing to avoid breaking dominance properties.
1927         NextLHSI->moveBefore(ARI);
1928         ARI = NextLHSI;
1929
1930         Value *NextOp = NextLHSI->getOperand(1);
1931         NextLHSI->setOperand(1, ExtraOperand);
1932         TmpLHSI = NextLHSI;
1933         ExtraOperand = NextOp;
1934       }
1935
1936       // Now that the instructions are reassociated, have the functor perform
1937       // the transformation...
1938       return F.apply(Root);
1939     }
1940
1941     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1942   }
1943   return 0;
1944 }
1945
1946 namespace {
1947
1948 // AddRHS - Implements: X + X --> X << 1
1949 struct AddRHS {
1950   Value *RHS;
1951   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1952   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1953   Instruction *apply(BinaryOperator &Add) const {
1954     return BinaryOperator::CreateShl(Add.getOperand(0),
1955                                      ConstantInt::get(Add.getType(), 1));
1956   }
1957 };
1958
1959 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1960 //                 iff C1&C2 == 0
1961 struct AddMaskingAnd {
1962   Constant *C2;
1963   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1964   bool shouldApply(Value *LHS) const {
1965     ConstantInt *C1;
1966     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1967            ConstantExpr::getAnd(C1, C2)->isNullValue();
1968   }
1969   Instruction *apply(BinaryOperator &Add) const {
1970     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1971   }
1972 };
1973
1974 }
1975
1976 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1977                                              InstCombiner *IC) {
1978   if (CastInst *CI = dyn_cast<CastInst>(&I))
1979     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1980
1981   // Figure out if the constant is the left or the right argument.
1982   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1983   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1984
1985   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1986     if (ConstIsRHS)
1987       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1988     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1989   }
1990
1991   Value *Op0 = SO, *Op1 = ConstOperand;
1992   if (!ConstIsRHS)
1993     std::swap(Op0, Op1);
1994   
1995   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1996     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1997                                     SO->getName()+".op");
1998   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1999     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2000                                    SO->getName()+".cmp");
2001   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
2002     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2003                                    SO->getName()+".cmp");
2004   llvm_unreachable("Unknown binary instruction type!");
2005 }
2006
2007 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
2008 // constant as the other operand, try to fold the binary operator into the
2009 // select arguments.  This also works for Cast instructions, which obviously do
2010 // not have a second operand.
2011 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2012                                      InstCombiner *IC) {
2013   // Don't modify shared select instructions
2014   if (!SI->hasOneUse()) return 0;
2015   Value *TV = SI->getOperand(1);
2016   Value *FV = SI->getOperand(2);
2017
2018   if (isa<Constant>(TV) || isa<Constant>(FV)) {
2019     // Bool selects with constant operands can be folded to logical ops.
2020     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
2021
2022     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2023     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2024
2025     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2026                               SelectFalseVal);
2027   }
2028   return 0;
2029 }
2030
2031
2032 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2033 /// has a PHI node as operand #0, see if we can fold the instruction into the
2034 /// PHI (which is only possible if all operands to the PHI are constants).
2035 ///
2036 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2037 /// that would normally be unprofitable because they strongly encourage jump
2038 /// threading.
2039 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2040                                          bool AllowAggressive) {
2041   AllowAggressive = false;
2042   PHINode *PN = cast<PHINode>(I.getOperand(0));
2043   unsigned NumPHIValues = PN->getNumIncomingValues();
2044   if (NumPHIValues == 0 ||
2045       // We normally only transform phis with a single use, unless we're trying
2046       // hard to make jump threading happen.
2047       (!PN->hasOneUse() && !AllowAggressive))
2048     return 0;
2049   
2050   
2051   // Check to see if all of the operands of the PHI are simple constants
2052   // (constantint/constantfp/undef).  If there is one non-constant value,
2053   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
2054   // bail out.  We don't do arbitrary constant expressions here because moving
2055   // their computation can be expensive without a cost model.
2056   BasicBlock *NonConstBB = 0;
2057   for (unsigned i = 0; i != NumPHIValues; ++i)
2058     if (!isa<Constant>(PN->getIncomingValue(i)) ||
2059         isa<ConstantExpr>(PN->getIncomingValue(i))) {
2060       if (NonConstBB) return 0;  // More than one non-const value.
2061       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2062       NonConstBB = PN->getIncomingBlock(i);
2063       
2064       // If the incoming non-constant value is in I's block, we have an infinite
2065       // loop.
2066       if (NonConstBB == I.getParent())
2067         return 0;
2068     }
2069   
2070   // If there is exactly one non-constant value, we can insert a copy of the
2071   // operation in that block.  However, if this is a critical edge, we would be
2072   // inserting the computation one some other paths (e.g. inside a loop).  Only
2073   // do this if the pred block is unconditionally branching into the phi block.
2074   if (NonConstBB != 0 && !AllowAggressive) {
2075     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2076     if (!BI || !BI->isUnconditional()) return 0;
2077   }
2078
2079   // Okay, we can do the transformation: create the new PHI node.
2080   PHINode *NewPN = PHINode::Create(I.getType(), "");
2081   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2082   InsertNewInstBefore(NewPN, *PN);
2083   NewPN->takeName(PN);
2084
2085   // Next, add all of the operands to the PHI.
2086   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2087     // We only currently try to fold the condition of a select when it is a phi,
2088     // not the true/false values.
2089     Value *TrueV = SI->getTrueValue();
2090     Value *FalseV = SI->getFalseValue();
2091     BasicBlock *PhiTransBB = PN->getParent();
2092     for (unsigned i = 0; i != NumPHIValues; ++i) {
2093       BasicBlock *ThisBB = PN->getIncomingBlock(i);
2094       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2095       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
2096       Value *InV = 0;
2097       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2098         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2099       } else {
2100         assert(PN->getIncomingBlock(i) == NonConstBB);
2101         InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2102                                  FalseVInPred,
2103                                  "phitmp", NonConstBB->getTerminator());
2104         Worklist.Add(cast<Instruction>(InV));
2105       }
2106       NewPN->addIncoming(InV, ThisBB);
2107     }
2108   } else if (I.getNumOperands() == 2) {
2109     Constant *C = cast<Constant>(I.getOperand(1));
2110     for (unsigned i = 0; i != NumPHIValues; ++i) {
2111       Value *InV = 0;
2112       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2113         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2114           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2115         else
2116           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2117       } else {
2118         assert(PN->getIncomingBlock(i) == NonConstBB);
2119         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2120           InV = BinaryOperator::Create(BO->getOpcode(),
2121                                        PN->getIncomingValue(i), C, "phitmp",
2122                                        NonConstBB->getTerminator());
2123         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2124           InV = CmpInst::Create(CI->getOpcode(),
2125                                 CI->getPredicate(),
2126                                 PN->getIncomingValue(i), C, "phitmp",
2127                                 NonConstBB->getTerminator());
2128         else
2129           llvm_unreachable("Unknown binop!");
2130         
2131         Worklist.Add(cast<Instruction>(InV));
2132       }
2133       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2134     }
2135   } else { 
2136     CastInst *CI = cast<CastInst>(&I);
2137     const Type *RetTy = CI->getType();
2138     for (unsigned i = 0; i != NumPHIValues; ++i) {
2139       Value *InV;
2140       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2141         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2142       } else {
2143         assert(PN->getIncomingBlock(i) == NonConstBB);
2144         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2145                                I.getType(), "phitmp", 
2146                                NonConstBB->getTerminator());
2147         Worklist.Add(cast<Instruction>(InV));
2148       }
2149       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2150     }
2151   }
2152   return ReplaceInstUsesWith(I, NewPN);
2153 }
2154
2155
2156 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2157 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2158 /// This basically requires proving that the add in the original type would not
2159 /// overflow to change the sign bit or have a carry out.
2160 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2161   // There are different heuristics we can use for this.  Here are some simple
2162   // ones.
2163   
2164   // Add has the property that adding any two 2's complement numbers can only 
2165   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2166   // have at least two sign bits, we know that the addition of the two values
2167   // will sign extend fine.
2168   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2169     return true;
2170   
2171   
2172   // If one of the operands only has one non-zero bit, and if the other operand
2173   // has a known-zero bit in a more significant place than it (not including the
2174   // sign bit) the ripple may go up to and fill the zero, but won't change the
2175   // sign.  For example, (X & ~4) + 1.
2176   
2177   // TODO: Implement.
2178   
2179   return false;
2180 }
2181
2182
2183 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2184   bool Changed = SimplifyCommutative(I);
2185   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2186
2187   if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2188                                  I.hasNoUnsignedWrap(), TD))
2189     return ReplaceInstUsesWith(I, V);
2190
2191   
2192   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2193     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2194       // X + (signbit) --> X ^ signbit
2195       const APInt& Val = CI->getValue();
2196       uint32_t BitWidth = Val.getBitWidth();
2197       if (Val == APInt::getSignBit(BitWidth))
2198         return BinaryOperator::CreateXor(LHS, RHS);
2199       
2200       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2201       // (X & 254)+1 -> (X&254)|1
2202       if (SimplifyDemandedInstructionBits(I))
2203         return &I;
2204
2205       // zext(bool) + C -> bool ? C + 1 : C
2206       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2207         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2208           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2209     }
2210
2211     if (isa<PHINode>(LHS))
2212       if (Instruction *NV = FoldOpIntoPhi(I))
2213         return NV;
2214     
2215     ConstantInt *XorRHS = 0;
2216     Value *XorLHS = 0;
2217     if (isa<ConstantInt>(RHSC) &&
2218         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2219       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2220       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2221       
2222       uint32_t Size = TySizeBits / 2;
2223       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2224       APInt CFF80Val(-C0080Val);
2225       do {
2226         if (TySizeBits > Size) {
2227           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2228           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2229           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2230               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2231             // This is a sign extend if the top bits are known zero.
2232             if (!MaskedValueIsZero(XorLHS, 
2233                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2234               Size = 0;  // Not a sign ext, but can't be any others either.
2235             break;
2236           }
2237         }
2238         Size >>= 1;
2239         C0080Val = APIntOps::lshr(C0080Val, Size);
2240         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2241       } while (Size >= 1);
2242       
2243       // FIXME: This shouldn't be necessary. When the backends can handle types
2244       // with funny bit widths then this switch statement should be removed. It
2245       // is just here to get the size of the "middle" type back up to something
2246       // that the back ends can handle.
2247       const Type *MiddleType = 0;
2248       switch (Size) {
2249         default: break;
2250         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2251         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2252         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2253       }
2254       if (MiddleType) {
2255         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2256         return new SExtInst(NewTrunc, I.getType(), I.getName());
2257       }
2258     }
2259   }
2260
2261   if (I.getType() == Type::getInt1Ty(*Context))
2262     return BinaryOperator::CreateXor(LHS, RHS);
2263
2264   // X + X --> X << 1
2265   if (I.getType()->isInteger()) {
2266     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2267       return Result;
2268
2269     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2270       if (RHSI->getOpcode() == Instruction::Sub)
2271         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2272           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2273     }
2274     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2275       if (LHSI->getOpcode() == Instruction::Sub)
2276         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2277           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2278     }
2279   }
2280
2281   // -A + B  -->  B - A
2282   // -A + -B  -->  -(A + B)
2283   if (Value *LHSV = dyn_castNegVal(LHS)) {
2284     if (LHS->getType()->isIntOrIntVector()) {
2285       if (Value *RHSV = dyn_castNegVal(RHS)) {
2286         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2287         return BinaryOperator::CreateNeg(NewAdd);
2288       }
2289     }
2290     
2291     return BinaryOperator::CreateSub(RHS, LHSV);
2292   }
2293
2294   // A + -B  -->  A - B
2295   if (!isa<Constant>(RHS))
2296     if (Value *V = dyn_castNegVal(RHS))
2297       return BinaryOperator::CreateSub(LHS, V);
2298
2299
2300   ConstantInt *C2;
2301   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2302     if (X == RHS)   // X*C + X --> X * (C+1)
2303       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2304
2305     // X*C1 + X*C2 --> X * (C1+C2)
2306     ConstantInt *C1;
2307     if (X == dyn_castFoldableMul(RHS, C1))
2308       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2309   }
2310
2311   // X + X*C --> X * (C+1)
2312   if (dyn_castFoldableMul(RHS, C2) == LHS)
2313     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2314
2315   // X + ~X --> -1   since   ~X = -X-1
2316   if (dyn_castNotVal(LHS) == RHS ||
2317       dyn_castNotVal(RHS) == LHS)
2318     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2319   
2320
2321   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2322   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2323     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2324       return R;
2325   
2326   // A+B --> A|B iff A and B have no bits set in common.
2327   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2328     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2329     APInt LHSKnownOne(IT->getBitWidth(), 0);
2330     APInt LHSKnownZero(IT->getBitWidth(), 0);
2331     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2332     if (LHSKnownZero != 0) {
2333       APInt RHSKnownOne(IT->getBitWidth(), 0);
2334       APInt RHSKnownZero(IT->getBitWidth(), 0);
2335       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2336       
2337       // No bits in common -> bitwise or.
2338       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2339         return BinaryOperator::CreateOr(LHS, RHS);
2340     }
2341   }
2342
2343   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2344   if (I.getType()->isIntOrIntVector()) {
2345     Value *W, *X, *Y, *Z;
2346     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2347         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2348       if (W != Y) {
2349         if (W == Z) {
2350           std::swap(Y, Z);
2351         } else if (Y == X) {
2352           std::swap(W, X);
2353         } else if (X == Z) {
2354           std::swap(Y, Z);
2355           std::swap(W, X);
2356         }
2357       }
2358
2359       if (W == Y) {
2360         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2361         return BinaryOperator::CreateMul(W, NewAdd);
2362       }
2363     }
2364   }
2365
2366   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2367     Value *X = 0;
2368     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2369       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2370
2371     // (X & FF00) + xx00  -> (X+xx00) & FF00
2372     if (LHS->hasOneUse() &&
2373         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2374       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2375       if (Anded == CRHS) {
2376         // See if all bits from the first bit set in the Add RHS up are included
2377         // in the mask.  First, get the rightmost bit.
2378         const APInt& AddRHSV = CRHS->getValue();
2379
2380         // Form a mask of all bits from the lowest bit added through the top.
2381         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2382
2383         // See if the and mask includes all of these bits.
2384         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2385
2386         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2387           // Okay, the xform is safe.  Insert the new add pronto.
2388           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2389           return BinaryOperator::CreateAnd(NewAdd, C2);
2390         }
2391       }
2392     }
2393
2394     // Try to fold constant add into select arguments.
2395     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2396       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2397         return R;
2398   }
2399
2400   // add (select X 0 (sub n A)) A  -->  select X A n
2401   {
2402     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2403     Value *A = RHS;
2404     if (!SI) {
2405       SI = dyn_cast<SelectInst>(RHS);
2406       A = LHS;
2407     }
2408     if (SI && SI->hasOneUse()) {
2409       Value *TV = SI->getTrueValue();
2410       Value *FV = SI->getFalseValue();
2411       Value *N;
2412
2413       // Can we fold the add into the argument of the select?
2414       // We check both true and false select arguments for a matching subtract.
2415       if (match(FV, m_Zero()) &&
2416           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2417         // Fold the add into the true select value.
2418         return SelectInst::Create(SI->getCondition(), N, A);
2419       if (match(TV, m_Zero()) &&
2420           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2421         // Fold the add into the false select value.
2422         return SelectInst::Create(SI->getCondition(), A, N);
2423     }
2424   }
2425
2426   // Check for (add (sext x), y), see if we can merge this into an
2427   // integer add followed by a sext.
2428   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2429     // (add (sext x), cst) --> (sext (add x, cst'))
2430     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2431       Constant *CI = 
2432         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2433       if (LHSConv->hasOneUse() &&
2434           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2435           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2436         // Insert the new, smaller add.
2437         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2438                                               CI, "addconv");
2439         return new SExtInst(NewAdd, I.getType());
2440       }
2441     }
2442     
2443     // (add (sext x), (sext y)) --> (sext (add int x, y))
2444     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2445       // Only do this if x/y have the same type, if at last one of them has a
2446       // single use (so we don't increase the number of sexts), and if the
2447       // integer add will not overflow.
2448       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2449           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2450           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2451                                    RHSConv->getOperand(0))) {
2452         // Insert the new integer add.
2453         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2454                                               RHSConv->getOperand(0), "addconv");
2455         return new SExtInst(NewAdd, I.getType());
2456       }
2457     }
2458   }
2459
2460   return Changed ? &I : 0;
2461 }
2462
2463 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2464   bool Changed = SimplifyCommutative(I);
2465   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2466
2467   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2468     // X + 0 --> X
2469     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2470       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2471                               (I.getType())->getValueAPF()))
2472         return ReplaceInstUsesWith(I, LHS);
2473     }
2474
2475     if (isa<PHINode>(LHS))
2476       if (Instruction *NV = FoldOpIntoPhi(I))
2477         return NV;
2478   }
2479
2480   // -A + B  -->  B - A
2481   // -A + -B  -->  -(A + B)
2482   if (Value *LHSV = dyn_castFNegVal(LHS))
2483     return BinaryOperator::CreateFSub(RHS, LHSV);
2484
2485   // A + -B  -->  A - B
2486   if (!isa<Constant>(RHS))
2487     if (Value *V = dyn_castFNegVal(RHS))
2488       return BinaryOperator::CreateFSub(LHS, V);
2489
2490   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2491   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2492     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2493       return ReplaceInstUsesWith(I, LHS);
2494
2495   // Check for (add double (sitofp x), y), see if we can merge this into an
2496   // integer add followed by a promotion.
2497   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2498     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2499     // ... if the constant fits in the integer value.  This is useful for things
2500     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2501     // requires a constant pool load, and generally allows the add to be better
2502     // instcombined.
2503     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2504       Constant *CI = 
2505       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2506       if (LHSConv->hasOneUse() &&
2507           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2508           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2509         // Insert the new integer add.
2510         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2511                                               CI, "addconv");
2512         return new SIToFPInst(NewAdd, I.getType());
2513       }
2514     }
2515     
2516     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2517     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2518       // Only do this if x/y have the same type, if at last one of them has a
2519       // single use (so we don't increase the number of int->fp conversions),
2520       // and if the integer add will not overflow.
2521       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2522           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2523           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2524                                    RHSConv->getOperand(0))) {
2525         // Insert the new integer add.
2526         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2527                                               RHSConv->getOperand(0),"addconv");
2528         return new SIToFPInst(NewAdd, I.getType());
2529       }
2530     }
2531   }
2532   
2533   return Changed ? &I : 0;
2534 }
2535
2536
2537 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2538 /// code necessary to compute the offset from the base pointer (without adding
2539 /// in the base pointer).  Return the result as a signed integer of intptr size.
2540 static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2541   TargetData &TD = *IC.getTargetData();
2542   gep_type_iterator GTI = gep_type_begin(GEP);
2543   const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2544   Value *Result = Constant::getNullValue(IntPtrTy);
2545
2546   // Build a mask for high order bits.
2547   unsigned IntPtrWidth = TD.getPointerSizeInBits();
2548   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2549
2550   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2551        ++i, ++GTI) {
2552     Value *Op = *i;
2553     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2554     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2555       if (OpC->isZero()) continue;
2556       
2557       // Handle a struct index, which adds its field offset to the pointer.
2558       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2559         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2560         
2561         Result = IC.Builder->CreateAdd(Result,
2562                                        ConstantInt::get(IntPtrTy, Size),
2563                                        GEP->getName()+".offs");
2564         continue;
2565       }
2566       
2567       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2568       Constant *OC =
2569               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2570       Scale = ConstantExpr::getMul(OC, Scale);
2571       // Emit an add instruction.
2572       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2573       continue;
2574     }
2575     // Convert to correct type.
2576     if (Op->getType() != IntPtrTy)
2577       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2578     if (Size != 1) {
2579       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2580       // We'll let instcombine(mul) convert this to a shl if possible.
2581       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2582     }
2583
2584     // Emit an add instruction.
2585     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2586   }
2587   return Result;
2588 }
2589
2590
2591 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2592 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
2593 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
2594 /// be complex, and scales are involved.  The above expression would also be
2595 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2596 /// This later form is less amenable to optimization though, and we are allowed
2597 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
2598 ///
2599 /// If we can't emit an optimized form for this expression, this returns null.
2600 /// 
2601 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2602                                           InstCombiner &IC) {
2603   TargetData &TD = *IC.getTargetData();
2604   gep_type_iterator GTI = gep_type_begin(GEP);
2605
2606   // Check to see if this gep only has a single variable index.  If so, and if
2607   // any constant indices are a multiple of its scale, then we can compute this
2608   // in terms of the scale of the variable index.  For example, if the GEP
2609   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2610   // because the expression will cross zero at the same point.
2611   unsigned i, e = GEP->getNumOperands();
2612   int64_t Offset = 0;
2613   for (i = 1; i != e; ++i, ++GTI) {
2614     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2615       // Compute the aggregate offset of constant indices.
2616       if (CI->isZero()) continue;
2617
2618       // Handle a struct index, which adds its field offset to the pointer.
2619       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2620         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2621       } else {
2622         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2623         Offset += Size*CI->getSExtValue();
2624       }
2625     } else {
2626       // Found our variable index.
2627       break;
2628     }
2629   }
2630   
2631   // If there are no variable indices, we must have a constant offset, just
2632   // evaluate it the general way.
2633   if (i == e) return 0;
2634   
2635   Value *VariableIdx = GEP->getOperand(i);
2636   // Determine the scale factor of the variable element.  For example, this is
2637   // 4 if the variable index is into an array of i32.
2638   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2639   
2640   // Verify that there are no other variable indices.  If so, emit the hard way.
2641   for (++i, ++GTI; i != e; ++i, ++GTI) {
2642     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2643     if (!CI) return 0;
2644    
2645     // Compute the aggregate offset of constant indices.
2646     if (CI->isZero()) continue;
2647     
2648     // Handle a struct index, which adds its field offset to the pointer.
2649     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2650       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2651     } else {
2652       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2653       Offset += Size*CI->getSExtValue();
2654     }
2655   }
2656   
2657   // Okay, we know we have a single variable index, which must be a
2658   // pointer/array/vector index.  If there is no offset, life is simple, return
2659   // the index.
2660   unsigned IntPtrWidth = TD.getPointerSizeInBits();
2661   if (Offset == 0) {
2662     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
2663     // we don't need to bother extending: the extension won't affect where the
2664     // computation crosses zero.
2665     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2666       VariableIdx = new TruncInst(VariableIdx, 
2667                                   TD.getIntPtrType(VariableIdx->getContext()),
2668                                   VariableIdx->getName(), &I);
2669     return VariableIdx;
2670   }
2671   
2672   // Otherwise, there is an index.  The computation we will do will be modulo
2673   // the pointer size, so get it.
2674   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2675   
2676   Offset &= PtrSizeMask;
2677   VariableScale &= PtrSizeMask;
2678
2679   // To do this transformation, any constant index must be a multiple of the
2680   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
2681   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
2682   // multiple of the variable scale.
2683   int64_t NewOffs = Offset / (int64_t)VariableScale;
2684   if (Offset != NewOffs*(int64_t)VariableScale)
2685     return 0;
2686
2687   // Okay, we can do this evaluation.  Start by converting the index to intptr.
2688   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2689   if (VariableIdx->getType() != IntPtrTy)
2690     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2691                                               true /*SExt*/, 
2692                                               VariableIdx->getName(), &I);
2693   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2694   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2695 }
2696
2697
2698 /// Optimize pointer differences into the same array into a size.  Consider:
2699 ///  &A[10] - &A[0]: we should compile this to "10".  LHS/RHS are the pointer
2700 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2701 ///
2702 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2703                                                const Type *Ty) {
2704   assert(TD && "Must have target data info for this");
2705   
2706   // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2707   // this.
2708   bool Swapped;
2709   GetElementPtrInst *GEP;
2710   
2711   if ((GEP = dyn_cast<GetElementPtrInst>(LHS)) &&
2712       GEP->getOperand(0) == RHS)
2713     Swapped = false;
2714   else if ((GEP = dyn_cast<GetElementPtrInst>(RHS)) &&
2715            GEP->getOperand(0) == LHS)
2716     Swapped = true;
2717   else
2718     return 0;
2719   
2720   // TODO: Could also optimize &A[i] - &A[j] -> "i-j".
2721   
2722   // Emit the offset of the GEP and an intptr_t.
2723   Value *Result = EmitGEPOffset(GEP, *this);
2724
2725   // If we have p - gep(p, ...)  then we have to negate the result.
2726   if (Swapped)
2727     Result = Builder->CreateNeg(Result, "diff.neg");
2728
2729   return Builder->CreateIntCast(Result, Ty, true);
2730 }
2731
2732
2733 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2734   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2735
2736   if (Op0 == Op1)                        // sub X, X  -> 0
2737     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2738
2739   // If this is a 'B = x-(-A)', change to B = x+A.
2740   if (Value *V = dyn_castNegVal(Op1))
2741     return BinaryOperator::CreateAdd(Op0, V);
2742
2743   if (isa<UndefValue>(Op0))
2744     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2745   if (isa<UndefValue>(Op1))
2746     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2747   if (I.getType() == Type::getInt1Ty(*Context))
2748     return BinaryOperator::CreateXor(Op0, Op1);
2749   
2750   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2751     // Replace (-1 - A) with (~A).
2752     if (C->isAllOnesValue())
2753       return BinaryOperator::CreateNot(Op1);
2754
2755     // C - ~X == X + (1+C)
2756     Value *X = 0;
2757     if (match(Op1, m_Not(m_Value(X))))
2758       return BinaryOperator::CreateAdd(X, AddOne(C));
2759
2760     // -(X >>u 31) -> (X >>s 31)
2761     // -(X >>s 31) -> (X >>u 31)
2762     if (C->isZero()) {
2763       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2764         if (SI->getOpcode() == Instruction::LShr) {
2765           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2766             // Check to see if we are shifting out everything but the sign bit.
2767             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2768                 SI->getType()->getPrimitiveSizeInBits()-1) {
2769               // Ok, the transformation is safe.  Insert AShr.
2770               return BinaryOperator::Create(Instruction::AShr, 
2771                                           SI->getOperand(0), CU, SI->getName());
2772             }
2773           }
2774         } else if (SI->getOpcode() == Instruction::AShr) {
2775           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2776             // Check to see if we are shifting out everything but the sign bit.
2777             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2778                 SI->getType()->getPrimitiveSizeInBits()-1) {
2779               // Ok, the transformation is safe.  Insert LShr. 
2780               return BinaryOperator::CreateLShr(
2781                                           SI->getOperand(0), CU, SI->getName());
2782             }
2783           }
2784         }
2785       }
2786     }
2787
2788     // Try to fold constant sub into select arguments.
2789     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2790       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2791         return R;
2792
2793     // C - zext(bool) -> bool ? C - 1 : C
2794     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2795       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2796         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2797   }
2798
2799   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2800     if (Op1I->getOpcode() == Instruction::Add) {
2801       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2802         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2803                                          I.getName());
2804       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2805         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2806                                          I.getName());
2807       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2808         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2809           // C1-(X+C2) --> (C1-C2)-X
2810           return BinaryOperator::CreateSub(
2811             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2812       }
2813     }
2814
2815     if (Op1I->hasOneUse()) {
2816       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2817       // is not used by anyone else...
2818       //
2819       if (Op1I->getOpcode() == Instruction::Sub) {
2820         // Swap the two operands of the subexpr...
2821         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2822         Op1I->setOperand(0, IIOp1);
2823         Op1I->setOperand(1, IIOp0);
2824
2825         // Create the new top level add instruction...
2826         return BinaryOperator::CreateAdd(Op0, Op1);
2827       }
2828
2829       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2830       //
2831       if (Op1I->getOpcode() == Instruction::And &&
2832           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2833         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2834
2835         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2836         return BinaryOperator::CreateAnd(Op0, NewNot);
2837       }
2838
2839       // 0 - (X sdiv C)  -> (X sdiv -C)
2840       if (Op1I->getOpcode() == Instruction::SDiv)
2841         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2842           if (CSI->isZero())
2843             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2844               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2845                                           ConstantExpr::getNeg(DivRHS));
2846
2847       // X - X*C --> X * (1-C)
2848       ConstantInt *C2 = 0;
2849       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2850         Constant *CP1 = 
2851           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2852                                              C2);
2853         return BinaryOperator::CreateMul(Op0, CP1);
2854       }
2855     }
2856   }
2857
2858   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2859     if (Op0I->getOpcode() == Instruction::Add) {
2860       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2861         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2862       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2863         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2864     } else if (Op0I->getOpcode() == Instruction::Sub) {
2865       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2866         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2867                                          I.getName());
2868     }
2869   }
2870
2871   ConstantInt *C1;
2872   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2873     if (X == Op1)  // X*C - X --> X * (C-1)
2874       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2875
2876     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2877     if (X == dyn_castFoldableMul(Op1, C2))
2878       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2879   }
2880   
2881   // Optimize pointer differences into the same array into a size.  Consider:
2882   //  &A[10] - &A[0]: we should compile this to "10".
2883   if (TD) {
2884     if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(Op0))
2885       if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(Op1))
2886         if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2887                                                    RHS->getOperand(0),
2888                                                    I.getType()))
2889           return ReplaceInstUsesWith(I, Res);
2890     
2891     // trunc(p)-trunc(q) -> trunc(p-q)
2892     if (TruncInst *LHST = dyn_cast<TruncInst>(Op0))
2893       if (TruncInst *RHST = dyn_cast<TruncInst>(Op1))
2894         if (PtrToIntInst *LHS = dyn_cast<PtrToIntInst>(LHST->getOperand(0)))
2895           if (PtrToIntInst *RHS = dyn_cast<PtrToIntInst>(RHST->getOperand(0)))
2896             if (Value *Res = OptimizePointerDifference(LHS->getOperand(0),
2897                                                        RHS->getOperand(0),
2898                                                        I.getType()))
2899               return ReplaceInstUsesWith(I, Res);
2900   }
2901   
2902   return 0;
2903 }
2904
2905 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2906   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2907
2908   // If this is a 'B = x-(-A)', change to B = x+A...
2909   if (Value *V = dyn_castFNegVal(Op1))
2910     return BinaryOperator::CreateFAdd(Op0, V);
2911
2912   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2913     if (Op1I->getOpcode() == Instruction::FAdd) {
2914       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2915         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2916                                           I.getName());
2917       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2918         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2919                                           I.getName());
2920     }
2921   }
2922
2923   return 0;
2924 }
2925
2926 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2927 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2928 /// TrueIfSigned if the result of the comparison is true when the input value is
2929 /// signed.
2930 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2931                            bool &TrueIfSigned) {
2932   switch (pred) {
2933   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2934     TrueIfSigned = true;
2935     return RHS->isZero();
2936   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2937     TrueIfSigned = true;
2938     return RHS->isAllOnesValue();
2939   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2940     TrueIfSigned = false;
2941     return RHS->isAllOnesValue();
2942   case ICmpInst::ICMP_UGT:
2943     // True if LHS u> RHS and RHS == high-bit-mask - 1
2944     TrueIfSigned = true;
2945     return RHS->getValue() ==
2946       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2947   case ICmpInst::ICMP_UGE: 
2948     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2949     TrueIfSigned = true;
2950     return RHS->getValue().isSignBit();
2951   default:
2952     return false;
2953   }
2954 }
2955
2956 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2957   bool Changed = SimplifyCommutative(I);
2958   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2959
2960   if (isa<UndefValue>(Op1))              // undef * X -> 0
2961     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2962
2963   // Simplify mul instructions with a constant RHS.
2964   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2965     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
2966
2967       // ((X << C1)*C2) == (X * (C2 << C1))
2968       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2969         if (SI->getOpcode() == Instruction::Shl)
2970           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2971             return BinaryOperator::CreateMul(SI->getOperand(0),
2972                                         ConstantExpr::getShl(CI, ShOp));
2973
2974       if (CI->isZero())
2975         return ReplaceInstUsesWith(I, Op1C);  // X * 0  == 0
2976       if (CI->equalsInt(1))                  // X * 1  == X
2977         return ReplaceInstUsesWith(I, Op0);
2978       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2979         return BinaryOperator::CreateNeg(Op0, I.getName());
2980
2981       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2982       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2983         return BinaryOperator::CreateShl(Op0,
2984                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2985       }
2986     } else if (isa<VectorType>(Op1C->getType())) {
2987       if (Op1C->isNullValue())
2988         return ReplaceInstUsesWith(I, Op1C);
2989
2990       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2991         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2992           return BinaryOperator::CreateNeg(Op0, I.getName());
2993
2994         // As above, vector X*splat(1.0) -> X in all defined cases.
2995         if (Constant *Splat = Op1V->getSplatValue()) {
2996           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2997             if (CI->equalsInt(1))
2998               return ReplaceInstUsesWith(I, Op0);
2999         }
3000       }
3001     }
3002     
3003     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3004       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
3005           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
3006         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
3007         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3008         Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
3009         return BinaryOperator::CreateAdd(Add, C1C2);
3010         
3011       }
3012
3013     // Try to fold constant mul into select arguments.
3014     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3015       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3016         return R;
3017
3018     if (isa<PHINode>(Op0))
3019       if (Instruction *NV = FoldOpIntoPhi(I))
3020         return NV;
3021   }
3022
3023   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
3024     if (Value *Op1v = dyn_castNegVal(Op1))
3025       return BinaryOperator::CreateMul(Op0v, Op1v);
3026
3027   // (X / Y) *  Y = X - (X % Y)
3028   // (X / Y) * -Y = (X % Y) - X
3029   {
3030     Value *Op1C = Op1;
3031     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3032     if (!BO ||
3033         (BO->getOpcode() != Instruction::UDiv && 
3034          BO->getOpcode() != Instruction::SDiv)) {
3035       Op1C = Op0;
3036       BO = dyn_cast<BinaryOperator>(Op1);
3037     }
3038     Value *Neg = dyn_castNegVal(Op1C);
3039     if (BO && BO->hasOneUse() &&
3040         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
3041         (BO->getOpcode() == Instruction::UDiv ||
3042          BO->getOpcode() == Instruction::SDiv)) {
3043       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3044
3045       // If the division is exact, X % Y is zero.
3046       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3047         if (SDiv->isExact()) {
3048           if (Op1BO == Op1C)
3049             return ReplaceInstUsesWith(I, Op0BO);
3050           return BinaryOperator::CreateNeg(Op0BO);
3051         }
3052
3053       Value *Rem;
3054       if (BO->getOpcode() == Instruction::UDiv)
3055         Rem = Builder->CreateURem(Op0BO, Op1BO);
3056       else
3057         Rem = Builder->CreateSRem(Op0BO, Op1BO);
3058       Rem->takeName(BO);
3059
3060       if (Op1BO == Op1C)
3061         return BinaryOperator::CreateSub(Op0BO, Rem);
3062       return BinaryOperator::CreateSub(Rem, Op0BO);
3063     }
3064   }
3065
3066   /// i1 mul -> i1 and.
3067   if (I.getType() == Type::getInt1Ty(*Context))
3068     return BinaryOperator::CreateAnd(Op0, Op1);
3069
3070   // X*(1 << Y) --> X << Y
3071   // (1 << Y)*X --> X << Y
3072   {
3073     Value *Y;
3074     if (match(Op0, m_Shl(m_One(), m_Value(Y))))
3075       return BinaryOperator::CreateShl(Op1, Y);
3076     if (match(Op1, m_Shl(m_One(), m_Value(Y))))
3077       return BinaryOperator::CreateShl(Op0, Y);
3078   }
3079   
3080   // If one of the operands of the multiply is a cast from a boolean value, then
3081   // we know the bool is either zero or one, so this is a 'masking' multiply.
3082   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
3083   if (!isa<VectorType>(I.getType())) {
3084     // -2 is "-1 << 1" so it is all bits set except the low one.
3085     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
3086     
3087     Value *BoolCast = 0, *OtherOp = 0;
3088     if (MaskedValueIsZero(Op0, Negative2))
3089       BoolCast = Op0, OtherOp = Op1;
3090     else if (MaskedValueIsZero(Op1, Negative2))
3091       BoolCast = Op1, OtherOp = Op0;
3092
3093     if (BoolCast) {
3094       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3095                                     BoolCast, "tmp");
3096       return BinaryOperator::CreateAnd(V, OtherOp);
3097     }
3098   }
3099
3100   return Changed ? &I : 0;
3101 }
3102
3103 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3104   bool Changed = SimplifyCommutative(I);
3105   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3106
3107   // Simplify mul instructions with a constant RHS...
3108   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3109     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
3110       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
3111       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3112       if (Op1F->isExactlyValue(1.0))
3113         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
3114     } else if (isa<VectorType>(Op1C->getType())) {
3115       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
3116         // As above, vector X*splat(1.0) -> X in all defined cases.
3117         if (Constant *Splat = Op1V->getSplatValue()) {
3118           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3119             if (F->isExactlyValue(1.0))
3120               return ReplaceInstUsesWith(I, Op0);
3121         }
3122       }
3123     }
3124
3125     // Try to fold constant mul into select arguments.
3126     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3127       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3128         return R;
3129
3130     if (isa<PHINode>(Op0))
3131       if (Instruction *NV = FoldOpIntoPhi(I))
3132         return NV;
3133   }
3134
3135   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
3136     if (Value *Op1v = dyn_castFNegVal(Op1))
3137       return BinaryOperator::CreateFMul(Op0v, Op1v);
3138
3139   return Changed ? &I : 0;
3140 }
3141
3142 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3143 /// instruction.
3144 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3145   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3146   
3147   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3148   int NonNullOperand = -1;
3149   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3150     if (ST->isNullValue())
3151       NonNullOperand = 2;
3152   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3153   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3154     if (ST->isNullValue())
3155       NonNullOperand = 1;
3156   
3157   if (NonNullOperand == -1)
3158     return false;
3159   
3160   Value *SelectCond = SI->getOperand(0);
3161   
3162   // Change the div/rem to use 'Y' instead of the select.
3163   I.setOperand(1, SI->getOperand(NonNullOperand));
3164   
3165   // Okay, we know we replace the operand of the div/rem with 'Y' with no
3166   // problem.  However, the select, or the condition of the select may have
3167   // multiple uses.  Based on our knowledge that the operand must be non-zero,
3168   // propagate the known value for the select into other uses of it, and
3169   // propagate a known value of the condition into its other users.
3170   
3171   // If the select and condition only have a single use, don't bother with this,
3172   // early exit.
3173   if (SI->use_empty() && SelectCond->hasOneUse())
3174     return true;
3175   
3176   // Scan the current block backward, looking for other uses of SI.
3177   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3178   
3179   while (BBI != BBFront) {
3180     --BBI;
3181     // If we found a call to a function, we can't assume it will return, so
3182     // information from below it cannot be propagated above it.
3183     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3184       break;
3185     
3186     // Replace uses of the select or its condition with the known values.
3187     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3188          I != E; ++I) {
3189       if (*I == SI) {
3190         *I = SI->getOperand(NonNullOperand);
3191         Worklist.Add(BBI);
3192       } else if (*I == SelectCond) {
3193         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3194                                    ConstantInt::getFalse(*Context);
3195         Worklist.Add(BBI);
3196       }
3197     }
3198     
3199     // If we past the instruction, quit looking for it.
3200     if (&*BBI == SI)
3201       SI = 0;
3202     if (&*BBI == SelectCond)
3203       SelectCond = 0;
3204     
3205     // If we ran out of things to eliminate, break out of the loop.
3206     if (SelectCond == 0 && SI == 0)
3207       break;
3208     
3209   }
3210   return true;
3211 }
3212
3213
3214 /// This function implements the transforms on div instructions that work
3215 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3216 /// used by the visitors to those instructions.
3217 /// @brief Transforms common to all three div instructions
3218 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3219   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3220
3221   // undef / X -> 0        for integer.
3222   // undef / X -> undef    for FP (the undef could be a snan).
3223   if (isa<UndefValue>(Op0)) {
3224     if (Op0->getType()->isFPOrFPVector())
3225       return ReplaceInstUsesWith(I, Op0);
3226     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3227   }
3228
3229   // X / undef -> undef
3230   if (isa<UndefValue>(Op1))
3231     return ReplaceInstUsesWith(I, Op1);
3232
3233   return 0;
3234 }
3235
3236 /// This function implements the transforms common to both integer division
3237 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3238 /// division instructions.
3239 /// @brief Common integer divide transforms
3240 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3241   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3242
3243   // (sdiv X, X) --> 1     (udiv X, X) --> 1
3244   if (Op0 == Op1) {
3245     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3246       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
3247       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3248       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3249     }
3250
3251     Constant *CI = ConstantInt::get(I.getType(), 1);
3252     return ReplaceInstUsesWith(I, CI);
3253   }
3254   
3255   if (Instruction *Common = commonDivTransforms(I))
3256     return Common;
3257   
3258   // Handle cases involving: [su]div X, (select Cond, Y, Z)
3259   // This does not apply for fdiv.
3260   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3261     return &I;
3262
3263   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3264     // div X, 1 == X
3265     if (RHS->equalsInt(1))
3266       return ReplaceInstUsesWith(I, Op0);
3267
3268     // (X / C1) / C2  -> X / (C1*C2)
3269     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3270       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3271         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3272           if (MultiplyOverflows(RHS, LHSRHS,
3273                                 I.getOpcode()==Instruction::SDiv))
3274             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3275           else 
3276             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3277                                       ConstantExpr::getMul(RHS, LHSRHS));
3278         }
3279
3280     if (!RHS->isZero()) { // avoid X udiv 0
3281       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3282         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3283           return R;
3284       if (isa<PHINode>(Op0))
3285         if (Instruction *NV = FoldOpIntoPhi(I))
3286           return NV;
3287     }
3288   }
3289
3290   // 0 / X == 0, we don't need to preserve faults!
3291   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3292     if (LHS->equalsInt(0))
3293       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3294
3295   // It can't be division by zero, hence it must be division by one.
3296   if (I.getType() == Type::getInt1Ty(*Context))
3297     return ReplaceInstUsesWith(I, Op0);
3298
3299   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3300     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3301       // div X, 1 == X
3302       if (X->isOne())
3303         return ReplaceInstUsesWith(I, Op0);
3304   }
3305
3306   return 0;
3307 }
3308
3309 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3310   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3311
3312   // Handle the integer div common cases
3313   if (Instruction *Common = commonIDivTransforms(I))
3314     return Common;
3315
3316   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3317     // X udiv C^2 -> X >> C
3318     // Check to see if this is an unsigned division with an exact power of 2,
3319     // if so, convert to a right shift.
3320     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3321       return BinaryOperator::CreateLShr(Op0, 
3322             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3323
3324     // X udiv C, where C >= signbit
3325     if (C->getValue().isNegative()) {
3326       Value *IC = Builder->CreateICmpULT( Op0, C);
3327       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3328                                 ConstantInt::get(I.getType(), 1));
3329     }
3330   }
3331
3332   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3333   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3334     if (RHSI->getOpcode() == Instruction::Shl &&
3335         isa<ConstantInt>(RHSI->getOperand(0))) {
3336       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3337       if (C1.isPowerOf2()) {
3338         Value *N = RHSI->getOperand(1);
3339         const Type *NTy = N->getType();
3340         if (uint32_t C2 = C1.logBase2())
3341           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3342         return BinaryOperator::CreateLShr(Op0, N);
3343       }
3344     }
3345   }
3346   
3347   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3348   // where C1&C2 are powers of two.
3349   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3350     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3351       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3352         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3353         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3354           // Compute the shift amounts
3355           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3356           // Construct the "on true" case of the select
3357           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3358           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3359   
3360           // Construct the "on false" case of the select
3361           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3362           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3363
3364           // construct the select instruction and return it.
3365           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3366         }
3367       }
3368   return 0;
3369 }
3370
3371 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3372   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3373
3374   // Handle the integer div common cases
3375   if (Instruction *Common = commonIDivTransforms(I))
3376     return Common;
3377
3378   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3379     // sdiv X, -1 == -X
3380     if (RHS->isAllOnesValue())
3381       return BinaryOperator::CreateNeg(Op0);
3382
3383     // sdiv X, C  -->  ashr X, log2(C)
3384     if (cast<SDivOperator>(&I)->isExact() &&
3385         RHS->getValue().isNonNegative() &&
3386         RHS->getValue().isPowerOf2()) {
3387       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3388                                             RHS->getValue().exactLogBase2());
3389       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3390     }
3391
3392     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3393     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3394       if (isa<Constant>(Sub->getOperand(0)) &&
3395           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3396           Sub->hasNoSignedWrap())
3397         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3398                                           ConstantExpr::getNeg(RHS));
3399   }
3400
3401   // If the sign bits of both operands are zero (i.e. we can prove they are
3402   // unsigned inputs), turn this into a udiv.
3403   if (I.getType()->isInteger()) {
3404     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3405     if (MaskedValueIsZero(Op0, Mask)) {
3406       if (MaskedValueIsZero(Op1, Mask)) {
3407         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3408         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3409       }
3410       ConstantInt *ShiftedInt;
3411       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3412           ShiftedInt->getValue().isPowerOf2()) {
3413         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3414         // Safe because the only negative value (1 << Y) can take on is
3415         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3416         // the sign bit set.
3417         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3418       }
3419     }
3420   }
3421   
3422   return 0;
3423 }
3424
3425 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3426   return commonDivTransforms(I);
3427 }
3428
3429 /// This function implements the transforms on rem instructions that work
3430 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3431 /// is used by the visitors to those instructions.
3432 /// @brief Transforms common to all three rem instructions
3433 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3434   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3435
3436   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3437     if (I.getType()->isFPOrFPVector())
3438       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3439     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3440   }
3441   if (isa<UndefValue>(Op1))
3442     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3443
3444   // Handle cases involving: rem X, (select Cond, Y, Z)
3445   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3446     return &I;
3447
3448   return 0;
3449 }
3450
3451 /// This function implements the transforms common to both integer remainder
3452 /// instructions (urem and srem). It is called by the visitors to those integer
3453 /// remainder instructions.
3454 /// @brief Common integer remainder transforms
3455 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3456   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3457
3458   if (Instruction *common = commonRemTransforms(I))
3459     return common;
3460
3461   // 0 % X == 0 for integer, we don't need to preserve faults!
3462   if (Constant *LHS = dyn_cast<Constant>(Op0))
3463     if (LHS->isNullValue())
3464       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3465
3466   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3467     // X % 0 == undef, we don't need to preserve faults!
3468     if (RHS->equalsInt(0))
3469       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3470     
3471     if (RHS->equalsInt(1))  // X % 1 == 0
3472       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3473
3474     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3475       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3476         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3477           return R;
3478       } else if (isa<PHINode>(Op0I)) {
3479         if (Instruction *NV = FoldOpIntoPhi(I))
3480           return NV;
3481       }
3482
3483       // See if we can fold away this rem instruction.
3484       if (SimplifyDemandedInstructionBits(I))
3485         return &I;
3486     }
3487   }
3488
3489   return 0;
3490 }
3491
3492 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3493   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3494
3495   if (Instruction *common = commonIRemTransforms(I))
3496     return common;
3497   
3498   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3499     // X urem C^2 -> X and C
3500     // Check to see if this is an unsigned remainder with an exact power of 2,
3501     // if so, convert to a bitwise and.
3502     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3503       if (C->getValue().isPowerOf2())
3504         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3505   }
3506
3507   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3508     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3509     if (RHSI->getOpcode() == Instruction::Shl &&
3510         isa<ConstantInt>(RHSI->getOperand(0))) {
3511       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3512         Constant *N1 = Constant::getAllOnesValue(I.getType());
3513         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3514         return BinaryOperator::CreateAnd(Op0, Add);
3515       }
3516     }
3517   }
3518
3519   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3520   // where C1&C2 are powers of two.
3521   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3522     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3523       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3524         // STO == 0 and SFO == 0 handled above.
3525         if ((STO->getValue().isPowerOf2()) && 
3526             (SFO->getValue().isPowerOf2())) {
3527           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3528                                               SI->getName()+".t");
3529           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3530                                                SI->getName()+".f");
3531           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3532         }
3533       }
3534   }
3535   
3536   return 0;
3537 }
3538
3539 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3540   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3541
3542   // Handle the integer rem common cases
3543   if (Instruction *Common = commonIRemTransforms(I))
3544     return Common;
3545   
3546   if (Value *RHSNeg = dyn_castNegVal(Op1))
3547     if (!isa<Constant>(RHSNeg) ||
3548         (isa<ConstantInt>(RHSNeg) &&
3549          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3550       // X % -Y -> X % Y
3551       Worklist.AddValue(I.getOperand(1));
3552       I.setOperand(1, RHSNeg);
3553       return &I;
3554     }
3555
3556   // If the sign bits of both operands are zero (i.e. we can prove they are
3557   // unsigned inputs), turn this into a urem.
3558   if (I.getType()->isInteger()) {
3559     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3560     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3561       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3562       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3563     }
3564   }
3565
3566   // If it's a constant vector, flip any negative values positive.
3567   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3568     unsigned VWidth = RHSV->getNumOperands();
3569
3570     bool hasNegative = false;
3571     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3572       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3573         if (RHS->getValue().isNegative())
3574           hasNegative = true;
3575
3576     if (hasNegative) {
3577       std::vector<Constant *> Elts(VWidth);
3578       for (unsigned i = 0; i != VWidth; ++i) {
3579         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3580           if (RHS->getValue().isNegative())
3581             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3582           else
3583             Elts[i] = RHS;
3584         }
3585       }
3586
3587       Constant *NewRHSV = ConstantVector::get(Elts);
3588       if (NewRHSV != RHSV) {
3589         Worklist.AddValue(I.getOperand(1));
3590         I.setOperand(1, NewRHSV);
3591         return &I;
3592       }
3593     }
3594   }
3595
3596   return 0;
3597 }
3598
3599 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3600   return commonRemTransforms(I);
3601 }
3602
3603 // isOneBitSet - Return true if there is exactly one bit set in the specified
3604 // constant.
3605 static bool isOneBitSet(const ConstantInt *CI) {
3606   return CI->getValue().isPowerOf2();
3607 }
3608
3609 // isHighOnes - Return true if the constant is of the form 1+0+.
3610 // This is the same as lowones(~X).
3611 static bool isHighOnes(const ConstantInt *CI) {
3612   return (~CI->getValue() + 1).isPowerOf2();
3613 }
3614
3615 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3616 /// are carefully arranged to allow folding of expressions such as:
3617 ///
3618 ///      (A < B) | (A > B) --> (A != B)
3619 ///
3620 /// Note that this is only valid if the first and second predicates have the
3621 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3622 ///
3623 /// Three bits are used to represent the condition, as follows:
3624 ///   0  A > B
3625 ///   1  A == B
3626 ///   2  A < B
3627 ///
3628 /// <=>  Value  Definition
3629 /// 000     0   Always false
3630 /// 001     1   A >  B
3631 /// 010     2   A == B
3632 /// 011     3   A >= B
3633 /// 100     4   A <  B
3634 /// 101     5   A != B
3635 /// 110     6   A <= B
3636 /// 111     7   Always true
3637 ///  
3638 static unsigned getICmpCode(const ICmpInst *ICI) {
3639   switch (ICI->getPredicate()) {
3640     // False -> 0
3641   case ICmpInst::ICMP_UGT: return 1;  // 001
3642   case ICmpInst::ICMP_SGT: return 1;  // 001
3643   case ICmpInst::ICMP_EQ:  return 2;  // 010
3644   case ICmpInst::ICMP_UGE: return 3;  // 011
3645   case ICmpInst::ICMP_SGE: return 3;  // 011
3646   case ICmpInst::ICMP_ULT: return 4;  // 100
3647   case ICmpInst::ICMP_SLT: return 4;  // 100
3648   case ICmpInst::ICMP_NE:  return 5;  // 101
3649   case ICmpInst::ICMP_ULE: return 6;  // 110
3650   case ICmpInst::ICMP_SLE: return 6;  // 110
3651     // True -> 7
3652   default:
3653     llvm_unreachable("Invalid ICmp predicate!");
3654     return 0;
3655   }
3656 }
3657
3658 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3659 /// predicate into a three bit mask. It also returns whether it is an ordered
3660 /// predicate by reference.
3661 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3662   isOrdered = false;
3663   switch (CC) {
3664   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3665   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3666   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3667   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3668   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3669   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3670   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3671   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3672   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3673   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3674   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3675   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3676   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3677   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3678     // True -> 7
3679   default:
3680     // Not expecting FCMP_FALSE and FCMP_TRUE;
3681     llvm_unreachable("Unexpected FCmp predicate!");
3682     return 0;
3683   }
3684 }
3685
3686 /// getICmpValue - This is the complement of getICmpCode, which turns an
3687 /// opcode and two operands into either a constant true or false, or a brand 
3688 /// new ICmp instruction. The sign is passed in to determine which kind
3689 /// of predicate to use in the new icmp instruction.
3690 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3691                            LLVMContext *Context) {
3692   switch (code) {
3693   default: llvm_unreachable("Illegal ICmp code!");
3694   case  0: return ConstantInt::getFalse(*Context);
3695   case  1: 
3696     if (sign)
3697       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3698     else
3699       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3700   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3701   case  3: 
3702     if (sign)
3703       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3704     else
3705       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3706   case  4: 
3707     if (sign)
3708       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3709     else
3710       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3711   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3712   case  6: 
3713     if (sign)
3714       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3715     else
3716       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3717   case  7: return ConstantInt::getTrue(*Context);
3718   }
3719 }
3720
3721 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3722 /// opcode and two operands into either a FCmp instruction. isordered is passed
3723 /// in to determine which kind of predicate to use in the new fcmp instruction.
3724 static Value *getFCmpValue(bool isordered, unsigned code,
3725                            Value *LHS, Value *RHS, LLVMContext *Context) {
3726   switch (code) {
3727   default: llvm_unreachable("Illegal FCmp code!");
3728   case  0:
3729     if (isordered)
3730       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3731     else
3732       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3733   case  1: 
3734     if (isordered)
3735       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3736     else
3737       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3738   case  2: 
3739     if (isordered)
3740       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3741     else
3742       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3743   case  3: 
3744     if (isordered)
3745       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3746     else
3747       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3748   case  4: 
3749     if (isordered)
3750       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3751     else
3752       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3753   case  5: 
3754     if (isordered)
3755       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3756     else
3757       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3758   case  6: 
3759     if (isordered)
3760       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3761     else
3762       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3763   case  7: return ConstantInt::getTrue(*Context);
3764   }
3765 }
3766
3767 /// PredicatesFoldable - Return true if both predicates match sign or if at
3768 /// least one of them is an equality comparison (which is signless).
3769 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3770   return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3771          (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3772          (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
3773 }
3774
3775 namespace { 
3776 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3777 struct FoldICmpLogical {
3778   InstCombiner &IC;
3779   Value *LHS, *RHS;
3780   ICmpInst::Predicate pred;
3781   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3782     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3783       pred(ICI->getPredicate()) {}
3784   bool shouldApply(Value *V) const {
3785     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3786       if (PredicatesFoldable(pred, ICI->getPredicate()))
3787         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3788                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3789     return false;
3790   }
3791   Instruction *apply(Instruction &Log) const {
3792     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3793     if (ICI->getOperand(0) != LHS) {
3794       assert(ICI->getOperand(1) == LHS);
3795       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3796     }
3797
3798     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3799     unsigned LHSCode = getICmpCode(ICI);
3800     unsigned RHSCode = getICmpCode(RHSICI);
3801     unsigned Code;
3802     switch (Log.getOpcode()) {
3803     case Instruction::And: Code = LHSCode & RHSCode; break;
3804     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3805     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3806     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3807     }
3808
3809     bool isSigned = RHSICI->isSigned() || ICI->isSigned();
3810     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3811     if (Instruction *I = dyn_cast<Instruction>(RV))
3812       return I;
3813     // Otherwise, it's a constant boolean value...
3814     return IC.ReplaceInstUsesWith(Log, RV);
3815   }
3816 };
3817 } // end anonymous namespace
3818
3819 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3820 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3821 // guaranteed to be a binary operator.
3822 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3823                                     ConstantInt *OpRHS,
3824                                     ConstantInt *AndRHS,
3825                                     BinaryOperator &TheAnd) {
3826   Value *X = Op->getOperand(0);
3827   Constant *Together = 0;
3828   if (!Op->isShift())
3829     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3830
3831   switch (Op->getOpcode()) {
3832   case Instruction::Xor:
3833     if (Op->hasOneUse()) {
3834       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3835       Value *And = Builder->CreateAnd(X, AndRHS);
3836       And->takeName(Op);
3837       return BinaryOperator::CreateXor(And, Together);
3838     }
3839     break;
3840   case Instruction::Or:
3841     if (Together == AndRHS) // (X | C) & C --> C
3842       return ReplaceInstUsesWith(TheAnd, AndRHS);
3843
3844     if (Op->hasOneUse() && Together != OpRHS) {
3845       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3846       Value *Or = Builder->CreateOr(X, Together);
3847       Or->takeName(Op);
3848       return BinaryOperator::CreateAnd(Or, AndRHS);
3849     }
3850     break;
3851   case Instruction::Add:
3852     if (Op->hasOneUse()) {
3853       // Adding a one to a single bit bit-field should be turned into an XOR
3854       // of the bit.  First thing to check is to see if this AND is with a
3855       // single bit constant.
3856       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3857
3858       // If there is only one bit set...
3859       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3860         // Ok, at this point, we know that we are masking the result of the
3861         // ADD down to exactly one bit.  If the constant we are adding has
3862         // no bits set below this bit, then we can eliminate the ADD.
3863         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3864
3865         // Check to see if any bits below the one bit set in AndRHSV are set.
3866         if ((AddRHS & (AndRHSV-1)) == 0) {
3867           // If not, the only thing that can effect the output of the AND is
3868           // the bit specified by AndRHSV.  If that bit is set, the effect of
3869           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3870           // no effect.
3871           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3872             TheAnd.setOperand(0, X);
3873             return &TheAnd;
3874           } else {
3875             // Pull the XOR out of the AND.
3876             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3877             NewAnd->takeName(Op);
3878             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3879           }
3880         }
3881       }
3882     }
3883     break;
3884
3885   case Instruction::Shl: {
3886     // We know that the AND will not produce any of the bits shifted in, so if
3887     // the anded constant includes them, clear them now!
3888     //
3889     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3890     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3891     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3892     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3893
3894     if (CI->getValue() == ShlMask) { 
3895     // Masking out bits that the shift already masks
3896       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3897     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3898       TheAnd.setOperand(1, CI);
3899       return &TheAnd;
3900     }
3901     break;
3902   }
3903   case Instruction::LShr:
3904   {
3905     // We know that the AND will not produce any of the bits shifted in, so if
3906     // the anded constant includes them, clear them now!  This only applies to
3907     // unsigned shifts, because a signed shr may bring in set bits!
3908     //
3909     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3910     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3911     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3912     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3913
3914     if (CI->getValue() == ShrMask) {   
3915     // Masking out bits that the shift already masks.
3916       return ReplaceInstUsesWith(TheAnd, Op);
3917     } else if (CI != AndRHS) {
3918       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3919       return &TheAnd;
3920     }
3921     break;
3922   }
3923   case Instruction::AShr:
3924     // Signed shr.
3925     // See if this is shifting in some sign extension, then masking it out
3926     // with an and.
3927     if (Op->hasOneUse()) {
3928       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3929       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3930       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3931       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3932       if (C == AndRHS) {          // Masking out bits shifted in.
3933         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3934         // Make the argument unsigned.
3935         Value *ShVal = Op->getOperand(0);
3936         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3937         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3938       }
3939     }
3940     break;
3941   }
3942   return 0;
3943 }
3944
3945
3946 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3947 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3948 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3949 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3950 /// insert new instructions.
3951 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3952                                            bool isSigned, bool Inside, 
3953                                            Instruction &IB) {
3954   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3955             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3956          "Lo is not <= Hi in range emission code!");
3957     
3958   if (Inside) {
3959     if (Lo == Hi)  // Trivially false.
3960       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3961
3962     // V >= Min && V < Hi --> V < Hi
3963     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3964       ICmpInst::Predicate pred = (isSigned ? 
3965         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3966       return new ICmpInst(pred, V, Hi);
3967     }
3968
3969     // Emit V-Lo <u Hi-Lo
3970     Constant *NegLo = ConstantExpr::getNeg(Lo);
3971     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3972     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3973     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3974   }
3975
3976   if (Lo == Hi)  // Trivially true.
3977     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3978
3979   // V < Min || V >= Hi -> V > Hi-1
3980   Hi = SubOne(cast<ConstantInt>(Hi));
3981   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3982     ICmpInst::Predicate pred = (isSigned ? 
3983         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3984     return new ICmpInst(pred, V, Hi);
3985   }
3986
3987   // Emit V-Lo >u Hi-1-Lo
3988   // Note that Hi has already had one subtracted from it, above.
3989   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3990   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3991   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3992   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3993 }
3994
3995 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3996 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3997 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3998 // not, since all 1s are not contiguous.
3999 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
4000   const APInt& V = Val->getValue();
4001   uint32_t BitWidth = Val->getType()->getBitWidth();
4002   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
4003
4004   // look for the first zero bit after the run of ones
4005   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
4006   // look for the first non-zero bit
4007   ME = V.getActiveBits(); 
4008   return true;
4009 }
4010
4011 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4012 /// where isSub determines whether the operator is a sub.  If we can fold one of
4013 /// the following xforms:
4014 /// 
4015 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4016 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4017 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4018 ///
4019 /// return (A +/- B).
4020 ///
4021 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
4022                                         ConstantInt *Mask, bool isSub,
4023                                         Instruction &I) {
4024   Instruction *LHSI = dyn_cast<Instruction>(LHS);
4025   if (!LHSI || LHSI->getNumOperands() != 2 ||
4026       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4027
4028   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4029
4030   switch (LHSI->getOpcode()) {
4031   default: return 0;
4032   case Instruction::And:
4033     if (ConstantExpr::getAnd(N, Mask) == Mask) {
4034       // If the AndRHS is a power of two minus one (0+1+), this is simple.
4035       if ((Mask->getValue().countLeadingZeros() + 
4036            Mask->getValue().countPopulation()) == 
4037           Mask->getValue().getBitWidth())
4038         break;
4039
4040       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4041       // part, we don't need any explicit masks to take them out of A.  If that
4042       // is all N is, ignore it.
4043       uint32_t MB = 0, ME = 0;
4044       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
4045         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
4046         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4047         if (MaskedValueIsZero(RHS, Mask))
4048           break;
4049       }
4050     }
4051     return 0;
4052   case Instruction::Or:
4053   case Instruction::Xor:
4054     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4055     if ((Mask->getValue().countLeadingZeros() + 
4056          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
4057         && ConstantExpr::getAnd(N, Mask)->isNullValue())
4058       break;
4059     return 0;
4060   }
4061   
4062   if (isSub)
4063     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4064   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
4065 }
4066
4067 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4068 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4069                                           ICmpInst *LHS, ICmpInst *RHS) {
4070   // (icmp eq A, null) & (icmp eq B, null) -->
4071   //     (icmp eq (ptrtoint(A)|ptrtoint(B)), 0)
4072   if (TD &&
4073       LHS->getPredicate() == ICmpInst::ICMP_EQ &&
4074       RHS->getPredicate() == ICmpInst::ICMP_EQ &&
4075       isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4076       isa<ConstantPointerNull>(RHS->getOperand(1))) {
4077     const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4078     Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4079     Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4080     Value *NewOr = Builder->CreateOr(A, B);
4081     return new ICmpInst(ICmpInst::ICMP_EQ, NewOr,
4082                         Constant::getNullValue(IntPtrTy));
4083   }
4084   
4085   Value *Val, *Val2;
4086   ConstantInt *LHSCst, *RHSCst;
4087   ICmpInst::Predicate LHSCC, RHSCC;
4088   
4089   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
4090   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4091                          m_ConstantInt(LHSCst))) ||
4092       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4093                          m_ConstantInt(RHSCst))))
4094     return 0;
4095   
4096   if (LHSCst == RHSCst && LHSCC == RHSCC) {
4097     // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4098     // where C is a power of 2
4099     if (LHSCC == ICmpInst::ICMP_ULT &&
4100         LHSCst->getValue().isPowerOf2()) {
4101       Value *NewOr = Builder->CreateOr(Val, Val2);
4102       return new ICmpInst(LHSCC, NewOr, LHSCst);
4103     }
4104     
4105     // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4106     if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4107       Value *NewOr = Builder->CreateOr(Val, Val2);
4108       return new ICmpInst(LHSCC, NewOr, LHSCst);
4109     }
4110   }
4111   
4112   // From here on, we only handle:
4113   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4114   if (Val != Val2) return 0;
4115   
4116   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4117   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4118       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4119       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4120       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4121     return 0;
4122   
4123   // We can't fold (ugt x, C) & (sgt x, C2).
4124   if (!PredicatesFoldable(LHSCC, RHSCC))
4125     return 0;
4126     
4127   // Ensure that the larger constant is on the RHS.
4128   bool ShouldSwap;
4129   if (CmpInst::isSigned(LHSCC) ||
4130       (ICmpInst::isEquality(LHSCC) && 
4131        CmpInst::isSigned(RHSCC)))
4132     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4133   else
4134     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4135     
4136   if (ShouldSwap) {
4137     std::swap(LHS, RHS);
4138     std::swap(LHSCst, RHSCst);
4139     std::swap(LHSCC, RHSCC);
4140   }
4141
4142   // At this point, we know we have have two icmp instructions
4143   // comparing a value against two constants and and'ing the result
4144   // together.  Because of the above check, we know that we only have
4145   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
4146   // (from the FoldICmpLogical check above), that the two constants 
4147   // are not equal and that the larger constant is on the RHS
4148   assert(LHSCst != RHSCst && "Compares not folded above?");
4149
4150   switch (LHSCC) {
4151   default: llvm_unreachable("Unknown integer condition code!");
4152   case ICmpInst::ICMP_EQ:
4153     switch (RHSCC) {
4154     default: llvm_unreachable("Unknown integer condition code!");
4155     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
4156     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
4157     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
4158       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4159     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
4160     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
4161     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
4162       return ReplaceInstUsesWith(I, LHS);
4163     }
4164   case ICmpInst::ICMP_NE:
4165     switch (RHSCC) {
4166     default: llvm_unreachable("Unknown integer condition code!");
4167     case ICmpInst::ICMP_ULT:
4168       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4169         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
4170       break;                        // (X != 13 & X u< 15) -> no change
4171     case ICmpInst::ICMP_SLT:
4172       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4173         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
4174       break;                        // (X != 13 & X s< 15) -> no change
4175     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
4176     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
4177     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
4178       return ReplaceInstUsesWith(I, RHS);
4179     case ICmpInst::ICMP_NE:
4180       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4181         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4182         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4183         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4184                             ConstantInt::get(Add->getType(), 1));
4185       }
4186       break;                        // (X != 13 & X != 15) -> no change
4187     }
4188     break;
4189   case ICmpInst::ICMP_ULT:
4190     switch (RHSCC) {
4191     default: llvm_unreachable("Unknown integer condition code!");
4192     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
4193     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
4194       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4195     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
4196       break;
4197     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
4198     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
4199       return ReplaceInstUsesWith(I, LHS);
4200     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
4201       break;
4202     }
4203     break;
4204   case ICmpInst::ICMP_SLT:
4205     switch (RHSCC) {
4206     default: llvm_unreachable("Unknown integer condition code!");
4207     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
4208     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
4209       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4210     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
4211       break;
4212     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
4213     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
4214       return ReplaceInstUsesWith(I, LHS);
4215     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
4216       break;
4217     }
4218     break;
4219   case ICmpInst::ICMP_UGT:
4220     switch (RHSCC) {
4221     default: llvm_unreachable("Unknown integer condition code!");
4222     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
4223     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
4224       return ReplaceInstUsesWith(I, RHS);
4225     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
4226       break;
4227     case ICmpInst::ICMP_NE:
4228       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4229         return new ICmpInst(LHSCC, Val, RHSCst);
4230       break;                        // (X u> 13 & X != 15) -> no change
4231     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
4232       return InsertRangeTest(Val, AddOne(LHSCst),
4233                              RHSCst, false, true, I);
4234     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
4235       break;
4236     }
4237     break;
4238   case ICmpInst::ICMP_SGT:
4239     switch (RHSCC) {
4240     default: llvm_unreachable("Unknown integer condition code!");
4241     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
4242     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
4243       return ReplaceInstUsesWith(I, RHS);
4244     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
4245       break;
4246     case ICmpInst::ICMP_NE:
4247       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4248         return new ICmpInst(LHSCC, Val, RHSCst);
4249       break;                        // (X s> 13 & X != 15) -> no change
4250     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
4251       return InsertRangeTest(Val, AddOne(LHSCst),
4252                              RHSCst, true, true, I);
4253     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
4254       break;
4255     }
4256     break;
4257   }
4258  
4259   return 0;
4260 }
4261
4262 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4263                                           FCmpInst *RHS) {
4264   
4265   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4266       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4267     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4268     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4269       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4270         // If either of the constants are nans, then the whole thing returns
4271         // false.
4272         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4273           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4274         return new FCmpInst(FCmpInst::FCMP_ORD,
4275                             LHS->getOperand(0), RHS->getOperand(0));
4276       }
4277     
4278     // Handle vector zeros.  This occurs because the canonical form of
4279     // "fcmp ord x,x" is "fcmp ord x, 0".
4280     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4281         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4282       return new FCmpInst(FCmpInst::FCMP_ORD,
4283                           LHS->getOperand(0), RHS->getOperand(0));
4284     return 0;
4285   }
4286   
4287   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4288   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4289   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4290   
4291   
4292   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4293     // Swap RHS operands to match LHS.
4294     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4295     std::swap(Op1LHS, Op1RHS);
4296   }
4297   
4298   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4299     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4300     if (Op0CC == Op1CC)
4301       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4302     
4303     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
4304       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4305     if (Op0CC == FCmpInst::FCMP_TRUE)
4306       return ReplaceInstUsesWith(I, RHS);
4307     if (Op1CC == FCmpInst::FCMP_TRUE)
4308       return ReplaceInstUsesWith(I, LHS);
4309     
4310     bool Op0Ordered;
4311     bool Op1Ordered;
4312     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4313     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4314     if (Op1Pred == 0) {
4315       std::swap(LHS, RHS);
4316       std::swap(Op0Pred, Op1Pred);
4317       std::swap(Op0Ordered, Op1Ordered);
4318     }
4319     if (Op0Pred == 0) {
4320       // uno && ueq -> uno && (uno || eq) -> ueq
4321       // ord && olt -> ord && (ord && lt) -> olt
4322       if (Op0Ordered == Op1Ordered)
4323         return ReplaceInstUsesWith(I, RHS);
4324       
4325       // uno && oeq -> uno && (ord && eq) -> false
4326       // uno && ord -> false
4327       if (!Op0Ordered)
4328         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4329       // ord && ueq -> ord && (uno || eq) -> oeq
4330       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4331                                             Op0LHS, Op0RHS, Context));
4332     }
4333   }
4334
4335   return 0;
4336 }
4337
4338
4339 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4340   bool Changed = SimplifyCommutative(I);
4341   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4342
4343   if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4344     return ReplaceInstUsesWith(I, V);
4345
4346   // See if we can simplify any instructions used by the instruction whose sole 
4347   // purpose is to compute bits we don't care about.
4348   if (SimplifyDemandedInstructionBits(I))
4349     return &I;
4350   
4351
4352   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4353     const APInt &AndRHSMask = AndRHS->getValue();
4354     APInt NotAndRHS(~AndRHSMask);
4355
4356     // Optimize a variety of ((val OP C1) & C2) combinations...
4357     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4358       Value *Op0LHS = Op0I->getOperand(0);
4359       Value *Op0RHS = Op0I->getOperand(1);
4360       switch (Op0I->getOpcode()) {
4361       default: break;
4362       case Instruction::Xor:
4363       case Instruction::Or:
4364         // If the mask is only needed on one incoming arm, push it up.
4365         if (!Op0I->hasOneUse()) break;
4366           
4367         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4368           // Not masking anything out for the LHS, move to RHS.
4369           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4370                                              Op0RHS->getName()+".masked");
4371           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4372         }
4373         if (!isa<Constant>(Op0RHS) &&
4374             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4375           // Not masking anything out for the RHS, move to LHS.
4376           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4377                                              Op0LHS->getName()+".masked");
4378           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
4379         }
4380
4381         break;
4382       case Instruction::Add:
4383         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4384         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4385         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4386         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4387           return BinaryOperator::CreateAnd(V, AndRHS);
4388         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4389           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4390         break;
4391
4392       case Instruction::Sub:
4393         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4394         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4395         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4396         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4397           return BinaryOperator::CreateAnd(V, AndRHS);
4398
4399         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4400         // has 1's for all bits that the subtraction with A might affect.
4401         if (Op0I->hasOneUse()) {
4402           uint32_t BitWidth = AndRHSMask.getBitWidth();
4403           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4404           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4405
4406           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4407           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4408               MaskedValueIsZero(Op0LHS, Mask)) {
4409             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4410             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4411           }
4412         }
4413         break;
4414
4415       case Instruction::Shl:
4416       case Instruction::LShr:
4417         // (1 << x) & 1 --> zext(x == 0)
4418         // (1 >> x) & 1 --> zext(x == 0)
4419         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4420           Value *NewICmp =
4421             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4422           return new ZExtInst(NewICmp, I.getType());
4423         }
4424         break;
4425       }
4426
4427       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4428         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4429           return Res;
4430     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4431       // If this is an integer truncation or change from signed-to-unsigned, and
4432       // if the source is an and/or with immediate, transform it.  This
4433       // frequently occurs for bitfield accesses.
4434       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4435         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4436             CastOp->getNumOperands() == 2)
4437           if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
4438             if (CastOp->getOpcode() == Instruction::And) {
4439               // Change: and (cast (and X, C1) to T), C2
4440               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4441               // This will fold the two constants together, which may allow 
4442               // other simplifications.
4443               Value *NewCast = Builder->CreateTruncOrBitCast(
4444                 CastOp->getOperand(0), I.getType(), 
4445                 CastOp->getName()+".shrunk");
4446               // trunc_or_bitcast(C1)&C2
4447               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4448               C3 = ConstantExpr::getAnd(C3, AndRHS);
4449               return BinaryOperator::CreateAnd(NewCast, C3);
4450             } else if (CastOp->getOpcode() == Instruction::Or) {
4451               // Change: and (cast (or X, C1) to T), C2
4452               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4453               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4454               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4455                 // trunc(C1)&C2
4456                 return ReplaceInstUsesWith(I, AndRHS);
4457             }
4458           }
4459       }
4460     }
4461
4462     // Try to fold constant and into select arguments.
4463     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4464       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4465         return R;
4466     if (isa<PHINode>(Op0))
4467       if (Instruction *NV = FoldOpIntoPhi(I))
4468         return NV;
4469   }
4470
4471
4472   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4473   if (Value *Op0NotVal = dyn_castNotVal(Op0))
4474     if (Value *Op1NotVal = dyn_castNotVal(Op1))
4475       if (Op0->hasOneUse() && Op1->hasOneUse()) {
4476         Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4477                                       I.getName()+".demorgan");
4478         return BinaryOperator::CreateNot(Or);
4479       }
4480
4481   {
4482     Value *A = 0, *B = 0, *C = 0, *D = 0;
4483     // (A|B) & ~(A&B) -> A^B
4484     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4485         match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4486         ((A == C && B == D) || (A == D && B == C)))
4487       return BinaryOperator::CreateXor(A, B);
4488     
4489     // ~(A&B) & (A|B) -> A^B
4490     if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4491         match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4492         ((A == C && B == D) || (A == D && B == C)))
4493       return BinaryOperator::CreateXor(A, B);
4494     
4495     if (Op0->hasOneUse() &&
4496         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4497       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4498         I.swapOperands();     // Simplify below
4499         std::swap(Op0, Op1);
4500       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4501         cast<BinaryOperator>(Op0)->swapOperands();
4502         I.swapOperands();     // Simplify below
4503         std::swap(Op0, Op1);
4504       }
4505     }
4506
4507     if (Op1->hasOneUse() &&
4508         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4509       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4510         cast<BinaryOperator>(Op1)->swapOperands();
4511         std::swap(A, B);
4512       }
4513       if (A == Op0)                                // A&(A^B) -> A & ~B
4514         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4515     }
4516
4517     // (A&((~A)|B)) -> A&B
4518     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4519         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4520       return BinaryOperator::CreateAnd(A, Op1);
4521     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4522         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4523       return BinaryOperator::CreateAnd(A, Op0);
4524   }
4525   
4526   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4527     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4528     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4529       return R;
4530
4531     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4532       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4533         return Res;
4534   }
4535
4536   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4537   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4538     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4539       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4540         const Type *SrcTy = Op0C->getOperand(0)->getType();
4541         if (SrcTy == Op1C->getOperand(0)->getType() &&
4542             SrcTy->isIntOrIntVector() &&
4543             // Only do this if the casts both really cause code to be generated.
4544             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4545                               I.getType(), TD) &&
4546             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4547                               I.getType(), TD)) {
4548           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4549                                             Op1C->getOperand(0), I.getName());
4550           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4551         }
4552       }
4553     
4554   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4555   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4556     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4557       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4558           SI0->getOperand(1) == SI1->getOperand(1) &&
4559           (SI0->hasOneUse() || SI1->hasOneUse())) {
4560         Value *NewOp =
4561           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4562                              SI0->getName());
4563         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4564                                       SI1->getOperand(1));
4565       }
4566   }
4567
4568   // If and'ing two fcmp, try combine them into one.
4569   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4570     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4571       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4572         return Res;
4573   }
4574
4575   return Changed ? &I : 0;
4576 }
4577
4578 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4579 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4580 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4581 /// the expression came from the corresponding "byte swapped" byte in some other
4582 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4583 /// we know that the expression deposits the low byte of %X into the high byte
4584 /// of the bswap result and that all other bytes are zero.  This expression is
4585 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4586 /// match.
4587 ///
4588 /// This function returns true if the match was unsuccessful and false if so.
4589 /// On entry to the function the "OverallLeftShift" is a signed integer value
4590 /// indicating the number of bytes that the subexpression is later shifted.  For
4591 /// example, if the expression is later right shifted by 16 bits, the
4592 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4593 /// byte of ByteValues is actually being set.
4594 ///
4595 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4596 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4597 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4598 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4599 /// always in the local (OverallLeftShift) coordinate space.
4600 ///
4601 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4602                               SmallVector<Value*, 8> &ByteValues) {
4603   if (Instruction *I = dyn_cast<Instruction>(V)) {
4604     // If this is an or instruction, it may be an inner node of the bswap.
4605     if (I->getOpcode() == Instruction::Or) {
4606       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4607                                ByteValues) ||
4608              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4609                                ByteValues);
4610     }
4611   
4612     // If this is a logical shift by a constant multiple of 8, recurse with
4613     // OverallLeftShift and ByteMask adjusted.
4614     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4615       unsigned ShAmt = 
4616         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4617       // Ensure the shift amount is defined and of a byte value.
4618       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4619         return true;
4620
4621       unsigned ByteShift = ShAmt >> 3;
4622       if (I->getOpcode() == Instruction::Shl) {
4623         // X << 2 -> collect(X, +2)
4624         OverallLeftShift += ByteShift;
4625         ByteMask >>= ByteShift;
4626       } else {
4627         // X >>u 2 -> collect(X, -2)
4628         OverallLeftShift -= ByteShift;
4629         ByteMask <<= ByteShift;
4630         ByteMask &= (~0U >> (32-ByteValues.size()));
4631       }
4632
4633       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4634       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4635
4636       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4637                                ByteValues);
4638     }
4639
4640     // If this is a logical 'and' with a mask that clears bytes, clear the
4641     // corresponding bytes in ByteMask.
4642     if (I->getOpcode() == Instruction::And &&
4643         isa<ConstantInt>(I->getOperand(1))) {
4644       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4645       unsigned NumBytes = ByteValues.size();
4646       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4647       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4648       
4649       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4650         // If this byte is masked out by a later operation, we don't care what
4651         // the and mask is.
4652         if ((ByteMask & (1 << i)) == 0)
4653           continue;
4654         
4655         // If the AndMask is all zeros for this byte, clear the bit.
4656         APInt MaskB = AndMask & Byte;
4657         if (MaskB == 0) {
4658           ByteMask &= ~(1U << i);
4659           continue;
4660         }
4661         
4662         // If the AndMask is not all ones for this byte, it's not a bytezap.
4663         if (MaskB != Byte)
4664           return true;
4665
4666         // Otherwise, this byte is kept.
4667       }
4668
4669       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4670                                ByteValues);
4671     }
4672   }
4673   
4674   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4675   // the input value to the bswap.  Some observations: 1) if more than one byte
4676   // is demanded from this input, then it could not be successfully assembled
4677   // into a byteswap.  At least one of the two bytes would not be aligned with
4678   // their ultimate destination.
4679   if (!isPowerOf2_32(ByteMask)) return true;
4680   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4681   
4682   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4683   // is demanded, it needs to go into byte 0 of the result.  This means that the
4684   // byte needs to be shifted until it lands in the right byte bucket.  The
4685   // shift amount depends on the position: if the byte is coming from the high
4686   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4687   // low part, it must be shifted left.
4688   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4689   if (InputByteNo < ByteValues.size()/2) {
4690     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4691       return true;
4692   } else {
4693     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4694       return true;
4695   }
4696   
4697   // If the destination byte value is already defined, the values are or'd
4698   // together, which isn't a bswap (unless it's an or of the same bits).
4699   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4700     return true;
4701   ByteValues[DestByteNo] = V;
4702   return false;
4703 }
4704
4705 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4706 /// If so, insert the new bswap intrinsic and return it.
4707 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4708   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4709   if (!ITy || ITy->getBitWidth() % 16 || 
4710       // ByteMask only allows up to 32-byte values.
4711       ITy->getBitWidth() > 32*8) 
4712     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4713   
4714   /// ByteValues - For each byte of the result, we keep track of which value
4715   /// defines each byte.
4716   SmallVector<Value*, 8> ByteValues;
4717   ByteValues.resize(ITy->getBitWidth()/8);
4718     
4719   // Try to find all the pieces corresponding to the bswap.
4720   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4721   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4722     return 0;
4723   
4724   // Check to see if all of the bytes come from the same value.
4725   Value *V = ByteValues[0];
4726   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4727   
4728   // Check to make sure that all of the bytes come from the same value.
4729   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4730     if (ByteValues[i] != V)
4731       return 0;
4732   const Type *Tys[] = { ITy };
4733   Module *M = I.getParent()->getParent()->getParent();
4734   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4735   return CallInst::Create(F, V);
4736 }
4737
4738 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4739 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4740 /// we can simplify this expression to "cond ? C : D or B".
4741 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4742                                          Value *C, Value *D,
4743                                          LLVMContext *Context) {
4744   // If A is not a select of -1/0, this cannot match.
4745   Value *Cond = 0;
4746   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4747     return 0;
4748
4749   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4750   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4751     return SelectInst::Create(Cond, C, B);
4752   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4753     return SelectInst::Create(Cond, C, B);
4754   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4755   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4756     return SelectInst::Create(Cond, C, D);
4757   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4758     return SelectInst::Create(Cond, C, D);
4759   return 0;
4760 }
4761
4762 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4763 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4764                                          ICmpInst *LHS, ICmpInst *RHS) {
4765   // (icmp ne A, null) | (icmp ne B, null) -->
4766   //     (icmp ne (ptrtoint(A)|ptrtoint(B)), 0)
4767   if (TD &&
4768       LHS->getPredicate() == ICmpInst::ICMP_NE &&
4769       RHS->getPredicate() == ICmpInst::ICMP_NE &&
4770       isa<ConstantPointerNull>(LHS->getOperand(1)) &&
4771       isa<ConstantPointerNull>(RHS->getOperand(1))) {
4772     const Type *IntPtrTy = TD->getIntPtrType(I.getContext());
4773     Value *A = Builder->CreatePtrToInt(LHS->getOperand(0), IntPtrTy);
4774     Value *B = Builder->CreatePtrToInt(RHS->getOperand(0), IntPtrTy);
4775     Value *NewOr = Builder->CreateOr(A, B);
4776     return new ICmpInst(ICmpInst::ICMP_NE, NewOr,
4777                         Constant::getNullValue(IntPtrTy));
4778   }
4779   
4780   Value *Val, *Val2;
4781   ConstantInt *LHSCst, *RHSCst;
4782   ICmpInst::Predicate LHSCC, RHSCC;
4783   
4784   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4785   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4786       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4787     return 0;
4788
4789   
4790   // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4791   if (LHSCst == RHSCst && LHSCC == RHSCC &&
4792       LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4793     Value *NewOr = Builder->CreateOr(Val, Val2);
4794     return new ICmpInst(LHSCC, NewOr, LHSCst);
4795   }
4796   
4797   // From here on, we only handle:
4798   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4799   if (Val != Val2) return 0;
4800   
4801   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4802   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4803       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4804       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4805       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4806     return 0;
4807   
4808   // We can't fold (ugt x, C) | (sgt x, C2).
4809   if (!PredicatesFoldable(LHSCC, RHSCC))
4810     return 0;
4811   
4812   // Ensure that the larger constant is on the RHS.
4813   bool ShouldSwap;
4814   if (CmpInst::isSigned(LHSCC) ||
4815       (ICmpInst::isEquality(LHSCC) && 
4816        CmpInst::isSigned(RHSCC)))
4817     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4818   else
4819     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4820   
4821   if (ShouldSwap) {
4822     std::swap(LHS, RHS);
4823     std::swap(LHSCst, RHSCst);
4824     std::swap(LHSCC, RHSCC);
4825   }
4826   
4827   // At this point, we know we have have two icmp instructions
4828   // comparing a value against two constants and or'ing the result
4829   // together.  Because of the above check, we know that we only have
4830   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4831   // FoldICmpLogical check above), that the two constants are not
4832   // equal.
4833   assert(LHSCst != RHSCst && "Compares not folded above?");
4834
4835   switch (LHSCC) {
4836   default: llvm_unreachable("Unknown integer condition code!");
4837   case ICmpInst::ICMP_EQ:
4838     switch (RHSCC) {
4839     default: llvm_unreachable("Unknown integer condition code!");
4840     case ICmpInst::ICMP_EQ:
4841       if (LHSCst == SubOne(RHSCst)) {
4842         // (X == 13 | X == 14) -> X-13 <u 2
4843         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4844         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4845         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4846         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4847       }
4848       break;                         // (X == 13 | X == 15) -> no change
4849     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4850     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4851       break;
4852     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4853     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4854     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4855       return ReplaceInstUsesWith(I, RHS);
4856     }
4857     break;
4858   case ICmpInst::ICMP_NE:
4859     switch (RHSCC) {
4860     default: llvm_unreachable("Unknown integer condition code!");
4861     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4862     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4863     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4864       return ReplaceInstUsesWith(I, LHS);
4865     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4866     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4867     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4868       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4869     }
4870     break;
4871   case ICmpInst::ICMP_ULT:
4872     switch (RHSCC) {
4873     default: llvm_unreachable("Unknown integer condition code!");
4874     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4875       break;
4876     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4877       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4878       // this can cause overflow.
4879       if (RHSCst->isMaxValue(false))
4880         return ReplaceInstUsesWith(I, LHS);
4881       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4882                              false, false, I);
4883     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4884       break;
4885     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4886     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4887       return ReplaceInstUsesWith(I, RHS);
4888     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4889       break;
4890     }
4891     break;
4892   case ICmpInst::ICMP_SLT:
4893     switch (RHSCC) {
4894     default: llvm_unreachable("Unknown integer condition code!");
4895     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4896       break;
4897     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4898       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4899       // this can cause overflow.
4900       if (RHSCst->isMaxValue(true))
4901         return ReplaceInstUsesWith(I, LHS);
4902       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4903                              true, false, I);
4904     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4905       break;
4906     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4907     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4908       return ReplaceInstUsesWith(I, RHS);
4909     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4910       break;
4911     }
4912     break;
4913   case ICmpInst::ICMP_UGT:
4914     switch (RHSCC) {
4915     default: llvm_unreachable("Unknown integer condition code!");
4916     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4917     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4918       return ReplaceInstUsesWith(I, LHS);
4919     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4920       break;
4921     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4922     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4923       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4924     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4925       break;
4926     }
4927     break;
4928   case ICmpInst::ICMP_SGT:
4929     switch (RHSCC) {
4930     default: llvm_unreachable("Unknown integer condition code!");
4931     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4932     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4933       return ReplaceInstUsesWith(I, LHS);
4934     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4935       break;
4936     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4937     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4938       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4939     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4940       break;
4941     }
4942     break;
4943   }
4944   return 0;
4945 }
4946
4947 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4948                                          FCmpInst *RHS) {
4949   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4950       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4951       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4952     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4953       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4954         // If either of the constants are nans, then the whole thing returns
4955         // true.
4956         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4957           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4958         
4959         // Otherwise, no need to compare the two constants, compare the
4960         // rest.
4961         return new FCmpInst(FCmpInst::FCMP_UNO,
4962                             LHS->getOperand(0), RHS->getOperand(0));
4963       }
4964     
4965     // Handle vector zeros.  This occurs because the canonical form of
4966     // "fcmp uno x,x" is "fcmp uno x, 0".
4967     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4968         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4969       return new FCmpInst(FCmpInst::FCMP_UNO,
4970                           LHS->getOperand(0), RHS->getOperand(0));
4971     
4972     return 0;
4973   }
4974   
4975   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4976   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4977   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4978   
4979   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4980     // Swap RHS operands to match LHS.
4981     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4982     std::swap(Op1LHS, Op1RHS);
4983   }
4984   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4985     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4986     if (Op0CC == Op1CC)
4987       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4988                           Op0LHS, Op0RHS);
4989     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4990       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4991     if (Op0CC == FCmpInst::FCMP_FALSE)
4992       return ReplaceInstUsesWith(I, RHS);
4993     if (Op1CC == FCmpInst::FCMP_FALSE)
4994       return ReplaceInstUsesWith(I, LHS);
4995     bool Op0Ordered;
4996     bool Op1Ordered;
4997     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4998     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4999     if (Op0Ordered == Op1Ordered) {
5000       // If both are ordered or unordered, return a new fcmp with
5001       // or'ed predicates.
5002       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5003                                Op0LHS, Op0RHS, Context);
5004       if (Instruction *I = dyn_cast<Instruction>(RV))
5005         return I;
5006       // Otherwise, it's a constant boolean value...
5007       return ReplaceInstUsesWith(I, RV);
5008     }
5009   }
5010   return 0;
5011 }
5012
5013 /// FoldOrWithConstants - This helper function folds:
5014 ///
5015 ///     ((A | B) & C1) | (B & C2)
5016 ///
5017 /// into:
5018 /// 
5019 ///     (A & C1) | B
5020 ///
5021 /// when the XOR of the two constants is "all ones" (-1).
5022 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
5023                                                Value *A, Value *B, Value *C) {
5024   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5025   if (!CI1) return 0;
5026
5027   Value *V1 = 0;
5028   ConstantInt *CI2 = 0;
5029   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
5030
5031   APInt Xor = CI1->getValue() ^ CI2->getValue();
5032   if (!Xor.isAllOnesValue()) return 0;
5033
5034   if (V1 == A || V1 == B) {
5035     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
5036     return BinaryOperator::CreateOr(NewOp, V1);
5037   }
5038
5039   return 0;
5040 }
5041
5042 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
5043   bool Changed = SimplifyCommutative(I);
5044   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5045
5046   if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5047     return ReplaceInstUsesWith(I, V);
5048   
5049   
5050   // See if we can simplify any instructions used by the instruction whose sole 
5051   // purpose is to compute bits we don't care about.
5052   if (SimplifyDemandedInstructionBits(I))
5053     return &I;
5054
5055   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5056     ConstantInt *C1 = 0; Value *X = 0;
5057     // (X & C1) | C2 --> (X | C2) & (C1|C2)
5058     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
5059         isOnlyUse(Op0)) {
5060       Value *Or = Builder->CreateOr(X, RHS);
5061       Or->takeName(Op0);
5062       return BinaryOperator::CreateAnd(Or, 
5063                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
5064     }
5065
5066     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
5067     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
5068         isOnlyUse(Op0)) {
5069       Value *Or = Builder->CreateOr(X, RHS);
5070       Or->takeName(Op0);
5071       return BinaryOperator::CreateXor(Or,
5072                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
5073     }
5074
5075     // Try to fold constant and into select arguments.
5076     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5077       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5078         return R;
5079     if (isa<PHINode>(Op0))
5080       if (Instruction *NV = FoldOpIntoPhi(I))
5081         return NV;
5082   }
5083
5084   Value *A = 0, *B = 0;
5085   ConstantInt *C1 = 0, *C2 = 0;
5086
5087   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
5088   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
5089   if (match(Op0, m_Or(m_Value(), m_Value())) ||
5090       match(Op1, m_Or(m_Value(), m_Value())) ||
5091       (match(Op0, m_Shift(m_Value(), m_Value())) &&
5092        match(Op1, m_Shift(m_Value(), m_Value())))) {
5093     if (Instruction *BSwap = MatchBSwap(I))
5094       return BSwap;
5095   }
5096   
5097   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
5098   if (Op0->hasOneUse() &&
5099       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
5100       MaskedValueIsZero(Op1, C1->getValue())) {
5101     Value *NOr = Builder->CreateOr(A, Op1);
5102     NOr->takeName(Op0);
5103     return BinaryOperator::CreateXor(NOr, C1);
5104   }
5105
5106   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
5107   if (Op1->hasOneUse() &&
5108       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
5109       MaskedValueIsZero(Op0, C1->getValue())) {
5110     Value *NOr = Builder->CreateOr(A, Op0);
5111     NOr->takeName(Op0);
5112     return BinaryOperator::CreateXor(NOr, C1);
5113   }
5114
5115   // (A & C)|(B & D)
5116   Value *C = 0, *D = 0;
5117   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5118       match(Op1, m_And(m_Value(B), m_Value(D)))) {
5119     Value *V1 = 0, *V2 = 0, *V3 = 0;
5120     C1 = dyn_cast<ConstantInt>(C);
5121     C2 = dyn_cast<ConstantInt>(D);
5122     if (C1 && C2) {  // (A & C1)|(B & C2)
5123       // If we have: ((V + N) & C1) | (V & C2)
5124       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5125       // replace with V+N.
5126       if (C1->getValue() == ~C2->getValue()) {
5127         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
5128             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
5129           // Add commutes, try both ways.
5130           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5131             return ReplaceInstUsesWith(I, A);
5132           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5133             return ReplaceInstUsesWith(I, A);
5134         }
5135         // Or commutes, try both ways.
5136         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
5137             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
5138           // Add commutes, try both ways.
5139           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5140             return ReplaceInstUsesWith(I, B);
5141           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5142             return ReplaceInstUsesWith(I, B);
5143         }
5144       }
5145       V1 = 0; V2 = 0; V3 = 0;
5146     }
5147     
5148     // Check to see if we have any common things being and'ed.  If so, find the
5149     // terms for V1 & (V2|V3).
5150     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5151       if (A == B)      // (A & C)|(A & D) == A & (C|D)
5152         V1 = A, V2 = C, V3 = D;
5153       else if (A == D) // (A & C)|(B & A) == A & (B|C)
5154         V1 = A, V2 = B, V3 = C;
5155       else if (C == B) // (A & C)|(C & D) == C & (A|D)
5156         V1 = C, V2 = A, V3 = D;
5157       else if (C == D) // (A & C)|(B & C) == C & (A|B)
5158         V1 = C, V2 = A, V3 = B;
5159       
5160       if (V1) {
5161         Value *Or = Builder->CreateOr(V2, V3, "tmp");
5162         return BinaryOperator::CreateAnd(V1, Or);
5163       }
5164     }
5165
5166     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
5167     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
5168       return Match;
5169     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
5170       return Match;
5171     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
5172       return Match;
5173     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
5174       return Match;
5175
5176     // ((A&~B)|(~A&B)) -> A^B
5177     if ((match(C, m_Not(m_Specific(D))) &&
5178          match(B, m_Not(m_Specific(A)))))
5179       return BinaryOperator::CreateXor(A, D);
5180     // ((~B&A)|(~A&B)) -> A^B
5181     if ((match(A, m_Not(m_Specific(D))) &&
5182          match(B, m_Not(m_Specific(C)))))
5183       return BinaryOperator::CreateXor(C, D);
5184     // ((A&~B)|(B&~A)) -> A^B
5185     if ((match(C, m_Not(m_Specific(B))) &&
5186          match(D, m_Not(m_Specific(A)))))
5187       return BinaryOperator::CreateXor(A, B);
5188     // ((~B&A)|(B&~A)) -> A^B
5189     if ((match(A, m_Not(m_Specific(B))) &&
5190          match(D, m_Not(m_Specific(C)))))
5191       return BinaryOperator::CreateXor(C, B);
5192   }
5193   
5194   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
5195   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5196     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5197       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
5198           SI0->getOperand(1) == SI1->getOperand(1) &&
5199           (SI0->hasOneUse() || SI1->hasOneUse())) {
5200         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5201                                          SI0->getName());
5202         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
5203                                       SI1->getOperand(1));
5204       }
5205   }
5206
5207   // ((A|B)&1)|(B&-2) -> (A&1) | B
5208   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5209       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5210     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
5211     if (Ret) return Ret;
5212   }
5213   // (B&-2)|((A|B)&1) -> (A&1) | B
5214   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5215       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5216     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
5217     if (Ret) return Ret;
5218   }
5219
5220   // (~A | ~B) == (~(A & B)) - De Morgan's Law
5221   if (Value *Op0NotVal = dyn_castNotVal(Op0))
5222     if (Value *Op1NotVal = dyn_castNotVal(Op1))
5223       if (Op0->hasOneUse() && Op1->hasOneUse()) {
5224         Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5225                                         I.getName()+".demorgan");
5226         return BinaryOperator::CreateNot(And);
5227       }
5228
5229   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5230   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
5231     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5232       return R;
5233
5234     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5235       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5236         return Res;
5237   }
5238     
5239   // fold (or (cast A), (cast B)) -> (cast (or A, B))
5240   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5241     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5242       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
5243         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5244             !isa<ICmpInst>(Op1C->getOperand(0))) {
5245           const Type *SrcTy = Op0C->getOperand(0)->getType();
5246           if (SrcTy == Op1C->getOperand(0)->getType() &&
5247               SrcTy->isIntOrIntVector() &&
5248               // Only do this if the casts both really cause code to be
5249               // generated.
5250               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5251                                 I.getType(), TD) &&
5252               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5253                                 I.getType(), TD)) {
5254             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5255                                              Op1C->getOperand(0), I.getName());
5256             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5257           }
5258         }
5259       }
5260   }
5261   
5262     
5263   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
5264   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5265     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5266       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5267         return Res;
5268   }
5269
5270   return Changed ? &I : 0;
5271 }
5272
5273 namespace {
5274
5275 // XorSelf - Implements: X ^ X --> 0
5276 struct XorSelf {
5277   Value *RHS;
5278   XorSelf(Value *rhs) : RHS(rhs) {}
5279   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5280   Instruction *apply(BinaryOperator &Xor) const {
5281     return &Xor;
5282   }
5283 };
5284
5285 }
5286
5287 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5288   bool Changed = SimplifyCommutative(I);
5289   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5290
5291   if (isa<UndefValue>(Op1)) {
5292     if (isa<UndefValue>(Op0))
5293       // Handle undef ^ undef -> 0 special case. This is a common
5294       // idiom (misuse).
5295       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5296     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5297   }
5298
5299   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5300   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5301     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5302     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5303   }
5304   
5305   // See if we can simplify any instructions used by the instruction whose sole 
5306   // purpose is to compute bits we don't care about.
5307   if (SimplifyDemandedInstructionBits(I))
5308     return &I;
5309   if (isa<VectorType>(I.getType()))
5310     if (isa<ConstantAggregateZero>(Op1))
5311       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5312
5313   // Is this a ~ operation?
5314   if (Value *NotOp = dyn_castNotVal(&I)) {
5315     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5316       if (Op0I->getOpcode() == Instruction::And || 
5317           Op0I->getOpcode() == Instruction::Or) {
5318         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5319         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5320         if (dyn_castNotVal(Op0I->getOperand(1)))
5321           Op0I->swapOperands();
5322         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5323           Value *NotY =
5324             Builder->CreateNot(Op0I->getOperand(1),
5325                                Op0I->getOperand(1)->getName()+".not");
5326           if (Op0I->getOpcode() == Instruction::And)
5327             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5328           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5329         }
5330         
5331         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5332         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5333         if (isFreeToInvert(Op0I->getOperand(0)) && 
5334             isFreeToInvert(Op0I->getOperand(1))) {
5335           Value *NotX =
5336             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5337           Value *NotY =
5338             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5339           if (Op0I->getOpcode() == Instruction::And)
5340             return BinaryOperator::CreateOr(NotX, NotY);
5341           return BinaryOperator::CreateAnd(NotX, NotY);
5342         }
5343       }
5344     }
5345   }
5346   
5347   
5348   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5349     if (RHS->isOne() && Op0->hasOneUse()) {
5350       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5351       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5352         return new ICmpInst(ICI->getInversePredicate(),
5353                             ICI->getOperand(0), ICI->getOperand(1));
5354
5355       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5356         return new FCmpInst(FCI->getInversePredicate(),
5357                             FCI->getOperand(0), FCI->getOperand(1));
5358     }
5359
5360     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5361     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5362       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5363         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5364           Instruction::CastOps Opcode = Op0C->getOpcode();
5365           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5366               (RHS == ConstantExpr::getCast(Opcode, 
5367                                             ConstantInt::getTrue(*Context),
5368                                             Op0C->getDestTy()))) {
5369             CI->setPredicate(CI->getInversePredicate());
5370             return CastInst::Create(Opcode, CI, Op0C->getType());
5371           }
5372         }
5373       }
5374     }
5375
5376     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5377       // ~(c-X) == X-c-1 == X+(-c-1)
5378       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5379         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5380           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5381           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5382                                       ConstantInt::get(I.getType(), 1));
5383           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5384         }
5385           
5386       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5387         if (Op0I->getOpcode() == Instruction::Add) {
5388           // ~(X-c) --> (-c-1)-X
5389           if (RHS->isAllOnesValue()) {
5390             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5391             return BinaryOperator::CreateSub(
5392                            ConstantExpr::getSub(NegOp0CI,
5393                                       ConstantInt::get(I.getType(), 1)),
5394                                       Op0I->getOperand(0));
5395           } else if (RHS->getValue().isSignBit()) {
5396             // (X + C) ^ signbit -> (X + C + signbit)
5397             Constant *C = ConstantInt::get(*Context,
5398                                            RHS->getValue() + Op0CI->getValue());
5399             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5400
5401           }
5402         } else if (Op0I->getOpcode() == Instruction::Or) {
5403           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5404           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5405             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5406             // Anything in both C1 and C2 is known to be zero, remove it from
5407             // NewRHS.
5408             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5409             NewRHS = ConstantExpr::getAnd(NewRHS, 
5410                                        ConstantExpr::getNot(CommonBits));
5411             Worklist.Add(Op0I);
5412             I.setOperand(0, Op0I->getOperand(0));
5413             I.setOperand(1, NewRHS);
5414             return &I;
5415           }
5416         }
5417       }
5418     }
5419
5420     // Try to fold constant and into select arguments.
5421     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5422       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5423         return R;
5424     if (isa<PHINode>(Op0))
5425       if (Instruction *NV = FoldOpIntoPhi(I))
5426         return NV;
5427   }
5428
5429   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5430     if (X == Op1)
5431       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5432
5433   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5434     if (X == Op0)
5435       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5436
5437   
5438   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5439   if (Op1I) {
5440     Value *A, *B;
5441     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5442       if (A == Op0) {              // B^(B|A) == (A|B)^B
5443         Op1I->swapOperands();
5444         I.swapOperands();
5445         std::swap(Op0, Op1);
5446       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5447         I.swapOperands();     // Simplified below.
5448         std::swap(Op0, Op1);
5449       }
5450     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5451       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5452     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5453       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5454     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5455                Op1I->hasOneUse()){
5456       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5457         Op1I->swapOperands();
5458         std::swap(A, B);
5459       }
5460       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5461         I.swapOperands();     // Simplified below.
5462         std::swap(Op0, Op1);
5463       }
5464     }
5465   }
5466   
5467   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5468   if (Op0I) {
5469     Value *A, *B;
5470     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5471         Op0I->hasOneUse()) {
5472       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5473         std::swap(A, B);
5474       if (B == Op1)                                  // (A|B)^B == A & ~B
5475         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5476     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5477       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5478     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5479       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5480     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5481                Op0I->hasOneUse()){
5482       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5483         std::swap(A, B);
5484       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5485           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5486         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5487       }
5488     }
5489   }
5490   
5491   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5492   if (Op0I && Op1I && Op0I->isShift() && 
5493       Op0I->getOpcode() == Op1I->getOpcode() && 
5494       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5495       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5496     Value *NewOp =
5497       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5498                          Op0I->getName());
5499     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5500                                   Op1I->getOperand(1));
5501   }
5502     
5503   if (Op0I && Op1I) {
5504     Value *A, *B, *C, *D;
5505     // (A & B)^(A | B) -> A ^ B
5506     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5507         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5508       if ((A == C && B == D) || (A == D && B == C)) 
5509         return BinaryOperator::CreateXor(A, B);
5510     }
5511     // (A | B)^(A & B) -> A ^ B
5512     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5513         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5514       if ((A == C && B == D) || (A == D && B == C)) 
5515         return BinaryOperator::CreateXor(A, B);
5516     }
5517     
5518     // (A & B)^(C & D)
5519     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5520         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5521         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5522       // (X & Y)^(X & Y) -> (Y^Z) & X
5523       Value *X = 0, *Y = 0, *Z = 0;
5524       if (A == C)
5525         X = A, Y = B, Z = D;
5526       else if (A == D)
5527         X = A, Y = B, Z = C;
5528       else if (B == C)
5529         X = B, Y = A, Z = D;
5530       else if (B == D)
5531         X = B, Y = A, Z = C;
5532       
5533       if (X) {
5534         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5535         return BinaryOperator::CreateAnd(NewOp, X);
5536       }
5537     }
5538   }
5539     
5540   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5541   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5542     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5543       return R;
5544
5545   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5546   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5547     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5548       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5549         const Type *SrcTy = Op0C->getOperand(0)->getType();
5550         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5551             // Only do this if the casts both really cause code to be generated.
5552             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5553                               I.getType(), TD) &&
5554             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5555                               I.getType(), TD)) {
5556           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5557                                             Op1C->getOperand(0), I.getName());
5558           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5559         }
5560       }
5561   }
5562
5563   return Changed ? &I : 0;
5564 }
5565
5566 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5567                                    LLVMContext *Context) {
5568   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5569 }
5570
5571 static bool HasAddOverflow(ConstantInt *Result,
5572                            ConstantInt *In1, ConstantInt *In2,
5573                            bool IsSigned) {
5574   if (IsSigned)
5575     if (In2->getValue().isNegative())
5576       return Result->getValue().sgt(In1->getValue());
5577     else
5578       return Result->getValue().slt(In1->getValue());
5579   else
5580     return Result->getValue().ult(In1->getValue());
5581 }
5582
5583 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5584 /// overflowed for this type.
5585 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5586                             Constant *In2, LLVMContext *Context,
5587                             bool IsSigned = false) {
5588   Result = ConstantExpr::getAdd(In1, In2);
5589
5590   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5591     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5592       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5593       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5594                          ExtractElement(In1, Idx, Context),
5595                          ExtractElement(In2, Idx, Context),
5596                          IsSigned))
5597         return true;
5598     }
5599     return false;
5600   }
5601
5602   return HasAddOverflow(cast<ConstantInt>(Result),
5603                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5604                         IsSigned);
5605 }
5606
5607 static bool HasSubOverflow(ConstantInt *Result,
5608                            ConstantInt *In1, ConstantInt *In2,
5609                            bool IsSigned) {
5610   if (IsSigned)
5611     if (In2->getValue().isNegative())
5612       return Result->getValue().slt(In1->getValue());
5613     else
5614       return Result->getValue().sgt(In1->getValue());
5615   else
5616     return Result->getValue().ugt(In1->getValue());
5617 }
5618
5619 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5620 /// overflowed for this type.
5621 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5622                             Constant *In2, LLVMContext *Context,
5623                             bool IsSigned = false) {
5624   Result = ConstantExpr::getSub(In1, In2);
5625
5626   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5627     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5628       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5629       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5630                          ExtractElement(In1, Idx, Context),
5631                          ExtractElement(In2, Idx, Context),
5632                          IsSigned))
5633         return true;
5634     }
5635     return false;
5636   }
5637
5638   return HasSubOverflow(cast<ConstantInt>(Result),
5639                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5640                         IsSigned);
5641 }
5642
5643
5644 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5645 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5646 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5647                                        ICmpInst::Predicate Cond,
5648                                        Instruction &I) {
5649   // Look through bitcasts.
5650   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5651     RHS = BCI->getOperand(0);
5652
5653   Value *PtrBase = GEPLHS->getOperand(0);
5654   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5655     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5656     // This transformation (ignoring the base and scales) is valid because we
5657     // know pointers can't overflow since the gep is inbounds.  See if we can
5658     // output an optimized form.
5659     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5660     
5661     // If not, synthesize the offset the hard way.
5662     if (Offset == 0)
5663       Offset = EmitGEPOffset(GEPLHS, *this);
5664     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5665                         Constant::getNullValue(Offset->getType()));
5666   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5667     // If the base pointers are different, but the indices are the same, just
5668     // compare the base pointer.
5669     if (PtrBase != GEPRHS->getOperand(0)) {
5670       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5671       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5672                         GEPRHS->getOperand(0)->getType();
5673       if (IndicesTheSame)
5674         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5675           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5676             IndicesTheSame = false;
5677             break;
5678           }
5679
5680       // If all indices are the same, just compare the base pointers.
5681       if (IndicesTheSame)
5682         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5683                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5684
5685       // Otherwise, the base pointers are different and the indices are
5686       // different, bail out.
5687       return 0;
5688     }
5689
5690     // If one of the GEPs has all zero indices, recurse.
5691     bool AllZeros = true;
5692     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5693       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5694           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5695         AllZeros = false;
5696         break;
5697       }
5698     if (AllZeros)
5699       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5700                           ICmpInst::getSwappedPredicate(Cond), I);
5701
5702     // If the other GEP has all zero indices, recurse.
5703     AllZeros = true;
5704     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5705       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5706           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5707         AllZeros = false;
5708         break;
5709       }
5710     if (AllZeros)
5711       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5712
5713     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5714       // If the GEPs only differ by one index, compare it.
5715       unsigned NumDifferences = 0;  // Keep track of # differences.
5716       unsigned DiffOperand = 0;     // The operand that differs.
5717       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5718         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5719           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5720                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5721             // Irreconcilable differences.
5722             NumDifferences = 2;
5723             break;
5724           } else {
5725             if (NumDifferences++) break;
5726             DiffOperand = i;
5727           }
5728         }
5729
5730       if (NumDifferences == 0)   // SAME GEP?
5731         return ReplaceInstUsesWith(I, // No comparison is needed here.
5732                                    ConstantInt::get(Type::getInt1Ty(*Context),
5733                                              ICmpInst::isTrueWhenEqual(Cond)));
5734
5735       else if (NumDifferences == 1) {
5736         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5737         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5738         // Make sure we do a signed comparison here.
5739         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5740       }
5741     }
5742
5743     // Only lower this if the icmp is the only user of the GEP or if we expect
5744     // the result to fold to a constant!
5745     if (TD &&
5746         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5747         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5748       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5749       Value *L = EmitGEPOffset(GEPLHS, *this);
5750       Value *R = EmitGEPOffset(GEPRHS, *this);
5751       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5752     }
5753   }
5754   return 0;
5755 }
5756
5757 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5758 ///
5759 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5760                                                 Instruction *LHSI,
5761                                                 Constant *RHSC) {
5762   if (!isa<ConstantFP>(RHSC)) return 0;
5763   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5764   
5765   // Get the width of the mantissa.  We don't want to hack on conversions that
5766   // might lose information from the integer, e.g. "i64 -> float"
5767   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5768   if (MantissaWidth == -1) return 0;  // Unknown.
5769   
5770   // Check to see that the input is converted from an integer type that is small
5771   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5772   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5773   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5774   
5775   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5776   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5777   if (LHSUnsigned)
5778     ++InputSize;
5779   
5780   // If the conversion would lose info, don't hack on this.
5781   if ((int)InputSize > MantissaWidth)
5782     return 0;
5783   
5784   // Otherwise, we can potentially simplify the comparison.  We know that it
5785   // will always come through as an integer value and we know the constant is
5786   // not a NAN (it would have been previously simplified).
5787   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5788   
5789   ICmpInst::Predicate Pred;
5790   switch (I.getPredicate()) {
5791   default: llvm_unreachable("Unexpected predicate!");
5792   case FCmpInst::FCMP_UEQ:
5793   case FCmpInst::FCMP_OEQ:
5794     Pred = ICmpInst::ICMP_EQ;
5795     break;
5796   case FCmpInst::FCMP_UGT:
5797   case FCmpInst::FCMP_OGT:
5798     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5799     break;
5800   case FCmpInst::FCMP_UGE:
5801   case FCmpInst::FCMP_OGE:
5802     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5803     break;
5804   case FCmpInst::FCMP_ULT:
5805   case FCmpInst::FCMP_OLT:
5806     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5807     break;
5808   case FCmpInst::FCMP_ULE:
5809   case FCmpInst::FCMP_OLE:
5810     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5811     break;
5812   case FCmpInst::FCMP_UNE:
5813   case FCmpInst::FCMP_ONE:
5814     Pred = ICmpInst::ICMP_NE;
5815     break;
5816   case FCmpInst::FCMP_ORD:
5817     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5818   case FCmpInst::FCMP_UNO:
5819     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5820   }
5821   
5822   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5823   
5824   // Now we know that the APFloat is a normal number, zero or inf.
5825   
5826   // See if the FP constant is too large for the integer.  For example,
5827   // comparing an i8 to 300.0.
5828   unsigned IntWidth = IntTy->getScalarSizeInBits();
5829   
5830   if (!LHSUnsigned) {
5831     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5832     // and large values.
5833     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5834     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5835                           APFloat::rmNearestTiesToEven);
5836     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5837       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5838           Pred == ICmpInst::ICMP_SLE)
5839         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5840       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5841     }
5842   } else {
5843     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5844     // +INF and large values.
5845     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5846     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5847                           APFloat::rmNearestTiesToEven);
5848     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5849       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5850           Pred == ICmpInst::ICMP_ULE)
5851         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5852       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5853     }
5854   }
5855   
5856   if (!LHSUnsigned) {
5857     // See if the RHS value is < SignedMin.
5858     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5859     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5860                           APFloat::rmNearestTiesToEven);
5861     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5862       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5863           Pred == ICmpInst::ICMP_SGE)
5864         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5865       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5866     }
5867   }
5868
5869   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5870   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5871   // casting the FP value to the integer value and back, checking for equality.
5872   // Don't do this for zero, because -0.0 is not fractional.
5873   Constant *RHSInt = LHSUnsigned
5874     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5875     : ConstantExpr::getFPToSI(RHSC, IntTy);
5876   if (!RHS.isZero()) {
5877     bool Equal = LHSUnsigned
5878       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5879       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5880     if (!Equal) {
5881       // If we had a comparison against a fractional value, we have to adjust
5882       // the compare predicate and sometimes the value.  RHSC is rounded towards
5883       // zero at this point.
5884       switch (Pred) {
5885       default: llvm_unreachable("Unexpected integer comparison!");
5886       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5887         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5888       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5889         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5890       case ICmpInst::ICMP_ULE:
5891         // (float)int <= 4.4   --> int <= 4
5892         // (float)int <= -4.4  --> false
5893         if (RHS.isNegative())
5894           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5895         break;
5896       case ICmpInst::ICMP_SLE:
5897         // (float)int <= 4.4   --> int <= 4
5898         // (float)int <= -4.4  --> int < -4
5899         if (RHS.isNegative())
5900           Pred = ICmpInst::ICMP_SLT;
5901         break;
5902       case ICmpInst::ICMP_ULT:
5903         // (float)int < -4.4   --> false
5904         // (float)int < 4.4    --> int <= 4
5905         if (RHS.isNegative())
5906           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5907         Pred = ICmpInst::ICMP_ULE;
5908         break;
5909       case ICmpInst::ICMP_SLT:
5910         // (float)int < -4.4   --> int < -4
5911         // (float)int < 4.4    --> int <= 4
5912         if (!RHS.isNegative())
5913           Pred = ICmpInst::ICMP_SLE;
5914         break;
5915       case ICmpInst::ICMP_UGT:
5916         // (float)int > 4.4    --> int > 4
5917         // (float)int > -4.4   --> true
5918         if (RHS.isNegative())
5919           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5920         break;
5921       case ICmpInst::ICMP_SGT:
5922         // (float)int > 4.4    --> int > 4
5923         // (float)int > -4.4   --> int >= -4
5924         if (RHS.isNegative())
5925           Pred = ICmpInst::ICMP_SGE;
5926         break;
5927       case ICmpInst::ICMP_UGE:
5928         // (float)int >= -4.4   --> true
5929         // (float)int >= 4.4    --> int > 4
5930         if (!RHS.isNegative())
5931           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5932         Pred = ICmpInst::ICMP_UGT;
5933         break;
5934       case ICmpInst::ICMP_SGE:
5935         // (float)int >= -4.4   --> int >= -4
5936         // (float)int >= 4.4    --> int > 4
5937         if (!RHS.isNegative())
5938           Pred = ICmpInst::ICMP_SGT;
5939         break;
5940       }
5941     }
5942   }
5943
5944   // Lower this FP comparison into an appropriate integer version of the
5945   // comparison.
5946   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5947 }
5948
5949 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5950   bool Changed = false;
5951   
5952   /// Orders the operands of the compare so that they are listed from most
5953   /// complex to least complex.  This puts constants before unary operators,
5954   /// before binary operators.
5955   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
5956     I.swapOperands();
5957     Changed = true;
5958   }
5959
5960   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5961   
5962   if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
5963     return ReplaceInstUsesWith(I, V);
5964
5965   // Simplify 'fcmp pred X, X'
5966   if (Op0 == Op1) {
5967     switch (I.getPredicate()) {
5968     default: llvm_unreachable("Unknown predicate!");
5969     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5970     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5971     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5972     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5973       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5974       I.setPredicate(FCmpInst::FCMP_UNO);
5975       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5976       return &I;
5977       
5978     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5979     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5980     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5981     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5982       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5983       I.setPredicate(FCmpInst::FCMP_ORD);
5984       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5985       return &I;
5986     }
5987   }
5988     
5989   // Handle fcmp with constant RHS
5990   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5991     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5992       switch (LHSI->getOpcode()) {
5993       case Instruction::PHI:
5994         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5995         // block.  If in the same block, we're encouraging jump threading.  If
5996         // not, we are just pessimizing the code by making an i1 phi.
5997         if (LHSI->getParent() == I.getParent())
5998           if (Instruction *NV = FoldOpIntoPhi(I, true))
5999             return NV;
6000         break;
6001       case Instruction::SIToFP:
6002       case Instruction::UIToFP:
6003         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6004           return NV;
6005         break;
6006       case Instruction::Select:
6007         // If either operand of the select is a constant, we can fold the
6008         // comparison into the select arms, which will cause one to be
6009         // constant folded and the select turned into a bitwise or.
6010         Value *Op1 = 0, *Op2 = 0;
6011         if (LHSI->hasOneUse()) {
6012           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6013             // Fold the known value into the constant operand.
6014             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
6015             // Insert a new FCmp of the other select operand.
6016             Op2 = Builder->CreateFCmp(I.getPredicate(),
6017                                       LHSI->getOperand(2), RHSC, I.getName());
6018           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6019             // Fold the known value into the constant operand.
6020             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
6021             // Insert a new FCmp of the other select operand.
6022             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6023                                       RHSC, I.getName());
6024           }
6025         }
6026
6027         if (Op1)
6028           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6029         break;
6030       }
6031   }
6032
6033   return Changed ? &I : 0;
6034 }
6035
6036 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
6037   bool Changed = false;
6038   
6039   /// Orders the operands of the compare so that they are listed from most
6040   /// complex to least complex.  This puts constants before unary operators,
6041   /// before binary operators.
6042   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6043     I.swapOperands();
6044     Changed = true;
6045   }
6046   
6047   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6048   
6049   if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6050     return ReplaceInstUsesWith(I, V);
6051   
6052   const Type *Ty = Op0->getType();
6053
6054   // icmp's with boolean values can always be turned into bitwise operations
6055   if (Ty == Type::getInt1Ty(*Context)) {
6056     switch (I.getPredicate()) {
6057     default: llvm_unreachable("Invalid icmp instruction!");
6058     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6059       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
6060       return BinaryOperator::CreateNot(Xor);
6061     }
6062     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6063       return BinaryOperator::CreateXor(Op0, Op1);
6064
6065     case ICmpInst::ICMP_UGT:
6066       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6067       // FALL THROUGH
6068     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6069       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6070       return BinaryOperator::CreateAnd(Not, Op1);
6071     }
6072     case ICmpInst::ICMP_SGT:
6073       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6074       // FALL THROUGH
6075     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6076       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6077       return BinaryOperator::CreateAnd(Not, Op0);
6078     }
6079     case ICmpInst::ICMP_UGE:
6080       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6081       // FALL THROUGH
6082     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6083       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6084       return BinaryOperator::CreateOr(Not, Op1);
6085     }
6086     case ICmpInst::ICMP_SGE:
6087       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6088       // FALL THROUGH
6089     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6090       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6091       return BinaryOperator::CreateOr(Not, Op0);
6092     }
6093     }
6094   }
6095
6096   unsigned BitWidth = 0;
6097   if (TD)
6098     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6099   else if (Ty->isIntOrIntVector())
6100     BitWidth = Ty->getScalarSizeInBits();
6101
6102   bool isSignBit = false;
6103
6104   // See if we are doing a comparison with a constant.
6105   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6106     Value *A = 0, *B = 0;
6107     
6108     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6109     if (I.isEquality() && CI->isNullValue() &&
6110         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6111       // (icmp cond A B) if cond is equality
6112       return new ICmpInst(I.getPredicate(), A, B);
6113     }
6114     
6115     // If we have an icmp le or icmp ge instruction, turn it into the
6116     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6117     // them being folded in the code below.  The SimplifyICmpInst code has
6118     // already handled the edge cases for us, so we just assert on them.
6119     switch (I.getPredicate()) {
6120     default: break;
6121     case ICmpInst::ICMP_ULE:
6122       assert(!CI->isMaxValue(false));                 // A <=u MAX -> TRUE
6123       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6124                           AddOne(CI));
6125     case ICmpInst::ICMP_SLE:
6126       assert(!CI->isMaxValue(true));                  // A <=s MAX -> TRUE
6127       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6128                           AddOne(CI));
6129     case ICmpInst::ICMP_UGE:
6130       assert(!CI->isMinValue(false));                  // A >=u MIN -> TRUE
6131       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6132                           SubOne(CI));
6133     case ICmpInst::ICMP_SGE:
6134       assert(!CI->isMinValue(true));                   // A >=s MIN -> TRUE
6135       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6136                           SubOne(CI));
6137     }
6138     
6139     // If this comparison is a normal comparison, it demands all
6140     // bits, if it is a sign bit comparison, it only demands the sign bit.
6141     bool UnusedBit;
6142     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6143   }
6144
6145   // See if we can fold the comparison based on range information we can get
6146   // by checking whether bits are known to be zero or one in the input.
6147   if (BitWidth != 0) {
6148     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6149     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6150
6151     if (SimplifyDemandedBits(I.getOperandUse(0),
6152                              isSignBit ? APInt::getSignBit(BitWidth)
6153                                        : APInt::getAllOnesValue(BitWidth),
6154                              Op0KnownZero, Op0KnownOne, 0))
6155       return &I;
6156     if (SimplifyDemandedBits(I.getOperandUse(1),
6157                              APInt::getAllOnesValue(BitWidth),
6158                              Op1KnownZero, Op1KnownOne, 0))
6159       return &I;
6160
6161     // Given the known and unknown bits, compute a range that the LHS could be
6162     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6163     // EQ and NE we use unsigned values.
6164     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6165     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6166     if (I.isSigned()) {
6167       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6168                                              Op0Min, Op0Max);
6169       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6170                                              Op1Min, Op1Max);
6171     } else {
6172       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6173                                                Op0Min, Op0Max);
6174       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6175                                                Op1Min, Op1Max);
6176     }
6177
6178     // If Min and Max are known to be the same, then SimplifyDemandedBits
6179     // figured out that the LHS is a constant.  Just constant fold this now so
6180     // that code below can assume that Min != Max.
6181     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6182       return new ICmpInst(I.getPredicate(),
6183                           ConstantInt::get(*Context, Op0Min), Op1);
6184     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6185       return new ICmpInst(I.getPredicate(), Op0,
6186                           ConstantInt::get(*Context, Op1Min));
6187
6188     // Based on the range information we know about the LHS, see if we can
6189     // simplify this comparison.  For example, (x&4) < 8  is always true.
6190     switch (I.getPredicate()) {
6191     default: llvm_unreachable("Unknown icmp opcode!");
6192     case ICmpInst::ICMP_EQ:
6193       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6194         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6195       break;
6196     case ICmpInst::ICMP_NE:
6197       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6198         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6199       break;
6200     case ICmpInst::ICMP_ULT:
6201       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6202         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6203       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6204         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6205       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6206         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6207       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6208         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6209           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6210                               SubOne(CI));
6211
6212         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6213         if (CI->isMinValue(true))
6214           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6215                            Constant::getAllOnesValue(Op0->getType()));
6216       }
6217       break;
6218     case ICmpInst::ICMP_UGT:
6219       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6220         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6221       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6222         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6223
6224       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6225         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6226       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6227         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6228           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6229                               AddOne(CI));
6230
6231         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6232         if (CI->isMaxValue(true))
6233           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6234                               Constant::getNullValue(Op0->getType()));
6235       }
6236       break;
6237     case ICmpInst::ICMP_SLT:
6238       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6239         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6240       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6241         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6242       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6243         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6244       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6245         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6246           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6247                               SubOne(CI));
6248       }
6249       break;
6250     case ICmpInst::ICMP_SGT:
6251       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6252         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6253       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6254         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6255
6256       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6257         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6258       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6259         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6260           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6261                               AddOne(CI));
6262       }
6263       break;
6264     case ICmpInst::ICMP_SGE:
6265       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6266       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6267         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6268       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6269         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6270       break;
6271     case ICmpInst::ICMP_SLE:
6272       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6273       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6274         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6275       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6276         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6277       break;
6278     case ICmpInst::ICMP_UGE:
6279       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6280       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6281         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6282       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6283         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6284       break;
6285     case ICmpInst::ICMP_ULE:
6286       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6287       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6288         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6289       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6290         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6291       break;
6292     }
6293
6294     // Turn a signed comparison into an unsigned one if both operands
6295     // are known to have the same sign.
6296     if (I.isSigned() &&
6297         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6298          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6299       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6300   }
6301
6302   // Test if the ICmpInst instruction is used exclusively by a select as
6303   // part of a minimum or maximum operation. If so, refrain from doing
6304   // any other folding. This helps out other analyses which understand
6305   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6306   // and CodeGen. And in this case, at least one of the comparison
6307   // operands has at least one user besides the compare (the select),
6308   // which would often largely negate the benefit of folding anyway.
6309   if (I.hasOneUse())
6310     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6311       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6312           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6313         return 0;
6314
6315   // See if we are doing a comparison between a constant and an instruction that
6316   // can be folded into the comparison.
6317   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6318     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6319     // instruction, see if that instruction also has constants so that the 
6320     // instruction can be folded into the icmp 
6321     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6322       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6323         return Res;
6324   }
6325
6326   // Handle icmp with constant (but not simple integer constant) RHS
6327   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6328     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6329       switch (LHSI->getOpcode()) {
6330       case Instruction::GetElementPtr:
6331         if (RHSC->isNullValue()) {
6332           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6333           bool isAllZeros = true;
6334           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6335             if (!isa<Constant>(LHSI->getOperand(i)) ||
6336                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6337               isAllZeros = false;
6338               break;
6339             }
6340           if (isAllZeros)
6341             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6342                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6343         }
6344         break;
6345
6346       case Instruction::PHI:
6347         // Only fold icmp into the PHI if the phi and icmp are in the same
6348         // block.  If in the same block, we're encouraging jump threading.  If
6349         // not, we are just pessimizing the code by making an i1 phi.
6350         if (LHSI->getParent() == I.getParent())
6351           if (Instruction *NV = FoldOpIntoPhi(I, true))
6352             return NV;
6353         break;
6354       case Instruction::Select: {
6355         // If either operand of the select is a constant, we can fold the
6356         // comparison into the select arms, which will cause one to be
6357         // constant folded and the select turned into a bitwise or.
6358         Value *Op1 = 0, *Op2 = 0;
6359         if (LHSI->hasOneUse()) {
6360           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6361             // Fold the known value into the constant operand.
6362             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6363             // Insert a new ICmp of the other select operand.
6364             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6365                                       RHSC, I.getName());
6366           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6367             // Fold the known value into the constant operand.
6368             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6369             // Insert a new ICmp of the other select operand.
6370             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6371                                       RHSC, I.getName());
6372           }
6373         }
6374
6375         if (Op1)
6376           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6377         break;
6378       }
6379       case Instruction::Call:
6380         // If we have (malloc != null), and if the malloc has a single use, we
6381         // can assume it is successful and remove the malloc.
6382         if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6383             isa<ConstantPointerNull>(RHSC)) {
6384           // Need to explicitly erase malloc call here, instead of adding it to
6385           // Worklist, because it won't get DCE'd from the Worklist since
6386           // isInstructionTriviallyDead() returns false for function calls.
6387           // It is OK to replace LHSI/MallocCall with Undef because the 
6388           // instruction that uses it will be erased via Worklist.
6389           if (extractMallocCall(LHSI)) {
6390             LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6391             EraseInstFromFunction(*LHSI);
6392             return ReplaceInstUsesWith(I,
6393                                      ConstantInt::get(Type::getInt1Ty(*Context),
6394                                                       !I.isTrueWhenEqual()));
6395           }
6396           if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6397             if (MallocCall->hasOneUse()) {
6398               MallocCall->replaceAllUsesWith(
6399                                         UndefValue::get(MallocCall->getType()));
6400               EraseInstFromFunction(*MallocCall);
6401               Worklist.Add(LHSI); // The malloc's bitcast use.
6402               return ReplaceInstUsesWith(I,
6403                                      ConstantInt::get(Type::getInt1Ty(*Context),
6404                                                       !I.isTrueWhenEqual()));
6405             }
6406         }
6407         break;
6408       }
6409   }
6410
6411   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6412   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6413     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6414       return NI;
6415   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6416     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6417                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6418       return NI;
6419
6420   // Test to see if the operands of the icmp are casted versions of other
6421   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6422   // now.
6423   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6424     if (isa<PointerType>(Op0->getType()) && 
6425         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6426       // We keep moving the cast from the left operand over to the right
6427       // operand, where it can often be eliminated completely.
6428       Op0 = CI->getOperand(0);
6429
6430       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6431       // so eliminate it as well.
6432       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6433         Op1 = CI2->getOperand(0);
6434
6435       // If Op1 is a constant, we can fold the cast into the constant.
6436       if (Op0->getType() != Op1->getType()) {
6437         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6438           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6439         } else {
6440           // Otherwise, cast the RHS right before the icmp
6441           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6442         }
6443       }
6444       return new ICmpInst(I.getPredicate(), Op0, Op1);
6445     }
6446   }
6447   
6448   if (isa<CastInst>(Op0)) {
6449     // Handle the special case of: icmp (cast bool to X), <cst>
6450     // This comes up when you have code like
6451     //   int X = A < B;
6452     //   if (X) ...
6453     // For generality, we handle any zero-extension of any operand comparison
6454     // with a constant or another cast from the same type.
6455     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6456       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6457         return R;
6458   }
6459   
6460   // See if it's the same type of instruction on the left and right.
6461   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6462     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6463       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6464           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6465         switch (Op0I->getOpcode()) {
6466         default: break;
6467         case Instruction::Add:
6468         case Instruction::Sub:
6469         case Instruction::Xor:
6470           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6471             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6472                                 Op1I->getOperand(0));
6473           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6474           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6475             if (CI->getValue().isSignBit()) {
6476               ICmpInst::Predicate Pred = I.isSigned()
6477                                              ? I.getUnsignedPredicate()
6478                                              : I.getSignedPredicate();
6479               return new ICmpInst(Pred, Op0I->getOperand(0),
6480                                   Op1I->getOperand(0));
6481             }
6482             
6483             if (CI->getValue().isMaxSignedValue()) {
6484               ICmpInst::Predicate Pred = I.isSigned()
6485                                              ? I.getUnsignedPredicate()
6486                                              : I.getSignedPredicate();
6487               Pred = I.getSwappedPredicate(Pred);
6488               return new ICmpInst(Pred, Op0I->getOperand(0),
6489                                   Op1I->getOperand(0));
6490             }
6491           }
6492           break;
6493         case Instruction::Mul:
6494           if (!I.isEquality())
6495             break;
6496
6497           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6498             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6499             // Mask = -1 >> count-trailing-zeros(Cst).
6500             if (!CI->isZero() && !CI->isOne()) {
6501               const APInt &AP = CI->getValue();
6502               ConstantInt *Mask = ConstantInt::get(*Context, 
6503                                       APInt::getLowBitsSet(AP.getBitWidth(),
6504                                                            AP.getBitWidth() -
6505                                                       AP.countTrailingZeros()));
6506               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6507               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6508               return new ICmpInst(I.getPredicate(), And1, And2);
6509             }
6510           }
6511           break;
6512         }
6513       }
6514     }
6515   }
6516   
6517   // ~x < ~y --> y < x
6518   { Value *A, *B;
6519     if (match(Op0, m_Not(m_Value(A))) &&
6520         match(Op1, m_Not(m_Value(B))))
6521       return new ICmpInst(I.getPredicate(), B, A);
6522   }
6523   
6524   if (I.isEquality()) {
6525     Value *A, *B, *C, *D;
6526     
6527     // -x == -y --> x == y
6528     if (match(Op0, m_Neg(m_Value(A))) &&
6529         match(Op1, m_Neg(m_Value(B))))
6530       return new ICmpInst(I.getPredicate(), A, B);
6531     
6532     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6533       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6534         Value *OtherVal = A == Op1 ? B : A;
6535         return new ICmpInst(I.getPredicate(), OtherVal,
6536                             Constant::getNullValue(A->getType()));
6537       }
6538
6539       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6540         // A^c1 == C^c2 --> A == C^(c1^c2)
6541         ConstantInt *C1, *C2;
6542         if (match(B, m_ConstantInt(C1)) &&
6543             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6544           Constant *NC = 
6545                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6546           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6547           return new ICmpInst(I.getPredicate(), A, Xor);
6548         }
6549         
6550         // A^B == A^D -> B == D
6551         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6552         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6553         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6554         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6555       }
6556     }
6557     
6558     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6559         (A == Op0 || B == Op0)) {
6560       // A == (A^B)  ->  B == 0
6561       Value *OtherVal = A == Op0 ? B : A;
6562       return new ICmpInst(I.getPredicate(), OtherVal,
6563                           Constant::getNullValue(A->getType()));
6564     }
6565
6566     // (A-B) == A  ->  B == 0
6567     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6568       return new ICmpInst(I.getPredicate(), B, 
6569                           Constant::getNullValue(B->getType()));
6570
6571     // A == (A-B)  ->  B == 0
6572     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6573       return new ICmpInst(I.getPredicate(), B,
6574                           Constant::getNullValue(B->getType()));
6575     
6576     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6577     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6578         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6579         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6580       Value *X = 0, *Y = 0, *Z = 0;
6581       
6582       if (A == C) {
6583         X = B; Y = D; Z = A;
6584       } else if (A == D) {
6585         X = B; Y = C; Z = A;
6586       } else if (B == C) {
6587         X = A; Y = D; Z = B;
6588       } else if (B == D) {
6589         X = A; Y = C; Z = B;
6590       }
6591       
6592       if (X) {   // Build (X^Y) & Z
6593         Op1 = Builder->CreateXor(X, Y, "tmp");
6594         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6595         I.setOperand(0, Op1);
6596         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6597         return &I;
6598       }
6599     }
6600   }
6601   return Changed ? &I : 0;
6602 }
6603
6604
6605 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6606 /// and CmpRHS are both known to be integer constants.
6607 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6608                                           ConstantInt *DivRHS) {
6609   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6610   const APInt &CmpRHSV = CmpRHS->getValue();
6611   
6612   // FIXME: If the operand types don't match the type of the divide 
6613   // then don't attempt this transform. The code below doesn't have the
6614   // logic to deal with a signed divide and an unsigned compare (and
6615   // vice versa). This is because (x /s C1) <s C2  produces different 
6616   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6617   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6618   // work. :(  The if statement below tests that condition and bails 
6619   // if it finds it. 
6620   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6621   if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
6622     return 0;
6623   if (DivRHS->isZero())
6624     return 0; // The ProdOV computation fails on divide by zero.
6625   if (DivIsSigned && DivRHS->isAllOnesValue())
6626     return 0; // The overflow computation also screws up here
6627   if (DivRHS->isOne())
6628     return 0; // Not worth bothering, and eliminates some funny cases
6629               // with INT_MIN.
6630
6631   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6632   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6633   // C2 (CI). By solving for X we can turn this into a range check 
6634   // instead of computing a divide. 
6635   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6636
6637   // Determine if the product overflows by seeing if the product is
6638   // not equal to the divide. Make sure we do the same kind of divide
6639   // as in the LHS instruction that we're folding. 
6640   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6641                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6642
6643   // Get the ICmp opcode
6644   ICmpInst::Predicate Pred = ICI.getPredicate();
6645
6646   // Figure out the interval that is being checked.  For example, a comparison
6647   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6648   // Compute this interval based on the constants involved and the signedness of
6649   // the compare/divide.  This computes a half-open interval, keeping track of
6650   // whether either value in the interval overflows.  After analysis each
6651   // overflow variable is set to 0 if it's corresponding bound variable is valid
6652   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6653   int LoOverflow = 0, HiOverflow = 0;
6654   Constant *LoBound = 0, *HiBound = 0;
6655   
6656   if (!DivIsSigned) {  // udiv
6657     // e.g. X/5 op 3  --> [15, 20)
6658     LoBound = Prod;
6659     HiOverflow = LoOverflow = ProdOV;
6660     if (!HiOverflow)
6661       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6662   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6663     if (CmpRHSV == 0) {       // (X / pos) op 0
6664       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6665       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6666       HiBound = DivRHS;
6667     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6668       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6669       HiOverflow = LoOverflow = ProdOV;
6670       if (!HiOverflow)
6671         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6672     } else {                       // (X / pos) op neg
6673       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6674       HiBound = AddOne(Prod);
6675       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6676       if (!LoOverflow) {
6677         ConstantInt* DivNeg =
6678                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6679         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6680                                      true) ? -1 : 0;
6681        }
6682     }
6683   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6684     if (CmpRHSV == 0) {       // (X / neg) op 0
6685       // e.g. X/-5 op 0  --> [-4, 5)
6686       LoBound = AddOne(DivRHS);
6687       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6688       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6689         HiOverflow = 1;            // [INTMIN+1, overflow)
6690         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6691       }
6692     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6693       // e.g. X/-5 op 3  --> [-19, -14)
6694       HiBound = AddOne(Prod);
6695       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6696       if (!LoOverflow)
6697         LoOverflow = AddWithOverflow(LoBound, HiBound,
6698                                      DivRHS, Context, true) ? -1 : 0;
6699     } else {                       // (X / neg) op neg
6700       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6701       LoOverflow = HiOverflow = ProdOV;
6702       if (!HiOverflow)
6703         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6704     }
6705     
6706     // Dividing by a negative swaps the condition.  LT <-> GT
6707     Pred = ICmpInst::getSwappedPredicate(Pred);
6708   }
6709
6710   Value *X = DivI->getOperand(0);
6711   switch (Pred) {
6712   default: llvm_unreachable("Unhandled icmp opcode!");
6713   case ICmpInst::ICMP_EQ:
6714     if (LoOverflow && HiOverflow)
6715       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6716     else if (HiOverflow)
6717       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6718                           ICmpInst::ICMP_UGE, X, LoBound);
6719     else if (LoOverflow)
6720       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6721                           ICmpInst::ICMP_ULT, X, HiBound);
6722     else
6723       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6724   case ICmpInst::ICMP_NE:
6725     if (LoOverflow && HiOverflow)
6726       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6727     else if (HiOverflow)
6728       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6729                           ICmpInst::ICMP_ULT, X, LoBound);
6730     else if (LoOverflow)
6731       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6732                           ICmpInst::ICMP_UGE, X, HiBound);
6733     else
6734       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6735   case ICmpInst::ICMP_ULT:
6736   case ICmpInst::ICMP_SLT:
6737     if (LoOverflow == +1)   // Low bound is greater than input range.
6738       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6739     if (LoOverflow == -1)   // Low bound is less than input range.
6740       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6741     return new ICmpInst(Pred, X, LoBound);
6742   case ICmpInst::ICMP_UGT:
6743   case ICmpInst::ICMP_SGT:
6744     if (HiOverflow == +1)       // High bound greater than input range.
6745       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6746     else if (HiOverflow == -1)  // High bound less than input range.
6747       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6748     if (Pred == ICmpInst::ICMP_UGT)
6749       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6750     else
6751       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6752   }
6753 }
6754
6755
6756 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6757 ///
6758 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6759                                                           Instruction *LHSI,
6760                                                           ConstantInt *RHS) {
6761   const APInt &RHSV = RHS->getValue();
6762   
6763   switch (LHSI->getOpcode()) {
6764   case Instruction::Trunc:
6765     if (ICI.isEquality() && LHSI->hasOneUse()) {
6766       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6767       // of the high bits truncated out of x are known.
6768       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6769              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6770       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6771       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6772       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6773       
6774       // If all the high bits are known, we can do this xform.
6775       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6776         // Pull in the high bits from known-ones set.
6777         APInt NewRHS(RHS->getValue());
6778         NewRHS.zext(SrcBits);
6779         NewRHS |= KnownOne;
6780         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6781                             ConstantInt::get(*Context, NewRHS));
6782       }
6783     }
6784     break;
6785       
6786   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6787     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6788       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6789       // fold the xor.
6790       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6791           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6792         Value *CompareVal = LHSI->getOperand(0);
6793         
6794         // If the sign bit of the XorCST is not set, there is no change to
6795         // the operation, just stop using the Xor.
6796         if (!XorCST->getValue().isNegative()) {
6797           ICI.setOperand(0, CompareVal);
6798           Worklist.Add(LHSI);
6799           return &ICI;
6800         }
6801         
6802         // Was the old condition true if the operand is positive?
6803         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6804         
6805         // If so, the new one isn't.
6806         isTrueIfPositive ^= true;
6807         
6808         if (isTrueIfPositive)
6809           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6810                               SubOne(RHS));
6811         else
6812           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6813                               AddOne(RHS));
6814       }
6815
6816       if (LHSI->hasOneUse()) {
6817         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6818         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6819           const APInt &SignBit = XorCST->getValue();
6820           ICmpInst::Predicate Pred = ICI.isSigned()
6821                                          ? ICI.getUnsignedPredicate()
6822                                          : ICI.getSignedPredicate();
6823           return new ICmpInst(Pred, LHSI->getOperand(0),
6824                               ConstantInt::get(*Context, RHSV ^ SignBit));
6825         }
6826
6827         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6828         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6829           const APInt &NotSignBit = XorCST->getValue();
6830           ICmpInst::Predicate Pred = ICI.isSigned()
6831                                          ? ICI.getUnsignedPredicate()
6832                                          : ICI.getSignedPredicate();
6833           Pred = ICI.getSwappedPredicate(Pred);
6834           return new ICmpInst(Pred, LHSI->getOperand(0),
6835                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6836         }
6837       }
6838     }
6839     break;
6840   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6841     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6842         LHSI->getOperand(0)->hasOneUse()) {
6843       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6844       
6845       // If the LHS is an AND of a truncating cast, we can widen the
6846       // and/compare to be the input width without changing the value
6847       // produced, eliminating a cast.
6848       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6849         // We can do this transformation if either the AND constant does not
6850         // have its sign bit set or if it is an equality comparison. 
6851         // Extending a relational comparison when we're checking the sign
6852         // bit would not work.
6853         if (Cast->hasOneUse() &&
6854             (ICI.isEquality() ||
6855              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6856           uint32_t BitWidth = 
6857             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6858           APInt NewCST = AndCST->getValue();
6859           NewCST.zext(BitWidth);
6860           APInt NewCI = RHSV;
6861           NewCI.zext(BitWidth);
6862           Value *NewAnd = 
6863             Builder->CreateAnd(Cast->getOperand(0),
6864                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6865           return new ICmpInst(ICI.getPredicate(), NewAnd,
6866                               ConstantInt::get(*Context, NewCI));
6867         }
6868       }
6869       
6870       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6871       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6872       // happens a LOT in code produced by the C front-end, for bitfield
6873       // access.
6874       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6875       if (Shift && !Shift->isShift())
6876         Shift = 0;
6877       
6878       ConstantInt *ShAmt;
6879       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6880       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6881       const Type *AndTy = AndCST->getType();          // Type of the and.
6882       
6883       // We can fold this as long as we can't shift unknown bits
6884       // into the mask.  This can only happen with signed shift
6885       // rights, as they sign-extend.
6886       if (ShAmt) {
6887         bool CanFold = Shift->isLogicalShift();
6888         if (!CanFold) {
6889           // To test for the bad case of the signed shr, see if any
6890           // of the bits shifted in could be tested after the mask.
6891           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6892           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6893           
6894           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6895           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6896                AndCST->getValue()) == 0)
6897             CanFold = true;
6898         }
6899         
6900         if (CanFold) {
6901           Constant *NewCst;
6902           if (Shift->getOpcode() == Instruction::Shl)
6903             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6904           else
6905             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6906           
6907           // Check to see if we are shifting out any of the bits being
6908           // compared.
6909           if (ConstantExpr::get(Shift->getOpcode(),
6910                                        NewCst, ShAmt) != RHS) {
6911             // If we shifted bits out, the fold is not going to work out.
6912             // As a special case, check to see if this means that the
6913             // result is always true or false now.
6914             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6915               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6916             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6917               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6918           } else {
6919             ICI.setOperand(1, NewCst);
6920             Constant *NewAndCST;
6921             if (Shift->getOpcode() == Instruction::Shl)
6922               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6923             else
6924               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6925             LHSI->setOperand(1, NewAndCST);
6926             LHSI->setOperand(0, Shift->getOperand(0));
6927             Worklist.Add(Shift); // Shift is dead.
6928             return &ICI;
6929           }
6930         }
6931       }
6932       
6933       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6934       // preferable because it allows the C<<Y expression to be hoisted out
6935       // of a loop if Y is invariant and X is not.
6936       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6937           ICI.isEquality() && !Shift->isArithmeticShift() &&
6938           !isa<Constant>(Shift->getOperand(0))) {
6939         // Compute C << Y.
6940         Value *NS;
6941         if (Shift->getOpcode() == Instruction::LShr) {
6942           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6943         } else {
6944           // Insert a logical shift.
6945           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6946         }
6947         
6948         // Compute X & (C << Y).
6949         Value *NewAnd = 
6950           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6951         
6952         ICI.setOperand(0, NewAnd);
6953         return &ICI;
6954       }
6955     }
6956     break;
6957     
6958   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6959     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6960     if (!ShAmt) break;
6961     
6962     uint32_t TypeBits = RHSV.getBitWidth();
6963     
6964     // Check that the shift amount is in range.  If not, don't perform
6965     // undefined shifts.  When the shift is visited it will be
6966     // simplified.
6967     if (ShAmt->uge(TypeBits))
6968       break;
6969     
6970     if (ICI.isEquality()) {
6971       // If we are comparing against bits always shifted out, the
6972       // comparison cannot succeed.
6973       Constant *Comp =
6974         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6975                                                                  ShAmt);
6976       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6977         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6978         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6979         return ReplaceInstUsesWith(ICI, Cst);
6980       }
6981       
6982       if (LHSI->hasOneUse()) {
6983         // Otherwise strength reduce the shift into an and.
6984         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6985         Constant *Mask =
6986           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6987                                                        TypeBits-ShAmtVal));
6988         
6989         Value *And =
6990           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6991         return new ICmpInst(ICI.getPredicate(), And,
6992                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6993       }
6994     }
6995     
6996     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6997     bool TrueIfSigned = false;
6998     if (LHSI->hasOneUse() &&
6999         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7000       // (X << 31) <s 0  --> (X&1) != 0
7001       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
7002                                            (TypeBits-ShAmt->getZExtValue()-1));
7003       Value *And =
7004         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
7005       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
7006                           And, Constant::getNullValue(And->getType()));
7007     }
7008     break;
7009   }
7010     
7011   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
7012   case Instruction::AShr: {
7013     // Only handle equality comparisons of shift-by-constant.
7014     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7015     if (!ShAmt || !ICI.isEquality()) break;
7016
7017     // Check that the shift amount is in range.  If not, don't perform
7018     // undefined shifts.  When the shift is visited it will be
7019     // simplified.
7020     uint32_t TypeBits = RHSV.getBitWidth();
7021     if (ShAmt->uge(TypeBits))
7022       break;
7023     
7024     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7025       
7026     // If we are comparing against bits always shifted out, the
7027     // comparison cannot succeed.
7028     APInt Comp = RHSV << ShAmtVal;
7029     if (LHSI->getOpcode() == Instruction::LShr)
7030       Comp = Comp.lshr(ShAmtVal);
7031     else
7032       Comp = Comp.ashr(ShAmtVal);
7033     
7034     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7035       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7036       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7037       return ReplaceInstUsesWith(ICI, Cst);
7038     }
7039     
7040     // Otherwise, check to see if the bits shifted out are known to be zero.
7041     // If so, we can compare against the unshifted value:
7042     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7043     if (LHSI->hasOneUse() &&
7044         MaskedValueIsZero(LHSI->getOperand(0), 
7045                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7046       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
7047                           ConstantExpr::getShl(RHS, ShAmt));
7048     }
7049       
7050     if (LHSI->hasOneUse()) {
7051       // Otherwise strength reduce the shift into an and.
7052       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7053       Constant *Mask = ConstantInt::get(*Context, Val);
7054       
7055       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7056                                       Mask, LHSI->getName()+".mask");
7057       return new ICmpInst(ICI.getPredicate(), And,
7058                           ConstantExpr::getShl(RHS, ShAmt));
7059     }
7060     break;
7061   }
7062     
7063   case Instruction::SDiv:
7064   case Instruction::UDiv:
7065     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7066     // Fold this div into the comparison, producing a range check. 
7067     // Determine, based on the divide type, what the range is being 
7068     // checked.  If there is an overflow on the low or high side, remember 
7069     // it, otherwise compute the range [low, hi) bounding the new value.
7070     // See: InsertRangeTest above for the kinds of replacements possible.
7071     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7072       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7073                                           DivRHS))
7074         return R;
7075     break;
7076
7077   case Instruction::Add:
7078     // Fold: icmp pred (add, X, C1), C2
7079
7080     if (!ICI.isEquality()) {
7081       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7082       if (!LHSC) break;
7083       const APInt &LHSV = LHSC->getValue();
7084
7085       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7086                             .subtract(LHSV);
7087
7088       if (ICI.isSigned()) {
7089         if (CR.getLower().isSignBit()) {
7090           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7091                               ConstantInt::get(*Context, CR.getUpper()));
7092         } else if (CR.getUpper().isSignBit()) {
7093           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7094                               ConstantInt::get(*Context, CR.getLower()));
7095         }
7096       } else {
7097         if (CR.getLower().isMinValue()) {
7098           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7099                               ConstantInt::get(*Context, CR.getUpper()));
7100         } else if (CR.getUpper().isMinValue()) {
7101           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7102                               ConstantInt::get(*Context, CR.getLower()));
7103         }
7104       }
7105     }
7106     break;
7107   }
7108   
7109   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7110   if (ICI.isEquality()) {
7111     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7112     
7113     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7114     // the second operand is a constant, simplify a bit.
7115     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7116       switch (BO->getOpcode()) {
7117       case Instruction::SRem:
7118         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7119         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7120           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7121           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7122             Value *NewRem =
7123               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7124                                   BO->getName());
7125             return new ICmpInst(ICI.getPredicate(), NewRem,
7126                                 Constant::getNullValue(BO->getType()));
7127           }
7128         }
7129         break;
7130       case Instruction::Add:
7131         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7132         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7133           if (BO->hasOneUse())
7134             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7135                                 ConstantExpr::getSub(RHS, BOp1C));
7136         } else if (RHSV == 0) {
7137           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7138           // efficiently invertible, or if the add has just this one use.
7139           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7140           
7141           if (Value *NegVal = dyn_castNegVal(BOp1))
7142             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7143           else if (Value *NegVal = dyn_castNegVal(BOp0))
7144             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7145           else if (BO->hasOneUse()) {
7146             Value *Neg = Builder->CreateNeg(BOp1);
7147             Neg->takeName(BO);
7148             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7149           }
7150         }
7151         break;
7152       case Instruction::Xor:
7153         // For the xor case, we can xor two constants together, eliminating
7154         // the explicit xor.
7155         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7156           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7157                               ConstantExpr::getXor(RHS, BOC));
7158         
7159         // FALLTHROUGH
7160       case Instruction::Sub:
7161         // Replace (([sub|xor] A, B) != 0) with (A != B)
7162         if (RHSV == 0)
7163           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7164                               BO->getOperand(1));
7165         break;
7166         
7167       case Instruction::Or:
7168         // If bits are being or'd in that are not present in the constant we
7169         // are comparing against, then the comparison could never succeed!
7170         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7171           Constant *NotCI = ConstantExpr::getNot(RHS);
7172           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7173             return ReplaceInstUsesWith(ICI,
7174                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7175                                        isICMP_NE));
7176         }
7177         break;
7178         
7179       case Instruction::And:
7180         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7181           // If bits are being compared against that are and'd out, then the
7182           // comparison can never succeed!
7183           if ((RHSV & ~BOC->getValue()) != 0)
7184             return ReplaceInstUsesWith(ICI,
7185                                        ConstantInt::get(Type::getInt1Ty(*Context),
7186                                        isICMP_NE));
7187           
7188           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7189           if (RHS == BOC && RHSV.isPowerOf2())
7190             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7191                                 ICmpInst::ICMP_NE, LHSI,
7192                                 Constant::getNullValue(RHS->getType()));
7193           
7194           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7195           if (BOC->getValue().isSignBit()) {
7196             Value *X = BO->getOperand(0);
7197             Constant *Zero = Constant::getNullValue(X->getType());
7198             ICmpInst::Predicate pred = isICMP_NE ? 
7199               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7200             return new ICmpInst(pred, X, Zero);
7201           }
7202           
7203           // ((X & ~7) == 0) --> X < 8
7204           if (RHSV == 0 && isHighOnes(BOC)) {
7205             Value *X = BO->getOperand(0);
7206             Constant *NegX = ConstantExpr::getNeg(BOC);
7207             ICmpInst::Predicate pred = isICMP_NE ? 
7208               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7209             return new ICmpInst(pred, X, NegX);
7210           }
7211         }
7212       default: break;
7213       }
7214     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7215       // Handle icmp {eq|ne} <intrinsic>, intcst.
7216       if (II->getIntrinsicID() == Intrinsic::bswap) {
7217         Worklist.Add(II);
7218         ICI.setOperand(0, II->getOperand(1));
7219         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7220         return &ICI;
7221       }
7222     }
7223   }
7224   return 0;
7225 }
7226
7227 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7228 /// We only handle extending casts so far.
7229 ///
7230 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7231   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7232   Value *LHSCIOp        = LHSCI->getOperand(0);
7233   const Type *SrcTy     = LHSCIOp->getType();
7234   const Type *DestTy    = LHSCI->getType();
7235   Value *RHSCIOp;
7236
7237   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7238   // integer type is the same size as the pointer type.
7239   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7240       TD->getPointerSizeInBits() ==
7241          cast<IntegerType>(DestTy)->getBitWidth()) {
7242     Value *RHSOp = 0;
7243     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7244       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7245     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7246       RHSOp = RHSC->getOperand(0);
7247       // If the pointer types don't match, insert a bitcast.
7248       if (LHSCIOp->getType() != RHSOp->getType())
7249         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7250     }
7251
7252     if (RHSOp)
7253       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7254   }
7255   
7256   // The code below only handles extension cast instructions, so far.
7257   // Enforce this.
7258   if (LHSCI->getOpcode() != Instruction::ZExt &&
7259       LHSCI->getOpcode() != Instruction::SExt)
7260     return 0;
7261
7262   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7263   bool isSignedCmp = ICI.isSigned();
7264
7265   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7266     // Not an extension from the same type?
7267     RHSCIOp = CI->getOperand(0);
7268     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7269       return 0;
7270     
7271     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7272     // and the other is a zext), then we can't handle this.
7273     if (CI->getOpcode() != LHSCI->getOpcode())
7274       return 0;
7275
7276     // Deal with equality cases early.
7277     if (ICI.isEquality())
7278       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7279
7280     // A signed comparison of sign extended values simplifies into a
7281     // signed comparison.
7282     if (isSignedCmp && isSignedExt)
7283       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7284
7285     // The other three cases all fold into an unsigned comparison.
7286     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7287   }
7288
7289   // If we aren't dealing with a constant on the RHS, exit early
7290   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7291   if (!CI)
7292     return 0;
7293
7294   // Compute the constant that would happen if we truncated to SrcTy then
7295   // reextended to DestTy.
7296   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7297   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7298                                                 Res1, DestTy);
7299
7300   // If the re-extended constant didn't change...
7301   if (Res2 == CI) {
7302     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7303     // For example, we might have:
7304     //    %A = sext i16 %X to i32
7305     //    %B = icmp ugt i32 %A, 1330
7306     // It is incorrect to transform this into 
7307     //    %B = icmp ugt i16 %X, 1330
7308     // because %A may have negative value. 
7309     //
7310     // However, we allow this when the compare is EQ/NE, because they are
7311     // signless.
7312     if (isSignedExt == isSignedCmp || ICI.isEquality())
7313       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7314     return 0;
7315   }
7316
7317   // The re-extended constant changed so the constant cannot be represented 
7318   // in the shorter type. Consequently, we cannot emit a simple comparison.
7319
7320   // First, handle some easy cases. We know the result cannot be equal at this
7321   // point so handle the ICI.isEquality() cases
7322   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7323     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7324   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7325     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7326
7327   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7328   // should have been folded away previously and not enter in here.
7329   Value *Result;
7330   if (isSignedCmp) {
7331     // We're performing a signed comparison.
7332     if (cast<ConstantInt>(CI)->getValue().isNegative())
7333       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7334     else
7335       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7336   } else {
7337     // We're performing an unsigned comparison.
7338     if (isSignedExt) {
7339       // We're performing an unsigned comp with a sign extended value.
7340       // This is true if the input is >= 0. [aka >s -1]
7341       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7342       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7343     } else {
7344       // Unsigned extend & unsigned compare -> always true.
7345       Result = ConstantInt::getTrue(*Context);
7346     }
7347   }
7348
7349   // Finally, return the value computed.
7350   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7351       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7352     return ReplaceInstUsesWith(ICI, Result);
7353
7354   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7355           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7356          "ICmp should be folded!");
7357   if (Constant *CI = dyn_cast<Constant>(Result))
7358     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7359   return BinaryOperator::CreateNot(Result);
7360 }
7361
7362 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7363   return commonShiftTransforms(I);
7364 }
7365
7366 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7367   return commonShiftTransforms(I);
7368 }
7369
7370 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7371   if (Instruction *R = commonShiftTransforms(I))
7372     return R;
7373   
7374   Value *Op0 = I.getOperand(0);
7375   
7376   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7377   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7378     if (CSI->isAllOnesValue())
7379       return ReplaceInstUsesWith(I, CSI);
7380
7381   // See if we can turn a signed shr into an unsigned shr.
7382   if (MaskedValueIsZero(Op0,
7383                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7384     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7385
7386   // Arithmetic shifting an all-sign-bit value is a no-op.
7387   unsigned NumSignBits = ComputeNumSignBits(Op0);
7388   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7389     return ReplaceInstUsesWith(I, Op0);
7390
7391   return 0;
7392 }
7393
7394 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7395   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7396   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7397
7398   // shl X, 0 == X and shr X, 0 == X
7399   // shl 0, X == 0 and shr 0, X == 0
7400   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7401       Op0 == Constant::getNullValue(Op0->getType()))
7402     return ReplaceInstUsesWith(I, Op0);
7403   
7404   if (isa<UndefValue>(Op0)) {            
7405     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7406       return ReplaceInstUsesWith(I, Op0);
7407     else                                    // undef << X -> 0, undef >>u X -> 0
7408       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7409   }
7410   if (isa<UndefValue>(Op1)) {
7411     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7412       return ReplaceInstUsesWith(I, Op0);          
7413     else                                     // X << undef, X >>u undef -> 0
7414       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7415   }
7416
7417   // See if we can fold away this shift.
7418   if (SimplifyDemandedInstructionBits(I))
7419     return &I;
7420
7421   // Try to fold constant and into select arguments.
7422   if (isa<Constant>(Op0))
7423     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7424       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7425         return R;
7426
7427   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7428     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7429       return Res;
7430   return 0;
7431 }
7432
7433 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7434                                                BinaryOperator &I) {
7435   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7436
7437   // See if we can simplify any instructions used by the instruction whose sole 
7438   // purpose is to compute bits we don't care about.
7439   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7440   
7441   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7442   // a signed shift.
7443   //
7444   if (Op1->uge(TypeBits)) {
7445     if (I.getOpcode() != Instruction::AShr)
7446       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7447     else {
7448       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7449       return &I;
7450     }
7451   }
7452   
7453   // ((X*C1) << C2) == (X * (C1 << C2))
7454   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7455     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7456       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7457         return BinaryOperator::CreateMul(BO->getOperand(0),
7458                                         ConstantExpr::getShl(BOOp, Op1));
7459   
7460   // Try to fold constant and into select arguments.
7461   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7462     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7463       return R;
7464   if (isa<PHINode>(Op0))
7465     if (Instruction *NV = FoldOpIntoPhi(I))
7466       return NV;
7467   
7468   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7469   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7470     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7471     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7472     // place.  Don't try to do this transformation in this case.  Also, we
7473     // require that the input operand is a shift-by-constant so that we have
7474     // confidence that the shifts will get folded together.  We could do this
7475     // xform in more cases, but it is unlikely to be profitable.
7476     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7477         isa<ConstantInt>(TrOp->getOperand(1))) {
7478       // Okay, we'll do this xform.  Make the shift of shift.
7479       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7480       // (shift2 (shift1 & 0x00FF), c2)
7481       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7482
7483       // For logical shifts, the truncation has the effect of making the high
7484       // part of the register be zeros.  Emulate this by inserting an AND to
7485       // clear the top bits as needed.  This 'and' will usually be zapped by
7486       // other xforms later if dead.
7487       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7488       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7489       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7490       
7491       // The mask we constructed says what the trunc would do if occurring
7492       // between the shifts.  We want to know the effect *after* the second
7493       // shift.  We know that it is a logical shift by a constant, so adjust the
7494       // mask as appropriate.
7495       if (I.getOpcode() == Instruction::Shl)
7496         MaskV <<= Op1->getZExtValue();
7497       else {
7498         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7499         MaskV = MaskV.lshr(Op1->getZExtValue());
7500       }
7501
7502       // shift1 & 0x00FF
7503       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7504                                       TI->getName());
7505
7506       // Return the value truncated to the interesting size.
7507       return new TruncInst(And, I.getType());
7508     }
7509   }
7510   
7511   if (Op0->hasOneUse()) {
7512     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7513       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7514       Value *V1, *V2;
7515       ConstantInt *CC;
7516       switch (Op0BO->getOpcode()) {
7517         default: break;
7518         case Instruction::Add:
7519         case Instruction::And:
7520         case Instruction::Or:
7521         case Instruction::Xor: {
7522           // These operators commute.
7523           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7524           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7525               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7526                     m_Specific(Op1)))) {
7527             Value *YS =         // (Y << C)
7528               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7529             // (X + (Y << C))
7530             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7531                                             Op0BO->getOperand(1)->getName());
7532             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7533             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7534                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7535           }
7536           
7537           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7538           Value *Op0BOOp1 = Op0BO->getOperand(1);
7539           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7540               match(Op0BOOp1, 
7541                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7542                           m_ConstantInt(CC))) &&
7543               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7544             Value *YS =   // (Y << C)
7545               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7546                                            Op0BO->getName());
7547             // X & (CC << C)
7548             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7549                                            V1->getName()+".mask");
7550             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7551           }
7552         }
7553           
7554         // FALL THROUGH.
7555         case Instruction::Sub: {
7556           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7557           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7558               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7559                     m_Specific(Op1)))) {
7560             Value *YS =  // (Y << C)
7561               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7562             // (X + (Y << C))
7563             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7564                                             Op0BO->getOperand(0)->getName());
7565             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7566             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7567                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7568           }
7569           
7570           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7571           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7572               match(Op0BO->getOperand(0),
7573                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7574                           m_ConstantInt(CC))) && V2 == Op1 &&
7575               cast<BinaryOperator>(Op0BO->getOperand(0))
7576                   ->getOperand(0)->hasOneUse()) {
7577             Value *YS = // (Y << C)
7578               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7579             // X & (CC << C)
7580             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7581                                            V1->getName()+".mask");
7582             
7583             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7584           }
7585           
7586           break;
7587         }
7588       }
7589       
7590       
7591       // If the operand is an bitwise operator with a constant RHS, and the
7592       // shift is the only use, we can pull it out of the shift.
7593       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7594         bool isValid = true;     // Valid only for And, Or, Xor
7595         bool highBitSet = false; // Transform if high bit of constant set?
7596         
7597         switch (Op0BO->getOpcode()) {
7598           default: isValid = false; break;   // Do not perform transform!
7599           case Instruction::Add:
7600             isValid = isLeftShift;
7601             break;
7602           case Instruction::Or:
7603           case Instruction::Xor:
7604             highBitSet = false;
7605             break;
7606           case Instruction::And:
7607             highBitSet = true;
7608             break;
7609         }
7610         
7611         // If this is a signed shift right, and the high bit is modified
7612         // by the logical operation, do not perform the transformation.
7613         // The highBitSet boolean indicates the value of the high bit of
7614         // the constant which would cause it to be modified for this
7615         // operation.
7616         //
7617         if (isValid && I.getOpcode() == Instruction::AShr)
7618           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7619         
7620         if (isValid) {
7621           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7622           
7623           Value *NewShift =
7624             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7625           NewShift->takeName(Op0BO);
7626           
7627           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7628                                         NewRHS);
7629         }
7630       }
7631     }
7632   }
7633   
7634   // Find out if this is a shift of a shift by a constant.
7635   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7636   if (ShiftOp && !ShiftOp->isShift())
7637     ShiftOp = 0;
7638   
7639   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7640     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7641     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7642     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7643     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7644     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7645     Value *X = ShiftOp->getOperand(0);
7646     
7647     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7648     
7649     const IntegerType *Ty = cast<IntegerType>(I.getType());
7650     
7651     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7652     if (I.getOpcode() == ShiftOp->getOpcode()) {
7653       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7654       // saturates.
7655       if (AmtSum >= TypeBits) {
7656         if (I.getOpcode() != Instruction::AShr)
7657           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7658         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7659       }
7660       
7661       return BinaryOperator::Create(I.getOpcode(), X,
7662                                     ConstantInt::get(Ty, AmtSum));
7663     }
7664     
7665     if (ShiftOp->getOpcode() == Instruction::LShr &&
7666         I.getOpcode() == Instruction::AShr) {
7667       if (AmtSum >= TypeBits)
7668         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7669       
7670       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7671       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7672     }
7673     
7674     if (ShiftOp->getOpcode() == Instruction::AShr &&
7675         I.getOpcode() == Instruction::LShr) {
7676       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7677       if (AmtSum >= TypeBits)
7678         AmtSum = TypeBits-1;
7679       
7680       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7681
7682       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7683       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7684     }
7685     
7686     // Okay, if we get here, one shift must be left, and the other shift must be
7687     // right.  See if the amounts are equal.
7688     if (ShiftAmt1 == ShiftAmt2) {
7689       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7690       if (I.getOpcode() == Instruction::Shl) {
7691         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7692         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7693       }
7694       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7695       if (I.getOpcode() == Instruction::LShr) {
7696         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7697         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7698       }
7699       // We can simplify ((X << C) >>s C) into a trunc + sext.
7700       // NOTE: we could do this for any C, but that would make 'unusual' integer
7701       // types.  For now, just stick to ones well-supported by the code
7702       // generators.
7703       const Type *SExtType = 0;
7704       switch (Ty->getBitWidth() - ShiftAmt1) {
7705       case 1  :
7706       case 8  :
7707       case 16 :
7708       case 32 :
7709       case 64 :
7710       case 128:
7711         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7712         break;
7713       default: break;
7714       }
7715       if (SExtType)
7716         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7717       // Otherwise, we can't handle it yet.
7718     } else if (ShiftAmt1 < ShiftAmt2) {
7719       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7720       
7721       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7722       if (I.getOpcode() == Instruction::Shl) {
7723         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7724                ShiftOp->getOpcode() == Instruction::AShr);
7725         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7726         
7727         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7728         return BinaryOperator::CreateAnd(Shift,
7729                                          ConstantInt::get(*Context, Mask));
7730       }
7731       
7732       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7733       if (I.getOpcode() == Instruction::LShr) {
7734         assert(ShiftOp->getOpcode() == Instruction::Shl);
7735         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7736         
7737         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7738         return BinaryOperator::CreateAnd(Shift,
7739                                          ConstantInt::get(*Context, Mask));
7740       }
7741       
7742       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7743     } else {
7744       assert(ShiftAmt2 < ShiftAmt1);
7745       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7746
7747       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7748       if (I.getOpcode() == Instruction::Shl) {
7749         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7750                ShiftOp->getOpcode() == Instruction::AShr);
7751         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7752                                             ConstantInt::get(Ty, ShiftDiff));
7753         
7754         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7755         return BinaryOperator::CreateAnd(Shift,
7756                                          ConstantInt::get(*Context, Mask));
7757       }
7758       
7759       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7760       if (I.getOpcode() == Instruction::LShr) {
7761         assert(ShiftOp->getOpcode() == Instruction::Shl);
7762         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7763         
7764         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7765         return BinaryOperator::CreateAnd(Shift,
7766                                          ConstantInt::get(*Context, Mask));
7767       }
7768       
7769       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7770     }
7771   }
7772   return 0;
7773 }
7774
7775
7776 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7777 /// expression.  If so, decompose it, returning some value X, such that Val is
7778 /// X*Scale+Offset.
7779 ///
7780 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7781                                         int &Offset, LLVMContext *Context) {
7782   assert(Val->getType() == Type::getInt32Ty(*Context) && 
7783          "Unexpected allocation size type!");
7784   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7785     Offset = CI->getZExtValue();
7786     Scale  = 0;
7787     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7788   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7789     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7790       if (I->getOpcode() == Instruction::Shl) {
7791         // This is a value scaled by '1 << the shift amt'.
7792         Scale = 1U << RHS->getZExtValue();
7793         Offset = 0;
7794         return I->getOperand(0);
7795       } else if (I->getOpcode() == Instruction::Mul) {
7796         // This value is scaled by 'RHS'.
7797         Scale = RHS->getZExtValue();
7798         Offset = 0;
7799         return I->getOperand(0);
7800       } else if (I->getOpcode() == Instruction::Add) {
7801         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7802         // where C1 is divisible by C2.
7803         unsigned SubScale;
7804         Value *SubVal = 
7805           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7806                                     Offset, Context);
7807         Offset += RHS->getZExtValue();
7808         Scale = SubScale;
7809         return SubVal;
7810       }
7811     }
7812   }
7813
7814   // Otherwise, we can't look past this.
7815   Scale = 1;
7816   Offset = 0;
7817   return Val;
7818 }
7819
7820
7821 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7822 /// try to eliminate the cast by moving the type information into the alloc.
7823 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7824                                                    AllocaInst &AI) {
7825   const PointerType *PTy = cast<PointerType>(CI.getType());
7826   
7827   BuilderTy AllocaBuilder(*Builder);
7828   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7829   
7830   // Remove any uses of AI that are dead.
7831   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7832   
7833   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7834     Instruction *User = cast<Instruction>(*UI++);
7835     if (isInstructionTriviallyDead(User)) {
7836       while (UI != E && *UI == User)
7837         ++UI; // If this instruction uses AI more than once, don't break UI.
7838       
7839       ++NumDeadInst;
7840       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7841       EraseInstFromFunction(*User);
7842     }
7843   }
7844
7845   // This requires TargetData to get the alloca alignment and size information.
7846   if (!TD) return 0;
7847
7848   // Get the type really allocated and the type casted to.
7849   const Type *AllocElTy = AI.getAllocatedType();
7850   const Type *CastElTy = PTy->getElementType();
7851   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7852
7853   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7854   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7855   if (CastElTyAlign < AllocElTyAlign) return 0;
7856
7857   // If the allocation has multiple uses, only promote it if we are strictly
7858   // increasing the alignment of the resultant allocation.  If we keep it the
7859   // same, we open the door to infinite loops of various kinds.  (A reference
7860   // from a dbg.declare doesn't count as a use for this purpose.)
7861   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7862       CastElTyAlign == AllocElTyAlign) return 0;
7863
7864   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7865   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7866   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7867
7868   // See if we can satisfy the modulus by pulling a scale out of the array
7869   // size argument.
7870   unsigned ArraySizeScale;
7871   int ArrayOffset;
7872   Value *NumElements = // See if the array size is a decomposable linear expr.
7873     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7874                               ArrayOffset, Context);
7875  
7876   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7877   // do the xform.
7878   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7879       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7880
7881   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7882   Value *Amt = 0;
7883   if (Scale == 1) {
7884     Amt = NumElements;
7885   } else {
7886     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7887     // Insert before the alloca, not before the cast.
7888     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7889   }
7890   
7891   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7892     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7893     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7894   }
7895   
7896   AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7897   New->setAlignment(AI.getAlignment());
7898   New->takeName(&AI);
7899   
7900   // If the allocation has one real use plus a dbg.declare, just remove the
7901   // declare.
7902   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7903     EraseInstFromFunction(*DI);
7904   }
7905   // If the allocation has multiple real uses, insert a cast and change all
7906   // things that used it to use the new cast.  This will also hack on CI, but it
7907   // will die soon.
7908   else if (!AI.hasOneUse()) {
7909     // New is the allocation instruction, pointer typed. AI is the original
7910     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7911     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7912     AI.replaceAllUsesWith(NewCast);
7913   }
7914   return ReplaceInstUsesWith(CI, New);
7915 }
7916
7917 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7918 /// and return it as type Ty without inserting any new casts and without
7919 /// changing the computed value.  This is used by code that tries to decide
7920 /// whether promoting or shrinking integer operations to wider or smaller types
7921 /// will allow us to eliminate a truncate or extend.
7922 ///
7923 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7924 /// extension operation if Ty is larger.
7925 ///
7926 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7927 /// should return true if trunc(V) can be computed by computing V in the smaller
7928 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7929 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7930 /// efficiently truncated.
7931 ///
7932 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7933 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7934 /// the final result.
7935 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7936                                               unsigned CastOpc,
7937                                               int &NumCastsRemoved){
7938   // We can always evaluate constants in another type.
7939   if (isa<Constant>(V))
7940     return true;
7941   
7942   Instruction *I = dyn_cast<Instruction>(V);
7943   if (!I) return false;
7944   
7945   const Type *OrigTy = V->getType();
7946   
7947   // If this is an extension or truncate, we can often eliminate it.
7948   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7949     // If this is a cast from the destination type, we can trivially eliminate
7950     // it, and this will remove a cast overall.
7951     if (I->getOperand(0)->getType() == Ty) {
7952       // If the first operand is itself a cast, and is eliminable, do not count
7953       // this as an eliminable cast.  We would prefer to eliminate those two
7954       // casts first.
7955       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7956         ++NumCastsRemoved;
7957       return true;
7958     }
7959   }
7960
7961   // We can't extend or shrink something that has multiple uses: doing so would
7962   // require duplicating the instruction in general, which isn't profitable.
7963   if (!I->hasOneUse()) return false;
7964
7965   unsigned Opc = I->getOpcode();
7966   switch (Opc) {
7967   case Instruction::Add:
7968   case Instruction::Sub:
7969   case Instruction::Mul:
7970   case Instruction::And:
7971   case Instruction::Or:
7972   case Instruction::Xor:
7973     // These operators can all arbitrarily be extended or truncated.
7974     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7975                                       NumCastsRemoved) &&
7976            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7977                                       NumCastsRemoved);
7978
7979   case Instruction::UDiv:
7980   case Instruction::URem: {
7981     // UDiv and URem can be truncated if all the truncated bits are zero.
7982     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7983     uint32_t BitWidth = Ty->getScalarSizeInBits();
7984     if (BitWidth < OrigBitWidth) {
7985       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7986       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7987           MaskedValueIsZero(I->getOperand(1), Mask)) {
7988         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7989                                           NumCastsRemoved) &&
7990                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7991                                           NumCastsRemoved);
7992       }
7993     }
7994     break;
7995   }
7996   case Instruction::Shl:
7997     // If we are truncating the result of this SHL, and if it's a shift of a
7998     // constant amount, we can always perform a SHL in a smaller type.
7999     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8000       uint32_t BitWidth = Ty->getScalarSizeInBits();
8001       if (BitWidth < OrigTy->getScalarSizeInBits() &&
8002           CI->getLimitedValue(BitWidth) < BitWidth)
8003         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8004                                           NumCastsRemoved);
8005     }
8006     break;
8007   case Instruction::LShr:
8008     // If this is a truncate of a logical shr, we can truncate it to a smaller
8009     // lshr iff we know that the bits we would otherwise be shifting in are
8010     // already zeros.
8011     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8012       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8013       uint32_t BitWidth = Ty->getScalarSizeInBits();
8014       if (BitWidth < OrigBitWidth &&
8015           MaskedValueIsZero(I->getOperand(0),
8016             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8017           CI->getLimitedValue(BitWidth) < BitWidth) {
8018         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8019                                           NumCastsRemoved);
8020       }
8021     }
8022     break;
8023   case Instruction::ZExt:
8024   case Instruction::SExt:
8025   case Instruction::Trunc:
8026     // If this is the same kind of case as our original (e.g. zext+zext), we
8027     // can safely replace it.  Note that replacing it does not reduce the number
8028     // of casts in the input.
8029     if (Opc == CastOpc)
8030       return true;
8031
8032     // sext (zext ty1), ty2 -> zext ty2
8033     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8034       return true;
8035     break;
8036   case Instruction::Select: {
8037     SelectInst *SI = cast<SelectInst>(I);
8038     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8039                                       NumCastsRemoved) &&
8040            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8041                                       NumCastsRemoved);
8042   }
8043   case Instruction::PHI: {
8044     // We can change a phi if we can change all operands.
8045     PHINode *PN = cast<PHINode>(I);
8046     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8047       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8048                                       NumCastsRemoved))
8049         return false;
8050     return true;
8051   }
8052   default:
8053     // TODO: Can handle more cases here.
8054     break;
8055   }
8056   
8057   return false;
8058 }
8059
8060 /// EvaluateInDifferentType - Given an expression that 
8061 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8062 /// evaluate the expression.
8063 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8064                                              bool isSigned) {
8065   if (Constant *C = dyn_cast<Constant>(V))
8066     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
8067
8068   // Otherwise, it must be an instruction.
8069   Instruction *I = cast<Instruction>(V);
8070   Instruction *Res = 0;
8071   unsigned Opc = I->getOpcode();
8072   switch (Opc) {
8073   case Instruction::Add:
8074   case Instruction::Sub:
8075   case Instruction::Mul:
8076   case Instruction::And:
8077   case Instruction::Or:
8078   case Instruction::Xor:
8079   case Instruction::AShr:
8080   case Instruction::LShr:
8081   case Instruction::Shl:
8082   case Instruction::UDiv:
8083   case Instruction::URem: {
8084     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8085     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8086     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8087     break;
8088   }    
8089   case Instruction::Trunc:
8090   case Instruction::ZExt:
8091   case Instruction::SExt:
8092     // If the source type of the cast is the type we're trying for then we can
8093     // just return the source.  There's no need to insert it because it is not
8094     // new.
8095     if (I->getOperand(0)->getType() == Ty)
8096       return I->getOperand(0);
8097     
8098     // Otherwise, must be the same type of cast, so just reinsert a new one.
8099     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
8100     break;
8101   case Instruction::Select: {
8102     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8103     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8104     Res = SelectInst::Create(I->getOperand(0), True, False);
8105     break;
8106   }
8107   case Instruction::PHI: {
8108     PHINode *OPN = cast<PHINode>(I);
8109     PHINode *NPN = PHINode::Create(Ty);
8110     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8111       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8112       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8113     }
8114     Res = NPN;
8115     break;
8116   }
8117   default: 
8118     // TODO: Can handle more cases here.
8119     llvm_unreachable("Unreachable!");
8120     break;
8121   }
8122   
8123   Res->takeName(I);
8124   return InsertNewInstBefore(Res, *I);
8125 }
8126
8127 /// @brief Implement the transforms common to all CastInst visitors.
8128 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8129   Value *Src = CI.getOperand(0);
8130
8131   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8132   // eliminate it now.
8133   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8134     if (Instruction::CastOps opc = 
8135         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8136       // The first cast (CSrc) is eliminable so we need to fix up or replace
8137       // the second cast (CI). CSrc will then have a good chance of being dead.
8138       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8139     }
8140   }
8141
8142   // If we are casting a select then fold the cast into the select
8143   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8144     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8145       return NV;
8146
8147   // If we are casting a PHI then fold the cast into the PHI
8148   if (isa<PHINode>(Src)) {
8149     // We don't do this if this would create a PHI node with an illegal type if
8150     // it is currently legal.
8151     if (!isa<IntegerType>(Src->getType()) ||
8152         !isa<IntegerType>(CI.getType()) ||
8153         ShouldChangeType(CI.getType(), Src->getType(), TD))
8154       if (Instruction *NV = FoldOpIntoPhi(CI))
8155         return NV;
8156   }
8157   
8158   return 0;
8159 }
8160
8161 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8162 /// or not there is a sequence of GEP indices into the type that will land us at
8163 /// the specified offset.  If so, fill them into NewIndices and return the
8164 /// resultant element type, otherwise return null.
8165 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8166                                        SmallVectorImpl<Value*> &NewIndices,
8167                                        const TargetData *TD,
8168                                        LLVMContext *Context) {
8169   if (!TD) return 0;
8170   if (!Ty->isSized()) return 0;
8171   
8172   // Start with the index over the outer type.  Note that the type size
8173   // might be zero (even if the offset isn't zero) if the indexed type
8174   // is something like [0 x {int, int}]
8175   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8176   int64_t FirstIdx = 0;
8177   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8178     FirstIdx = Offset/TySize;
8179     Offset -= FirstIdx*TySize;
8180     
8181     // Handle hosts where % returns negative instead of values [0..TySize).
8182     if (Offset < 0) {
8183       --FirstIdx;
8184       Offset += TySize;
8185       assert(Offset >= 0);
8186     }
8187     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8188   }
8189   
8190   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8191     
8192   // Index into the types.  If we fail, set OrigBase to null.
8193   while (Offset) {
8194     // Indexing into tail padding between struct/array elements.
8195     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8196       return 0;
8197     
8198     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8199       const StructLayout *SL = TD->getStructLayout(STy);
8200       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8201              "Offset must stay within the indexed type");
8202       
8203       unsigned Elt = SL->getElementContainingOffset(Offset);
8204       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8205       
8206       Offset -= SL->getElementOffset(Elt);
8207       Ty = STy->getElementType(Elt);
8208     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8209       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8210       assert(EltSize && "Cannot index into a zero-sized array");
8211       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8212       Offset %= EltSize;
8213       Ty = AT->getElementType();
8214     } else {
8215       // Otherwise, we can't index into the middle of this atomic type, bail.
8216       return 0;
8217     }
8218   }
8219   
8220   return Ty;
8221 }
8222
8223 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8224 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8225   Value *Src = CI.getOperand(0);
8226   
8227   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8228     // If casting the result of a getelementptr instruction with no offset, turn
8229     // this into a cast of the original pointer!
8230     if (GEP->hasAllZeroIndices()) {
8231       // Changing the cast operand is usually not a good idea but it is safe
8232       // here because the pointer operand is being replaced with another 
8233       // pointer operand so the opcode doesn't need to change.
8234       Worklist.Add(GEP);
8235       CI.setOperand(0, GEP->getOperand(0));
8236       return &CI;
8237     }
8238     
8239     // If the GEP has a single use, and the base pointer is a bitcast, and the
8240     // GEP computes a constant offset, see if we can convert these three
8241     // instructions into fewer.  This typically happens with unions and other
8242     // non-type-safe code.
8243     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8244       if (GEP->hasAllConstantIndices()) {
8245         // We are guaranteed to get a constant from EmitGEPOffset.
8246         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
8247         int64_t Offset = OffsetV->getSExtValue();
8248         
8249         // Get the base pointer input of the bitcast, and the type it points to.
8250         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8251         const Type *GEPIdxTy =
8252           cast<PointerType>(OrigBase->getType())->getElementType();
8253         SmallVector<Value*, 8> NewIndices;
8254         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8255           // If we were able to index down into an element, create the GEP
8256           // and bitcast the result.  This eliminates one bitcast, potentially
8257           // two.
8258           Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8259             Builder->CreateInBoundsGEP(OrigBase,
8260                                        NewIndices.begin(), NewIndices.end()) :
8261             Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8262           NGEP->takeName(GEP);
8263           
8264           if (isa<BitCastInst>(CI))
8265             return new BitCastInst(NGEP, CI.getType());
8266           assert(isa<PtrToIntInst>(CI));
8267           return new PtrToIntInst(NGEP, CI.getType());
8268         }
8269       }      
8270     }
8271   }
8272     
8273   return commonCastTransforms(CI);
8274 }
8275
8276 /// commonIntCastTransforms - This function implements the common transforms
8277 /// for trunc, zext, and sext.
8278 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8279   if (Instruction *Result = commonCastTransforms(CI))
8280     return Result;
8281
8282   Value *Src = CI.getOperand(0);
8283   const Type *SrcTy = Src->getType();
8284   const Type *DestTy = CI.getType();
8285   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8286   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8287
8288   // See if we can simplify any instructions used by the LHS whose sole 
8289   // purpose is to compute bits we don't care about.
8290   if (SimplifyDemandedInstructionBits(CI))
8291     return &CI;
8292
8293   // If the source isn't an instruction or has more than one use then we
8294   // can't do anything more. 
8295   Instruction *SrcI = dyn_cast<Instruction>(Src);
8296   if (!SrcI || !Src->hasOneUse())
8297     return 0;
8298
8299   // Attempt to propagate the cast into the instruction for int->int casts.
8300   int NumCastsRemoved = 0;
8301   // Only do this if the dest type is a simple type, don't convert the
8302   // expression tree to something weird like i93 unless the source is also
8303   // strange.
8304   if ((isa<VectorType>(DestTy) ||
8305        ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8306       CanEvaluateInDifferentType(SrcI, DestTy,
8307                                  CI.getOpcode(), NumCastsRemoved)) {
8308     // If this cast is a truncate, evaluting in a different type always
8309     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8310     // we need to do an AND to maintain the clear top-part of the computation,
8311     // so we require that the input have eliminated at least one cast.  If this
8312     // is a sign extension, we insert two new casts (to do the extension) so we
8313     // require that two casts have been eliminated.
8314     bool DoXForm = false;
8315     bool JustReplace = false;
8316     switch (CI.getOpcode()) {
8317     default:
8318       // All the others use floating point so we shouldn't actually 
8319       // get here because of the check above.
8320       llvm_unreachable("Unknown cast type");
8321     case Instruction::Trunc:
8322       DoXForm = true;
8323       break;
8324     case Instruction::ZExt: {
8325       DoXForm = NumCastsRemoved >= 1;
8326       
8327       if (!DoXForm && 0) {
8328         // If it's unnecessary to issue an AND to clear the high bits, it's
8329         // always profitable to do this xform.
8330         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8331         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8332         if (MaskedValueIsZero(TryRes, Mask))
8333           return ReplaceInstUsesWith(CI, TryRes);
8334         
8335         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8336           if (TryI->use_empty())
8337             EraseInstFromFunction(*TryI);
8338       }
8339       break;
8340     }
8341     case Instruction::SExt: {
8342       DoXForm = NumCastsRemoved >= 2;
8343       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8344         // If we do not have to emit the truncate + sext pair, then it's always
8345         // profitable to do this xform.
8346         //
8347         // It's not safe to eliminate the trunc + sext pair if one of the
8348         // eliminated cast is a truncate. e.g.
8349         // t2 = trunc i32 t1 to i16
8350         // t3 = sext i16 t2 to i32
8351         // !=
8352         // i32 t1
8353         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8354         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8355         if (NumSignBits > (DestBitSize - SrcBitSize))
8356           return ReplaceInstUsesWith(CI, TryRes);
8357         
8358         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8359           if (TryI->use_empty())
8360             EraseInstFromFunction(*TryI);
8361       }
8362       break;
8363     }
8364     }
8365     
8366     if (DoXForm) {
8367       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8368             " to avoid cast: " << CI);
8369       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8370                                            CI.getOpcode() == Instruction::SExt);
8371       if (JustReplace)
8372         // Just replace this cast with the result.
8373         return ReplaceInstUsesWith(CI, Res);
8374
8375       assert(Res->getType() == DestTy);
8376       switch (CI.getOpcode()) {
8377       default: llvm_unreachable("Unknown cast type!");
8378       case Instruction::Trunc:
8379         // Just replace this cast with the result.
8380         return ReplaceInstUsesWith(CI, Res);
8381       case Instruction::ZExt: {
8382         assert(SrcBitSize < DestBitSize && "Not a zext?");
8383
8384         // If the high bits are already zero, just replace this cast with the
8385         // result.
8386         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8387         if (MaskedValueIsZero(Res, Mask))
8388           return ReplaceInstUsesWith(CI, Res);
8389
8390         // We need to emit an AND to clear the high bits.
8391         Constant *C = ConstantInt::get(*Context, 
8392                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8393         return BinaryOperator::CreateAnd(Res, C);
8394       }
8395       case Instruction::SExt: {
8396         // If the high bits are already filled with sign bit, just replace this
8397         // cast with the result.
8398         unsigned NumSignBits = ComputeNumSignBits(Res);
8399         if (NumSignBits > (DestBitSize - SrcBitSize))
8400           return ReplaceInstUsesWith(CI, Res);
8401
8402         // We need to emit a cast to truncate, then a cast to sext.
8403         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8404       }
8405       }
8406     }
8407   }
8408   
8409   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8410   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8411
8412   switch (SrcI->getOpcode()) {
8413   case Instruction::Add:
8414   case Instruction::Mul:
8415   case Instruction::And:
8416   case Instruction::Or:
8417   case Instruction::Xor:
8418     // If we are discarding information, rewrite.
8419     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8420       // Don't insert two casts unless at least one can be eliminated.
8421       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8422           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8423         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8424         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8425         return BinaryOperator::Create(
8426             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8427       }
8428     }
8429
8430     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8431     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8432         SrcI->getOpcode() == Instruction::Xor &&
8433         Op1 == ConstantInt::getTrue(*Context) &&
8434         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8435       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8436       return BinaryOperator::CreateXor(New,
8437                                       ConstantInt::get(CI.getType(), 1));
8438     }
8439     break;
8440
8441   case Instruction::Shl: {
8442     // Canonicalize trunc inside shl, if we can.
8443     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8444     if (CI && DestBitSize < SrcBitSize &&
8445         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8446       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8447       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8448       return BinaryOperator::CreateShl(Op0c, Op1c);
8449     }
8450     break;
8451   }
8452   }
8453   return 0;
8454 }
8455
8456 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8457   if (Instruction *Result = commonIntCastTransforms(CI))
8458     return Result;
8459   
8460   Value *Src = CI.getOperand(0);
8461   const Type *Ty = CI.getType();
8462   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8463   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8464
8465   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8466   if (DestBitWidth == 1) {
8467     Constant *One = ConstantInt::get(Src->getType(), 1);
8468     Src = Builder->CreateAnd(Src, One, "tmp");
8469     Value *Zero = Constant::getNullValue(Src->getType());
8470     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8471   }
8472
8473   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8474   ConstantInt *ShAmtV = 0;
8475   Value *ShiftOp = 0;
8476   if (Src->hasOneUse() &&
8477       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8478     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8479     
8480     // Get a mask for the bits shifting in.
8481     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8482     if (MaskedValueIsZero(ShiftOp, Mask)) {
8483       if (ShAmt >= DestBitWidth)        // All zeros.
8484         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8485       
8486       // Okay, we can shrink this.  Truncate the input, then return a new
8487       // shift.
8488       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8489       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8490       return BinaryOperator::CreateLShr(V1, V2);
8491     }
8492   }
8493  
8494   return 0;
8495 }
8496
8497 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8498 /// in order to eliminate the icmp.
8499 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8500                                              bool DoXform) {
8501   // If we are just checking for a icmp eq of a single bit and zext'ing it
8502   // to an integer, then shift the bit to the appropriate place and then
8503   // cast to integer to avoid the comparison.
8504   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8505     const APInt &Op1CV = Op1C->getValue();
8506       
8507     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8508     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8509     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8510         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8511       if (!DoXform) return ICI;
8512
8513       Value *In = ICI->getOperand(0);
8514       Value *Sh = ConstantInt::get(In->getType(),
8515                                    In->getType()->getScalarSizeInBits()-1);
8516       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8517       if (In->getType() != CI.getType())
8518         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8519
8520       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8521         Constant *One = ConstantInt::get(In->getType(), 1);
8522         In = Builder->CreateXor(In, One, In->getName()+".not");
8523       }
8524
8525       return ReplaceInstUsesWith(CI, In);
8526     }
8527       
8528       
8529       
8530     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8531     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8532     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8533     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8534     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8535     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8536     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8537     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8538     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8539         // This only works for EQ and NE
8540         ICI->isEquality()) {
8541       // If Op1C some other power of two, convert:
8542       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8543       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8544       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8545       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8546         
8547       APInt KnownZeroMask(~KnownZero);
8548       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8549         if (!DoXform) return ICI;
8550
8551         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8552         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8553           // (X&4) == 2 --> false
8554           // (X&4) != 2 --> true
8555           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8556           Res = ConstantExpr::getZExt(Res, CI.getType());
8557           return ReplaceInstUsesWith(CI, Res);
8558         }
8559           
8560         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8561         Value *In = ICI->getOperand(0);
8562         if (ShiftAmt) {
8563           // Perform a logical shr by shiftamt.
8564           // Insert the shift to put the result in the low bit.
8565           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8566                                    In->getName()+".lobit");
8567         }
8568           
8569         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8570           Constant *One = ConstantInt::get(In->getType(), 1);
8571           In = Builder->CreateXor(In, One, "tmp");
8572         }
8573           
8574         if (CI.getType() == In->getType())
8575           return ReplaceInstUsesWith(CI, In);
8576         else
8577           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8578       }
8579     }
8580   }
8581
8582   // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
8583   // It is also profitable to transform icmp eq into not(xor(A, B)) because that
8584   // may lead to additional simplifications.
8585   if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
8586     if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
8587       uint32_t BitWidth = ITy->getBitWidth();
8588       if (BitWidth > 1) {
8589         Value *LHS = ICI->getOperand(0);
8590         Value *RHS = ICI->getOperand(1);
8591
8592         APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
8593         APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
8594         APInt TypeMask(APInt::getHighBitsSet(BitWidth, BitWidth-1));
8595         ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
8596         ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
8597
8598         if (KnownZeroLHS.countLeadingOnes() == BitWidth-1 &&
8599             KnownZeroRHS.countLeadingOnes() == BitWidth-1) {
8600           if (!DoXform) return ICI;
8601
8602           Value *Xor = Builder->CreateXor(LHS, RHS);
8603           if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8604             Xor = Builder->CreateXor(Xor, ConstantInt::get(ITy, 1));
8605           Xor->takeName(ICI);
8606           return ReplaceInstUsesWith(CI, Xor);
8607         }
8608       }
8609     }
8610   }
8611
8612   return 0;
8613 }
8614
8615 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8616   // If one of the common conversion will work ..
8617   if (Instruction *Result = commonIntCastTransforms(CI))
8618     return Result;
8619
8620   Value *Src = CI.getOperand(0);
8621
8622   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8623   // types and if the sizes are just right we can convert this into a logical
8624   // 'and' which will be much cheaper than the pair of casts.
8625   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8626     // Get the sizes of the types involved.  We know that the intermediate type
8627     // will be smaller than A or C, but don't know the relation between A and C.
8628     Value *A = CSrc->getOperand(0);
8629     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8630     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8631     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8632     // If we're actually extending zero bits, then if
8633     // SrcSize <  DstSize: zext(a & mask)
8634     // SrcSize == DstSize: a & mask
8635     // SrcSize  > DstSize: trunc(a) & mask
8636     if (SrcSize < DstSize) {
8637       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8638       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8639       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8640       return new ZExtInst(And, CI.getType());
8641     }
8642     
8643     if (SrcSize == DstSize) {
8644       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8645       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8646                                                            AndValue));
8647     }
8648     if (SrcSize > DstSize) {
8649       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8650       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8651       return BinaryOperator::CreateAnd(Trunc, 
8652                                        ConstantInt::get(Trunc->getType(),
8653                                                                AndValue));
8654     }
8655   }
8656
8657   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8658     return transformZExtICmp(ICI, CI);
8659
8660   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8661   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8662     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8663     // of the (zext icmp) will be transformed.
8664     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8665     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8666     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8667         (transformZExtICmp(LHS, CI, false) ||
8668          transformZExtICmp(RHS, CI, false))) {
8669       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8670       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8671       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8672     }
8673   }
8674
8675   // zext(trunc(t) & C) -> (t & zext(C)).
8676   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8677     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8678       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8679         Value *TI0 = TI->getOperand(0);
8680         if (TI0->getType() == CI.getType())
8681           return
8682             BinaryOperator::CreateAnd(TI0,
8683                                 ConstantExpr::getZExt(C, CI.getType()));
8684       }
8685
8686   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8687   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8688     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8689       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8690         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8691             And->getOperand(1) == C)
8692           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8693             Value *TI0 = TI->getOperand(0);
8694             if (TI0->getType() == CI.getType()) {
8695               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8696               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8697               return BinaryOperator::CreateXor(NewAnd, ZC);
8698             }
8699           }
8700
8701   return 0;
8702 }
8703
8704 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8705   if (Instruction *I = commonIntCastTransforms(CI))
8706     return I;
8707   
8708   Value *Src = CI.getOperand(0);
8709   
8710   // Canonicalize sign-extend from i1 to a select.
8711   if (Src->getType() == Type::getInt1Ty(*Context))
8712     return SelectInst::Create(Src,
8713                               Constant::getAllOnesValue(CI.getType()),
8714                               Constant::getNullValue(CI.getType()));
8715
8716   // See if the value being truncated is already sign extended.  If so, just
8717   // eliminate the trunc/sext pair.
8718   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8719     Value *Op = cast<User>(Src)->getOperand(0);
8720     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8721     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8722     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8723     unsigned NumSignBits = ComputeNumSignBits(Op);
8724
8725     if (OpBits == DestBits) {
8726       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8727       // bits, it is already ready.
8728       if (NumSignBits > DestBits-MidBits)
8729         return ReplaceInstUsesWith(CI, Op);
8730     } else if (OpBits < DestBits) {
8731       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8732       // bits, just sext from i32.
8733       if (NumSignBits > OpBits-MidBits)
8734         return new SExtInst(Op, CI.getType(), "tmp");
8735     } else {
8736       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8737       // bits, just truncate to i32.
8738       if (NumSignBits > OpBits-MidBits)
8739         return new TruncInst(Op, CI.getType(), "tmp");
8740     }
8741   }
8742
8743   // If the input is a shl/ashr pair of a same constant, then this is a sign
8744   // extension from a smaller value.  If we could trust arbitrary bitwidth
8745   // integers, we could turn this into a truncate to the smaller bit and then
8746   // use a sext for the whole extension.  Since we don't, look deeper and check
8747   // for a truncate.  If the source and dest are the same type, eliminate the
8748   // trunc and extend and just do shifts.  For example, turn:
8749   //   %a = trunc i32 %i to i8
8750   //   %b = shl i8 %a, 6
8751   //   %c = ashr i8 %b, 6
8752   //   %d = sext i8 %c to i32
8753   // into:
8754   //   %a = shl i32 %i, 30
8755   //   %d = ashr i32 %a, 30
8756   Value *A = 0;
8757   ConstantInt *BA = 0, *CA = 0;
8758   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8759                         m_ConstantInt(CA))) &&
8760       BA == CA && isa<TruncInst>(A)) {
8761     Value *I = cast<TruncInst>(A)->getOperand(0);
8762     if (I->getType() == CI.getType()) {
8763       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8764       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8765       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8766       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8767       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8768       return BinaryOperator::CreateAShr(I, ShAmtV);
8769     }
8770   }
8771   
8772   return 0;
8773 }
8774
8775 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8776 /// in the specified FP type without changing its value.
8777 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8778                               LLVMContext *Context) {
8779   bool losesInfo;
8780   APFloat F = CFP->getValueAPF();
8781   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8782   if (!losesInfo)
8783     return ConstantFP::get(*Context, F);
8784   return 0;
8785 }
8786
8787 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8788 /// through it until we get the source value.
8789 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8790   if (Instruction *I = dyn_cast<Instruction>(V))
8791     if (I->getOpcode() == Instruction::FPExt)
8792       return LookThroughFPExtensions(I->getOperand(0), Context);
8793   
8794   // If this value is a constant, return the constant in the smallest FP type
8795   // that can accurately represent it.  This allows us to turn
8796   // (float)((double)X+2.0) into x+2.0f.
8797   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8798     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8799       return V;  // No constant folding of this.
8800     // See if the value can be truncated to float and then reextended.
8801     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8802       return V;
8803     if (CFP->getType() == Type::getDoubleTy(*Context))
8804       return V;  // Won't shrink.
8805     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8806       return V;
8807     // Don't try to shrink to various long double types.
8808   }
8809   
8810   return V;
8811 }
8812
8813 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8814   if (Instruction *I = commonCastTransforms(CI))
8815     return I;
8816   
8817   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8818   // smaller than the destination type, we can eliminate the truncate by doing
8819   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8820   // many builtins (sqrt, etc).
8821   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8822   if (OpI && OpI->hasOneUse()) {
8823     switch (OpI->getOpcode()) {
8824     default: break;
8825     case Instruction::FAdd:
8826     case Instruction::FSub:
8827     case Instruction::FMul:
8828     case Instruction::FDiv:
8829     case Instruction::FRem:
8830       const Type *SrcTy = OpI->getType();
8831       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8832       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8833       if (LHSTrunc->getType() != SrcTy && 
8834           RHSTrunc->getType() != SrcTy) {
8835         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8836         // If the source types were both smaller than the destination type of
8837         // the cast, do this xform.
8838         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8839             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8840           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8841           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8842           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8843         }
8844       }
8845       break;  
8846     }
8847   }
8848   return 0;
8849 }
8850
8851 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8852   return commonCastTransforms(CI);
8853 }
8854
8855 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8856   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8857   if (OpI == 0)
8858     return commonCastTransforms(FI);
8859
8860   // fptoui(uitofp(X)) --> X
8861   // fptoui(sitofp(X)) --> X
8862   // This is safe if the intermediate type has enough bits in its mantissa to
8863   // accurately represent all values of X.  For example, do not do this with
8864   // i64->float->i64.  This is also safe for sitofp case, because any negative
8865   // 'X' value would cause an undefined result for the fptoui. 
8866   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8867       OpI->getOperand(0)->getType() == FI.getType() &&
8868       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8869                     OpI->getType()->getFPMantissaWidth())
8870     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8871
8872   return commonCastTransforms(FI);
8873 }
8874
8875 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8876   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8877   if (OpI == 0)
8878     return commonCastTransforms(FI);
8879   
8880   // fptosi(sitofp(X)) --> X
8881   // fptosi(uitofp(X)) --> X
8882   // This is safe if the intermediate type has enough bits in its mantissa to
8883   // accurately represent all values of X.  For example, do not do this with
8884   // i64->float->i64.  This is also safe for sitofp case, because any negative
8885   // 'X' value would cause an undefined result for the fptoui. 
8886   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8887       OpI->getOperand(0)->getType() == FI.getType() &&
8888       (int)FI.getType()->getScalarSizeInBits() <=
8889                     OpI->getType()->getFPMantissaWidth())
8890     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8891   
8892   return commonCastTransforms(FI);
8893 }
8894
8895 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8896   return commonCastTransforms(CI);
8897 }
8898
8899 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8900   return commonCastTransforms(CI);
8901 }
8902
8903 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8904   // If the destination integer type is smaller than the intptr_t type for
8905   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8906   // trunc to be exposed to other transforms.  Don't do this for extending
8907   // ptrtoint's, because we don't know if the target sign or zero extends its
8908   // pointers.
8909   if (TD &&
8910       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8911     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8912                                        TD->getIntPtrType(CI.getContext()),
8913                                        "tmp");
8914     return new TruncInst(P, CI.getType());
8915   }
8916   
8917   return commonPointerCastTransforms(CI);
8918 }
8919
8920 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8921   // If the source integer type is larger than the intptr_t type for
8922   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8923   // allows the trunc to be exposed to other transforms.  Don't do this for
8924   // extending inttoptr's, because we don't know if the target sign or zero
8925   // extends to pointers.
8926   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8927       TD->getPointerSizeInBits()) {
8928     Value *P = Builder->CreateTrunc(CI.getOperand(0),
8929                                     TD->getIntPtrType(CI.getContext()), "tmp");
8930     return new IntToPtrInst(P, CI.getType());
8931   }
8932   
8933   if (Instruction *I = commonCastTransforms(CI))
8934     return I;
8935
8936   return 0;
8937 }
8938
8939 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8940   // If the operands are integer typed then apply the integer transforms,
8941   // otherwise just apply the common ones.
8942   Value *Src = CI.getOperand(0);
8943   const Type *SrcTy = Src->getType();
8944   const Type *DestTy = CI.getType();
8945
8946   if (isa<PointerType>(SrcTy)) {
8947     if (Instruction *I = commonPointerCastTransforms(CI))
8948       return I;
8949   } else {
8950     if (Instruction *Result = commonCastTransforms(CI))
8951       return Result;
8952   }
8953
8954
8955   // Get rid of casts from one type to the same type. These are useless and can
8956   // be replaced by the operand.
8957   if (DestTy == Src->getType())
8958     return ReplaceInstUsesWith(CI, Src);
8959
8960   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8961     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8962     const Type *DstElTy = DstPTy->getElementType();
8963     const Type *SrcElTy = SrcPTy->getElementType();
8964     
8965     // If the address spaces don't match, don't eliminate the bitcast, which is
8966     // required for changing types.
8967     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8968       return 0;
8969     
8970     // If we are casting a alloca to a pointer to a type of the same
8971     // size, rewrite the allocation instruction to allocate the "right" type.
8972     // There is no need to modify malloc calls because it is their bitcast that
8973     // needs to be cleaned up.
8974     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
8975       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8976         return V;
8977     
8978     // If the source and destination are pointers, and this cast is equivalent
8979     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8980     // This can enhance SROA and other transforms that want type-safe pointers.
8981     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8982     unsigned NumZeros = 0;
8983     while (SrcElTy != DstElTy && 
8984            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8985            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8986       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8987       ++NumZeros;
8988     }
8989
8990     // If we found a path from the src to dest, create the getelementptr now.
8991     if (SrcElTy == DstElTy) {
8992       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8993       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8994                                                ((Instruction*) NULL));
8995     }
8996   }
8997
8998   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8999     if (DestVTy->getNumElements() == 1) {
9000       if (!isa<VectorType>(SrcTy)) {
9001         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
9002         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
9003                             Constant::getNullValue(Type::getInt32Ty(*Context)));
9004       }
9005       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9006     }
9007   }
9008
9009   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9010     if (SrcVTy->getNumElements() == 1) {
9011       if (!isa<VectorType>(DestTy)) {
9012         Value *Elem = 
9013           Builder->CreateExtractElement(Src,
9014                             Constant::getNullValue(Type::getInt32Ty(*Context)));
9015         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9016       }
9017     }
9018   }
9019
9020   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9021     if (SVI->hasOneUse()) {
9022       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9023       // a bitconvert to a vector with the same # elts.
9024       if (isa<VectorType>(DestTy) && 
9025           cast<VectorType>(DestTy)->getNumElements() ==
9026                 SVI->getType()->getNumElements() &&
9027           SVI->getType()->getNumElements() ==
9028             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9029         CastInst *Tmp;
9030         // If either of the operands is a cast from CI.getType(), then
9031         // evaluating the shuffle in the casted destination's type will allow
9032         // us to eliminate at least one cast.
9033         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9034              Tmp->getOperand(0)->getType() == DestTy) ||
9035             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9036              Tmp->getOperand(0)->getType() == DestTy)) {
9037           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9038           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
9039           // Return a new shuffle vector.  Use the same element ID's, as we
9040           // know the vector types match #elts.
9041           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9042         }
9043       }
9044     }
9045   }
9046   return 0;
9047 }
9048
9049 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9050 ///   %C = or %A, %B
9051 ///   %D = select %cond, %C, %A
9052 /// into:
9053 ///   %C = select %cond, %B, 0
9054 ///   %D = or %A, %C
9055 ///
9056 /// Assuming that the specified instruction is an operand to the select, return
9057 /// a bitmask indicating which operands of this instruction are foldable if they
9058 /// equal the other incoming value of the select.
9059 ///
9060 static unsigned GetSelectFoldableOperands(Instruction *I) {
9061   switch (I->getOpcode()) {
9062   case Instruction::Add:
9063   case Instruction::Mul:
9064   case Instruction::And:
9065   case Instruction::Or:
9066   case Instruction::Xor:
9067     return 3;              // Can fold through either operand.
9068   case Instruction::Sub:   // Can only fold on the amount subtracted.
9069   case Instruction::Shl:   // Can only fold on the shift amount.
9070   case Instruction::LShr:
9071   case Instruction::AShr:
9072     return 1;
9073   default:
9074     return 0;              // Cannot fold
9075   }
9076 }
9077
9078 /// GetSelectFoldableConstant - For the same transformation as the previous
9079 /// function, return the identity constant that goes into the select.
9080 static Constant *GetSelectFoldableConstant(Instruction *I,
9081                                            LLVMContext *Context) {
9082   switch (I->getOpcode()) {
9083   default: llvm_unreachable("This cannot happen!");
9084   case Instruction::Add:
9085   case Instruction::Sub:
9086   case Instruction::Or:
9087   case Instruction::Xor:
9088   case Instruction::Shl:
9089   case Instruction::LShr:
9090   case Instruction::AShr:
9091     return Constant::getNullValue(I->getType());
9092   case Instruction::And:
9093     return Constant::getAllOnesValue(I->getType());
9094   case Instruction::Mul:
9095     return ConstantInt::get(I->getType(), 1);
9096   }
9097 }
9098
9099 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9100 /// have the same opcode and only one use each.  Try to simplify this.
9101 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9102                                           Instruction *FI) {
9103   if (TI->getNumOperands() == 1) {
9104     // If this is a non-volatile load or a cast from the same type,
9105     // merge.
9106     if (TI->isCast()) {
9107       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9108         return 0;
9109     } else {
9110       return 0;  // unknown unary op.
9111     }
9112
9113     // Fold this by inserting a select from the input values.
9114     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9115                                           FI->getOperand(0), SI.getName()+".v");
9116     InsertNewInstBefore(NewSI, SI);
9117     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9118                             TI->getType());
9119   }
9120
9121   // Only handle binary operators here.
9122   if (!isa<BinaryOperator>(TI))
9123     return 0;
9124
9125   // Figure out if the operations have any operands in common.
9126   Value *MatchOp, *OtherOpT, *OtherOpF;
9127   bool MatchIsOpZero;
9128   if (TI->getOperand(0) == FI->getOperand(0)) {
9129     MatchOp  = TI->getOperand(0);
9130     OtherOpT = TI->getOperand(1);
9131     OtherOpF = FI->getOperand(1);
9132     MatchIsOpZero = true;
9133   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9134     MatchOp  = TI->getOperand(1);
9135     OtherOpT = TI->getOperand(0);
9136     OtherOpF = FI->getOperand(0);
9137     MatchIsOpZero = false;
9138   } else if (!TI->isCommutative()) {
9139     return 0;
9140   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9141     MatchOp  = TI->getOperand(0);
9142     OtherOpT = TI->getOperand(1);
9143     OtherOpF = FI->getOperand(0);
9144     MatchIsOpZero = true;
9145   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9146     MatchOp  = TI->getOperand(1);
9147     OtherOpT = TI->getOperand(0);
9148     OtherOpF = FI->getOperand(1);
9149     MatchIsOpZero = true;
9150   } else {
9151     return 0;
9152   }
9153
9154   // If we reach here, they do have operations in common.
9155   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9156                                          OtherOpF, SI.getName()+".v");
9157   InsertNewInstBefore(NewSI, SI);
9158
9159   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9160     if (MatchIsOpZero)
9161       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9162     else
9163       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9164   }
9165   llvm_unreachable("Shouldn't get here");
9166   return 0;
9167 }
9168
9169 static bool isSelect01(Constant *C1, Constant *C2) {
9170   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9171   if (!C1I)
9172     return false;
9173   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9174   if (!C2I)
9175     return false;
9176   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9177 }
9178
9179 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9180 /// facilitate further optimization.
9181 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9182                                             Value *FalseVal) {
9183   // See the comment above GetSelectFoldableOperands for a description of the
9184   // transformation we are doing here.
9185   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9186     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9187         !isa<Constant>(FalseVal)) {
9188       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9189         unsigned OpToFold = 0;
9190         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9191           OpToFold = 1;
9192         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9193           OpToFold = 2;
9194         }
9195
9196         if (OpToFold) {
9197           Constant *C = GetSelectFoldableConstant(TVI, Context);
9198           Value *OOp = TVI->getOperand(2-OpToFold);
9199           // Avoid creating select between 2 constants unless it's selecting
9200           // between 0 and 1.
9201           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9202             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9203             InsertNewInstBefore(NewSel, SI);
9204             NewSel->takeName(TVI);
9205             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9206               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9207             llvm_unreachable("Unknown instruction!!");
9208           }
9209         }
9210       }
9211     }
9212   }
9213
9214   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9215     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9216         !isa<Constant>(TrueVal)) {
9217       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9218         unsigned OpToFold = 0;
9219         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9220           OpToFold = 1;
9221         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9222           OpToFold = 2;
9223         }
9224
9225         if (OpToFold) {
9226           Constant *C = GetSelectFoldableConstant(FVI, Context);
9227           Value *OOp = FVI->getOperand(2-OpToFold);
9228           // Avoid creating select between 2 constants unless it's selecting
9229           // between 0 and 1.
9230           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9231             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9232             InsertNewInstBefore(NewSel, SI);
9233             NewSel->takeName(FVI);
9234             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9235               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9236             llvm_unreachable("Unknown instruction!!");
9237           }
9238         }
9239       }
9240     }
9241   }
9242
9243   return 0;
9244 }
9245
9246 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9247 /// ICmpInst as its first operand.
9248 ///
9249 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9250                                                    ICmpInst *ICI) {
9251   bool Changed = false;
9252   ICmpInst::Predicate Pred = ICI->getPredicate();
9253   Value *CmpLHS = ICI->getOperand(0);
9254   Value *CmpRHS = ICI->getOperand(1);
9255   Value *TrueVal = SI.getTrueValue();
9256   Value *FalseVal = SI.getFalseValue();
9257
9258   // Check cases where the comparison is with a constant that
9259   // can be adjusted to fit the min/max idiom. We may edit ICI in
9260   // place here, so make sure the select is the only user.
9261   if (ICI->hasOneUse())
9262     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9263       switch (Pred) {
9264       default: break;
9265       case ICmpInst::ICMP_ULT:
9266       case ICmpInst::ICMP_SLT: {
9267         // X < MIN ? T : F  -->  F
9268         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9269           return ReplaceInstUsesWith(SI, FalseVal);
9270         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9271         Constant *AdjustedRHS = SubOne(CI);
9272         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9273             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9274           Pred = ICmpInst::getSwappedPredicate(Pred);
9275           CmpRHS = AdjustedRHS;
9276           std::swap(FalseVal, TrueVal);
9277           ICI->setPredicate(Pred);
9278           ICI->setOperand(1, CmpRHS);
9279           SI.setOperand(1, TrueVal);
9280           SI.setOperand(2, FalseVal);
9281           Changed = true;
9282         }
9283         break;
9284       }
9285       case ICmpInst::ICMP_UGT:
9286       case ICmpInst::ICMP_SGT: {
9287         // X > MAX ? T : F  -->  F
9288         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9289           return ReplaceInstUsesWith(SI, FalseVal);
9290         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9291         Constant *AdjustedRHS = AddOne(CI);
9292         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9293             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9294           Pred = ICmpInst::getSwappedPredicate(Pred);
9295           CmpRHS = AdjustedRHS;
9296           std::swap(FalseVal, TrueVal);
9297           ICI->setPredicate(Pred);
9298           ICI->setOperand(1, CmpRHS);
9299           SI.setOperand(1, TrueVal);
9300           SI.setOperand(2, FalseVal);
9301           Changed = true;
9302         }
9303         break;
9304       }
9305       }
9306
9307       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9308       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9309       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9310       if (match(TrueVal, m_ConstantInt<-1>()) &&
9311           match(FalseVal, m_ConstantInt<0>()))
9312         Pred = ICI->getPredicate();
9313       else if (match(TrueVal, m_ConstantInt<0>()) &&
9314                match(FalseVal, m_ConstantInt<-1>()))
9315         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9316       
9317       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9318         // If we are just checking for a icmp eq of a single bit and zext'ing it
9319         // to an integer, then shift the bit to the appropriate place and then
9320         // cast to integer to avoid the comparison.
9321         const APInt &Op1CV = CI->getValue();
9322     
9323         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9324         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9325         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9326             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9327           Value *In = ICI->getOperand(0);
9328           Value *Sh = ConstantInt::get(In->getType(),
9329                                        In->getType()->getScalarSizeInBits()-1);
9330           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9331                                                         In->getName()+".lobit"),
9332                                    *ICI);
9333           if (In->getType() != SI.getType())
9334             In = CastInst::CreateIntegerCast(In, SI.getType(),
9335                                              true/*SExt*/, "tmp", ICI);
9336     
9337           if (Pred == ICmpInst::ICMP_SGT)
9338             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9339                                        In->getName()+".not"), *ICI);
9340     
9341           return ReplaceInstUsesWith(SI, In);
9342         }
9343       }
9344     }
9345
9346   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9347     // Transform (X == Y) ? X : Y  -> Y
9348     if (Pred == ICmpInst::ICMP_EQ)
9349       return ReplaceInstUsesWith(SI, FalseVal);
9350     // Transform (X != Y) ? X : Y  -> X
9351     if (Pred == ICmpInst::ICMP_NE)
9352       return ReplaceInstUsesWith(SI, TrueVal);
9353     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9354
9355   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9356     // Transform (X == Y) ? Y : X  -> X
9357     if (Pred == ICmpInst::ICMP_EQ)
9358       return ReplaceInstUsesWith(SI, FalseVal);
9359     // Transform (X != Y) ? Y : X  -> Y
9360     if (Pred == ICmpInst::ICMP_NE)
9361       return ReplaceInstUsesWith(SI, TrueVal);
9362     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9363   }
9364
9365   /// NOTE: if we wanted to, this is where to detect integer ABS
9366
9367   return Changed ? &SI : 0;
9368 }
9369
9370
9371 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9372 /// PHI node (but the two may be in different blocks).  See if the true/false
9373 /// values (V) are live in all of the predecessor blocks of the PHI.  For
9374 /// example, cases like this cannot be mapped:
9375 ///
9376 ///   X = phi [ C1, BB1], [C2, BB2]
9377 ///   Y = add
9378 ///   Z = select X, Y, 0
9379 ///
9380 /// because Y is not live in BB1/BB2.
9381 ///
9382 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9383                                                    const SelectInst &SI) {
9384   // If the value is a non-instruction value like a constant or argument, it
9385   // can always be mapped.
9386   const Instruction *I = dyn_cast<Instruction>(V);
9387   if (I == 0) return true;
9388   
9389   // If V is a PHI node defined in the same block as the condition PHI, we can
9390   // map the arguments.
9391   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9392   
9393   if (const PHINode *VP = dyn_cast<PHINode>(I))
9394     if (VP->getParent() == CondPHI->getParent())
9395       return true;
9396   
9397   // Otherwise, if the PHI and select are defined in the same block and if V is
9398   // defined in a different block, then we can transform it.
9399   if (SI.getParent() == CondPHI->getParent() &&
9400       I->getParent() != CondPHI->getParent())
9401     return true;
9402   
9403   // Otherwise we have a 'hard' case and we can't tell without doing more
9404   // detailed dominator based analysis, punt.
9405   return false;
9406 }
9407
9408 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9409   Value *CondVal = SI.getCondition();
9410   Value *TrueVal = SI.getTrueValue();
9411   Value *FalseVal = SI.getFalseValue();
9412
9413   // select true, X, Y  -> X
9414   // select false, X, Y -> Y
9415   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9416     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9417
9418   // select C, X, X -> X
9419   if (TrueVal == FalseVal)
9420     return ReplaceInstUsesWith(SI, TrueVal);
9421
9422   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9423     return ReplaceInstUsesWith(SI, FalseVal);
9424   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9425     return ReplaceInstUsesWith(SI, TrueVal);
9426   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9427     if (isa<Constant>(TrueVal))
9428       return ReplaceInstUsesWith(SI, TrueVal);
9429     else
9430       return ReplaceInstUsesWith(SI, FalseVal);
9431   }
9432
9433   if (SI.getType() == Type::getInt1Ty(*Context)) {
9434     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9435       if (C->getZExtValue()) {
9436         // Change: A = select B, true, C --> A = or B, C
9437         return BinaryOperator::CreateOr(CondVal, FalseVal);
9438       } else {
9439         // Change: A = select B, false, C --> A = and !B, C
9440         Value *NotCond =
9441           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9442                                              "not."+CondVal->getName()), SI);
9443         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9444       }
9445     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9446       if (C->getZExtValue() == false) {
9447         // Change: A = select B, C, false --> A = and B, C
9448         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9449       } else {
9450         // Change: A = select B, C, true --> A = or !B, C
9451         Value *NotCond =
9452           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9453                                              "not."+CondVal->getName()), SI);
9454         return BinaryOperator::CreateOr(NotCond, TrueVal);
9455       }
9456     }
9457     
9458     // select a, b, a  -> a&b
9459     // select a, a, b  -> a|b
9460     if (CondVal == TrueVal)
9461       return BinaryOperator::CreateOr(CondVal, FalseVal);
9462     else if (CondVal == FalseVal)
9463       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9464   }
9465
9466   // Selecting between two integer constants?
9467   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9468     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9469       // select C, 1, 0 -> zext C to int
9470       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9471         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9472       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9473         // select C, 0, 1 -> zext !C to int
9474         Value *NotCond =
9475           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9476                                                "not."+CondVal->getName()), SI);
9477         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9478       }
9479
9480       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9481         // If one of the constants is zero (we know they can't both be) and we
9482         // have an icmp instruction with zero, and we have an 'and' with the
9483         // non-constant value, eliminate this whole mess.  This corresponds to
9484         // cases like this: ((X & 27) ? 27 : 0)
9485         if (TrueValC->isZero() || FalseValC->isZero())
9486           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9487               cast<Constant>(IC->getOperand(1))->isNullValue())
9488             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9489               if (ICA->getOpcode() == Instruction::And &&
9490                   isa<ConstantInt>(ICA->getOperand(1)) &&
9491                   (ICA->getOperand(1) == TrueValC ||
9492                    ICA->getOperand(1) == FalseValC) &&
9493                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9494                 // Okay, now we know that everything is set up, we just don't
9495                 // know whether we have a icmp_ne or icmp_eq and whether the 
9496                 // true or false val is the zero.
9497                 bool ShouldNotVal = !TrueValC->isZero();
9498                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9499                 Value *V = ICA;
9500                 if (ShouldNotVal)
9501                   V = InsertNewInstBefore(BinaryOperator::Create(
9502                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9503                 return ReplaceInstUsesWith(SI, V);
9504               }
9505       }
9506     }
9507
9508   // See if we are selecting two values based on a comparison of the two values.
9509   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9510     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9511       // Transform (X == Y) ? X : Y  -> Y
9512       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9513         // This is not safe in general for floating point:  
9514         // consider X== -0, Y== +0.
9515         // It becomes safe if either operand is a nonzero constant.
9516         ConstantFP *CFPt, *CFPf;
9517         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9518               !CFPt->getValueAPF().isZero()) ||
9519             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9520              !CFPf->getValueAPF().isZero()))
9521         return ReplaceInstUsesWith(SI, FalseVal);
9522       }
9523       // Transform (X != Y) ? X : Y  -> X
9524       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9525         return ReplaceInstUsesWith(SI, TrueVal);
9526       // NOTE: if we wanted to, this is where to detect MIN/MAX
9527
9528     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9529       // Transform (X == Y) ? Y : X  -> X
9530       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9531         // This is not safe in general for floating point:  
9532         // consider X== -0, Y== +0.
9533         // It becomes safe if either operand is a nonzero constant.
9534         ConstantFP *CFPt, *CFPf;
9535         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9536               !CFPt->getValueAPF().isZero()) ||
9537             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9538              !CFPf->getValueAPF().isZero()))
9539           return ReplaceInstUsesWith(SI, FalseVal);
9540       }
9541       // Transform (X != Y) ? Y : X  -> Y
9542       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9543         return ReplaceInstUsesWith(SI, TrueVal);
9544       // NOTE: if we wanted to, this is where to detect MIN/MAX
9545     }
9546     // NOTE: if we wanted to, this is where to detect ABS
9547   }
9548
9549   // See if we are selecting two values based on a comparison of the two values.
9550   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9551     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9552       return Result;
9553
9554   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9555     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9556       if (TI->hasOneUse() && FI->hasOneUse()) {
9557         Instruction *AddOp = 0, *SubOp = 0;
9558
9559         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9560         if (TI->getOpcode() == FI->getOpcode())
9561           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9562             return IV;
9563
9564         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9565         // even legal for FP.
9566         if ((TI->getOpcode() == Instruction::Sub &&
9567              FI->getOpcode() == Instruction::Add) ||
9568             (TI->getOpcode() == Instruction::FSub &&
9569              FI->getOpcode() == Instruction::FAdd)) {
9570           AddOp = FI; SubOp = TI;
9571         } else if ((FI->getOpcode() == Instruction::Sub &&
9572                     TI->getOpcode() == Instruction::Add) ||
9573                    (FI->getOpcode() == Instruction::FSub &&
9574                     TI->getOpcode() == Instruction::FAdd)) {
9575           AddOp = TI; SubOp = FI;
9576         }
9577
9578         if (AddOp) {
9579           Value *OtherAddOp = 0;
9580           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9581             OtherAddOp = AddOp->getOperand(1);
9582           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9583             OtherAddOp = AddOp->getOperand(0);
9584           }
9585
9586           if (OtherAddOp) {
9587             // So at this point we know we have (Y -> OtherAddOp):
9588             //        select C, (add X, Y), (sub X, Z)
9589             Value *NegVal;  // Compute -Z
9590             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9591               NegVal = ConstantExpr::getNeg(C);
9592             } else {
9593               NegVal = InsertNewInstBefore(
9594                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9595                                               "tmp"), SI);
9596             }
9597
9598             Value *NewTrueOp = OtherAddOp;
9599             Value *NewFalseOp = NegVal;
9600             if (AddOp != TI)
9601               std::swap(NewTrueOp, NewFalseOp);
9602             Instruction *NewSel =
9603               SelectInst::Create(CondVal, NewTrueOp,
9604                                  NewFalseOp, SI.getName() + ".p");
9605
9606             NewSel = InsertNewInstBefore(NewSel, SI);
9607             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9608           }
9609         }
9610       }
9611
9612   // See if we can fold the select into one of our operands.
9613   if (SI.getType()->isInteger()) {
9614     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9615     if (FoldI)
9616       return FoldI;
9617   }
9618
9619   // See if we can fold the select into a phi node if the condition is a select.
9620   if (isa<PHINode>(SI.getCondition())) 
9621     // The true/false values have to be live in the PHI predecessor's blocks.
9622     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9623         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9624       if (Instruction *NV = FoldOpIntoPhi(SI))
9625         return NV;
9626
9627   if (BinaryOperator::isNot(CondVal)) {
9628     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9629     SI.setOperand(1, FalseVal);
9630     SI.setOperand(2, TrueVal);
9631     return &SI;
9632   }
9633
9634   return 0;
9635 }
9636
9637 /// EnforceKnownAlignment - If the specified pointer points to an object that
9638 /// we control, modify the object's alignment to PrefAlign. This isn't
9639 /// often possible though. If alignment is important, a more reliable approach
9640 /// is to simply align all global variables and allocation instructions to
9641 /// their preferred alignment from the beginning.
9642 ///
9643 static unsigned EnforceKnownAlignment(Value *V,
9644                                       unsigned Align, unsigned PrefAlign) {
9645
9646   User *U = dyn_cast<User>(V);
9647   if (!U) return Align;
9648
9649   switch (Operator::getOpcode(U)) {
9650   default: break;
9651   case Instruction::BitCast:
9652     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9653   case Instruction::GetElementPtr: {
9654     // If all indexes are zero, it is just the alignment of the base pointer.
9655     bool AllZeroOperands = true;
9656     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9657       if (!isa<Constant>(*i) ||
9658           !cast<Constant>(*i)->isNullValue()) {
9659         AllZeroOperands = false;
9660         break;
9661       }
9662
9663     if (AllZeroOperands) {
9664       // Treat this like a bitcast.
9665       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9666     }
9667     break;
9668   }
9669   }
9670
9671   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9672     // If there is a large requested alignment and we can, bump up the alignment
9673     // of the global.
9674     if (!GV->isDeclaration()) {
9675       if (GV->getAlignment() >= PrefAlign)
9676         Align = GV->getAlignment();
9677       else {
9678         GV->setAlignment(PrefAlign);
9679         Align = PrefAlign;
9680       }
9681     }
9682   } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9683     // If there is a requested alignment and if this is an alloca, round up.
9684     if (AI->getAlignment() >= PrefAlign)
9685       Align = AI->getAlignment();
9686     else {
9687       AI->setAlignment(PrefAlign);
9688       Align = PrefAlign;
9689     }
9690   }
9691
9692   return Align;
9693 }
9694
9695 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9696 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9697 /// and it is more than the alignment of the ultimate object, see if we can
9698 /// increase the alignment of the ultimate object, making this check succeed.
9699 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9700                                                   unsigned PrefAlign) {
9701   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9702                       sizeof(PrefAlign) * CHAR_BIT;
9703   APInt Mask = APInt::getAllOnesValue(BitWidth);
9704   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9705   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9706   unsigned TrailZ = KnownZero.countTrailingOnes();
9707   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9708
9709   if (PrefAlign > Align)
9710     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9711   
9712     // We don't need to make any adjustment.
9713   return Align;
9714 }
9715
9716 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9717   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9718   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9719   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9720   unsigned CopyAlign = MI->getAlignment();
9721
9722   if (CopyAlign < MinAlign) {
9723     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9724                                              MinAlign, false));
9725     return MI;
9726   }
9727   
9728   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9729   // load/store.
9730   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9731   if (MemOpLength == 0) return 0;
9732   
9733   // Source and destination pointer types are always "i8*" for intrinsic.  See
9734   // if the size is something we can handle with a single primitive load/store.
9735   // A single load+store correctly handles overlapping memory in the memmove
9736   // case.
9737   unsigned Size = MemOpLength->getZExtValue();
9738   if (Size == 0) return MI;  // Delete this mem transfer.
9739   
9740   if (Size > 8 || (Size&(Size-1)))
9741     return 0;  // If not 1/2/4/8 bytes, exit.
9742   
9743   // Use an integer load+store unless we can find something better.
9744   Type *NewPtrTy =
9745                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9746   
9747   // Memcpy forces the use of i8* for the source and destination.  That means
9748   // that if you're using memcpy to move one double around, you'll get a cast
9749   // from double* to i8*.  We'd much rather use a double load+store rather than
9750   // an i64 load+store, here because this improves the odds that the source or
9751   // dest address will be promotable.  See if we can find a better type than the
9752   // integer datatype.
9753   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9754     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9755     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9756       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9757       // down through these levels if so.
9758       while (!SrcETy->isSingleValueType()) {
9759         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9760           if (STy->getNumElements() == 1)
9761             SrcETy = STy->getElementType(0);
9762           else
9763             break;
9764         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9765           if (ATy->getNumElements() == 1)
9766             SrcETy = ATy->getElementType();
9767           else
9768             break;
9769         } else
9770           break;
9771       }
9772       
9773       if (SrcETy->isSingleValueType())
9774         NewPtrTy = PointerType::getUnqual(SrcETy);
9775     }
9776   }
9777   
9778   
9779   // If the memcpy/memmove provides better alignment info than we can
9780   // infer, use it.
9781   SrcAlign = std::max(SrcAlign, CopyAlign);
9782   DstAlign = std::max(DstAlign, CopyAlign);
9783   
9784   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9785   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9786   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9787   InsertNewInstBefore(L, *MI);
9788   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9789
9790   // Set the size of the copy to 0, it will be deleted on the next iteration.
9791   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9792   return MI;
9793 }
9794
9795 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9796   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9797   if (MI->getAlignment() < Alignment) {
9798     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9799                                              Alignment, false));
9800     return MI;
9801   }
9802   
9803   // Extract the length and alignment and fill if they are constant.
9804   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9805   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9806   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9807     return 0;
9808   uint64_t Len = LenC->getZExtValue();
9809   Alignment = MI->getAlignment();
9810   
9811   // If the length is zero, this is a no-op
9812   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9813   
9814   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9815   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9816     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9817     
9818     Value *Dest = MI->getDest();
9819     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9820
9821     // Alignment 0 is identity for alignment 1 for memset, but not store.
9822     if (Alignment == 0) Alignment = 1;
9823     
9824     // Extract the fill value and store.
9825     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9826     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9827                                       Dest, false, Alignment), *MI);
9828     
9829     // Set the size of the copy to 0, it will be deleted on the next iteration.
9830     MI->setLength(Constant::getNullValue(LenC->getType()));
9831     return MI;
9832   }
9833
9834   return 0;
9835 }
9836
9837
9838 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9839 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9840 /// the heavy lifting.
9841 ///
9842 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9843   if (isFreeCall(&CI))
9844     return visitFree(CI);
9845
9846   // If the caller function is nounwind, mark the call as nounwind, even if the
9847   // callee isn't.
9848   if (CI.getParent()->getParent()->doesNotThrow() &&
9849       !CI.doesNotThrow()) {
9850     CI.setDoesNotThrow();
9851     return &CI;
9852   }
9853   
9854   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9855   if (!II) return visitCallSite(&CI);
9856   
9857   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9858   // visitCallSite.
9859   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9860     bool Changed = false;
9861
9862     // memmove/cpy/set of zero bytes is a noop.
9863     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9864       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9865
9866       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9867         if (CI->getZExtValue() == 1) {
9868           // Replace the instruction with just byte operations.  We would
9869           // transform other cases to loads/stores, but we don't know if
9870           // alignment is sufficient.
9871         }
9872     }
9873
9874     // If we have a memmove and the source operation is a constant global,
9875     // then the source and dest pointers can't alias, so we can change this
9876     // into a call to memcpy.
9877     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9878       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9879         if (GVSrc->isConstant()) {
9880           Module *M = CI.getParent()->getParent()->getParent();
9881           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9882           const Type *Tys[1];
9883           Tys[0] = CI.getOperand(3)->getType();
9884           CI.setOperand(0, 
9885                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9886           Changed = true;
9887         }
9888
9889       // memmove(x,x,size) -> noop.
9890       if (MMI->getSource() == MMI->getDest())
9891         return EraseInstFromFunction(CI);
9892     }
9893
9894     // If we can determine a pointer alignment that is bigger than currently
9895     // set, update the alignment.
9896     if (isa<MemTransferInst>(MI)) {
9897       if (Instruction *I = SimplifyMemTransfer(MI))
9898         return I;
9899     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9900       if (Instruction *I = SimplifyMemSet(MSI))
9901         return I;
9902     }
9903           
9904     if (Changed) return II;
9905   }
9906   
9907   switch (II->getIntrinsicID()) {
9908   default: break;
9909   case Intrinsic::bswap:
9910     // bswap(bswap(x)) -> x
9911     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9912       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9913         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9914     break;
9915   case Intrinsic::uadd_with_overflow: {
9916     Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
9917     const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
9918     uint32_t BitWidth = IT->getBitWidth();
9919     APInt Mask = APInt::getSignBit(BitWidth);
9920     APInt LHSKnownZero(BitWidth, 0);
9921     APInt LHSKnownOne(BitWidth, 0);
9922     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
9923     bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
9924     bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
9925
9926     if (LHSKnownNegative || LHSKnownPositive) {
9927       APInt RHSKnownZero(BitWidth, 0);
9928       APInt RHSKnownOne(BitWidth, 0);
9929       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
9930       bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
9931       bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
9932       if (LHSKnownNegative && RHSKnownNegative) {
9933         // The sign bit is set in both cases: this MUST overflow.
9934         // Create a simple add instruction, and insert it into the struct.
9935         Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
9936         Worklist.Add(Add);
9937         Constant *V[] = {
9938           UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
9939         };
9940         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
9941         return InsertValueInst::Create(Struct, Add, 0);
9942       }
9943       
9944       if (LHSKnownPositive && RHSKnownPositive) {
9945         // The sign bit is clear in both cases: this CANNOT overflow.
9946         // Create a simple add instruction, and insert it into the struct.
9947         Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
9948         Worklist.Add(Add);
9949         Constant *V[] = {
9950           UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
9951         };
9952         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
9953         return InsertValueInst::Create(Struct, Add, 0);
9954       }
9955     }
9956   }
9957   // FALL THROUGH uadd into sadd
9958   case Intrinsic::sadd_with_overflow:
9959     // Canonicalize constants into the RHS.
9960     if (isa<Constant>(II->getOperand(1)) &&
9961         !isa<Constant>(II->getOperand(2))) {
9962       Value *LHS = II->getOperand(1);
9963       II->setOperand(1, II->getOperand(2));
9964       II->setOperand(2, LHS);
9965       return II;
9966     }
9967
9968     // X + undef -> undef
9969     if (isa<UndefValue>(II->getOperand(2)))
9970       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
9971       
9972     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
9973       // X + 0 -> {X, false}
9974       if (RHS->isZero()) {
9975         Constant *V[] = {
9976           UndefValue::get(II->getOperand(0)->getType()),
9977           ConstantInt::getFalse(*Context)
9978         };
9979         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
9980         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
9981       }
9982     }
9983     break;
9984   case Intrinsic::usub_with_overflow:
9985   case Intrinsic::ssub_with_overflow:
9986     // undef - X -> undef
9987     // X - undef -> undef
9988     if (isa<UndefValue>(II->getOperand(1)) ||
9989         isa<UndefValue>(II->getOperand(2)))
9990       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
9991       
9992     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
9993       // X - 0 -> {X, false}
9994       if (RHS->isZero()) {
9995         Constant *V[] = {
9996           UndefValue::get(II->getOperand(1)->getType()),
9997           ConstantInt::getFalse(*Context)
9998         };
9999         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10000         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10001       }
10002     }
10003     break;
10004   case Intrinsic::umul_with_overflow:
10005   case Intrinsic::smul_with_overflow:
10006     // Canonicalize constants into the RHS.
10007     if (isa<Constant>(II->getOperand(1)) &&
10008         !isa<Constant>(II->getOperand(2))) {
10009       Value *LHS = II->getOperand(1);
10010       II->setOperand(1, II->getOperand(2));
10011       II->setOperand(2, LHS);
10012       return II;
10013     }
10014
10015     // X * undef -> undef
10016     if (isa<UndefValue>(II->getOperand(2)))
10017       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10018       
10019     if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10020       // X*0 -> {0, false}
10021       if (RHSI->isZero())
10022         return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10023       
10024       // X * 1 -> {X, false}
10025       if (RHSI->equalsInt(1)) {
10026         Constant *V[] = {
10027           UndefValue::get(II->getOperand(1)->getType()),
10028           ConstantInt::getFalse(*Context)
10029         };
10030         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10031         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10032       }
10033     }
10034     break;
10035   case Intrinsic::ppc_altivec_lvx:
10036   case Intrinsic::ppc_altivec_lvxl:
10037   case Intrinsic::x86_sse_loadu_ps:
10038   case Intrinsic::x86_sse2_loadu_pd:
10039   case Intrinsic::x86_sse2_loadu_dq:
10040     // Turn PPC lvx     -> load if the pointer is known aligned.
10041     // Turn X86 loadups -> load if the pointer is known aligned.
10042     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10043       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10044                                          PointerType::getUnqual(II->getType()));
10045       return new LoadInst(Ptr);
10046     }
10047     break;
10048   case Intrinsic::ppc_altivec_stvx:
10049   case Intrinsic::ppc_altivec_stvxl:
10050     // Turn stvx -> store if the pointer is known aligned.
10051     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10052       const Type *OpPtrTy = 
10053         PointerType::getUnqual(II->getOperand(1)->getType());
10054       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
10055       return new StoreInst(II->getOperand(1), Ptr);
10056     }
10057     break;
10058   case Intrinsic::x86_sse_storeu_ps:
10059   case Intrinsic::x86_sse2_storeu_pd:
10060   case Intrinsic::x86_sse2_storeu_dq:
10061     // Turn X86 storeu -> store if the pointer is known aligned.
10062     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10063       const Type *OpPtrTy = 
10064         PointerType::getUnqual(II->getOperand(2)->getType());
10065       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
10066       return new StoreInst(II->getOperand(2), Ptr);
10067     }
10068     break;
10069     
10070   case Intrinsic::x86_sse_cvttss2si: {
10071     // These intrinsics only demands the 0th element of its input vector.  If
10072     // we can simplify the input based on that, do so now.
10073     unsigned VWidth =
10074       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10075     APInt DemandedElts(VWidth, 1);
10076     APInt UndefElts(VWidth, 0);
10077     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
10078                                               UndefElts)) {
10079       II->setOperand(1, V);
10080       return II;
10081     }
10082     break;
10083   }
10084     
10085   case Intrinsic::ppc_altivec_vperm:
10086     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10087     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10088       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
10089       
10090       // Check that all of the elements are integer constants or undefs.
10091       bool AllEltsOk = true;
10092       for (unsigned i = 0; i != 16; ++i) {
10093         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
10094             !isa<UndefValue>(Mask->getOperand(i))) {
10095           AllEltsOk = false;
10096           break;
10097         }
10098       }
10099       
10100       if (AllEltsOk) {
10101         // Cast the input vectors to byte vectors.
10102         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10103         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
10104         Value *Result = UndefValue::get(Op0->getType());
10105         
10106         // Only extract each element once.
10107         Value *ExtractedElts[32];
10108         memset(ExtractedElts, 0, sizeof(ExtractedElts));
10109         
10110         for (unsigned i = 0; i != 16; ++i) {
10111           if (isa<UndefValue>(Mask->getOperand(i)))
10112             continue;
10113           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10114           Idx &= 31;  // Match the hardware behavior.
10115           
10116           if (ExtractedElts[Idx] == 0) {
10117             ExtractedElts[Idx] = 
10118               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
10119                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10120                                             "tmp");
10121           }
10122         
10123           // Insert this value into the result vector.
10124           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10125                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10126                                                 "tmp");
10127         }
10128         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
10129       }
10130     }
10131     break;
10132
10133   case Intrinsic::stackrestore: {
10134     // If the save is right next to the restore, remove the restore.  This can
10135     // happen when variable allocas are DCE'd.
10136     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10137       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10138         BasicBlock::iterator BI = SS;
10139         if (&*++BI == II)
10140           return EraseInstFromFunction(CI);
10141       }
10142     }
10143     
10144     // Scan down this block to see if there is another stack restore in the
10145     // same block without an intervening call/alloca.
10146     BasicBlock::iterator BI = II;
10147     TerminatorInst *TI = II->getParent()->getTerminator();
10148     bool CannotRemove = false;
10149     for (++BI; &*BI != TI; ++BI) {
10150       if (isa<AllocaInst>(BI) || isMalloc(BI)) {
10151         CannotRemove = true;
10152         break;
10153       }
10154       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10155         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10156           // If there is a stackrestore below this one, remove this one.
10157           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10158             return EraseInstFromFunction(CI);
10159           // Otherwise, ignore the intrinsic.
10160         } else {
10161           // If we found a non-intrinsic call, we can't remove the stack
10162           // restore.
10163           CannotRemove = true;
10164           break;
10165         }
10166       }
10167     }
10168     
10169     // If the stack restore is in a return/unwind block and if there are no
10170     // allocas or calls between the restore and the return, nuke the restore.
10171     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10172       return EraseInstFromFunction(CI);
10173     break;
10174   }
10175   }
10176
10177   return visitCallSite(II);
10178 }
10179
10180 // InvokeInst simplification
10181 //
10182 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10183   return visitCallSite(&II);
10184 }
10185
10186 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10187 /// passed through the varargs area, we can eliminate the use of the cast.
10188 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10189                                          const CastInst * const CI,
10190                                          const TargetData * const TD,
10191                                          const int ix) {
10192   if (!CI->isLosslessCast())
10193     return false;
10194
10195   // The size of ByVal arguments is derived from the type, so we
10196   // can't change to a type with a different size.  If the size were
10197   // passed explicitly we could avoid this check.
10198   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10199     return true;
10200
10201   const Type* SrcTy = 
10202             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10203   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10204   if (!SrcTy->isSized() || !DstTy->isSized())
10205     return false;
10206   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10207     return false;
10208   return true;
10209 }
10210
10211 // visitCallSite - Improvements for call and invoke instructions.
10212 //
10213 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10214   bool Changed = false;
10215
10216   // If the callee is a constexpr cast of a function, attempt to move the cast
10217   // to the arguments of the call/invoke.
10218   if (transformConstExprCastCall(CS)) return 0;
10219
10220   Value *Callee = CS.getCalledValue();
10221
10222   if (Function *CalleeF = dyn_cast<Function>(Callee))
10223     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10224       Instruction *OldCall = CS.getInstruction();
10225       // If the call and callee calling conventions don't match, this call must
10226       // be unreachable, as the call is undefined.
10227       new StoreInst(ConstantInt::getTrue(*Context),
10228                 UndefValue::get(Type::getInt1PtrTy(*Context)), 
10229                                   OldCall);
10230       // If OldCall dues not return void then replaceAllUsesWith undef.
10231       // This allows ValueHandlers and custom metadata to adjust itself.
10232       if (!OldCall->getType()->isVoidTy())
10233         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10234       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10235         return EraseInstFromFunction(*OldCall);
10236       return 0;
10237     }
10238
10239   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10240     // This instruction is not reachable, just remove it.  We insert a store to
10241     // undef so that we know that this code is not reachable, despite the fact
10242     // that we can't modify the CFG here.
10243     new StoreInst(ConstantInt::getTrue(*Context),
10244                UndefValue::get(Type::getInt1PtrTy(*Context)),
10245                   CS.getInstruction());
10246
10247     // If CS dues not return void then replaceAllUsesWith undef.
10248     // This allows ValueHandlers and custom metadata to adjust itself.
10249     if (!CS.getInstruction()->getType()->isVoidTy())
10250       CS.getInstruction()->
10251         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10252
10253     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10254       // Don't break the CFG, insert a dummy cond branch.
10255       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10256                          ConstantInt::getTrue(*Context), II);
10257     }
10258     return EraseInstFromFunction(*CS.getInstruction());
10259   }
10260
10261   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10262     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10263       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10264         return transformCallThroughTrampoline(CS);
10265
10266   const PointerType *PTy = cast<PointerType>(Callee->getType());
10267   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10268   if (FTy->isVarArg()) {
10269     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10270     // See if we can optimize any arguments passed through the varargs area of
10271     // the call.
10272     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10273            E = CS.arg_end(); I != E; ++I, ++ix) {
10274       CastInst *CI = dyn_cast<CastInst>(*I);
10275       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10276         *I = CI->getOperand(0);
10277         Changed = true;
10278       }
10279     }
10280   }
10281
10282   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10283     // Inline asm calls cannot throw - mark them 'nounwind'.
10284     CS.setDoesNotThrow();
10285     Changed = true;
10286   }
10287
10288   return Changed ? CS.getInstruction() : 0;
10289 }
10290
10291 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10292 // attempt to move the cast to the arguments of the call/invoke.
10293 //
10294 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10295   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10296   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10297   if (CE->getOpcode() != Instruction::BitCast || 
10298       !isa<Function>(CE->getOperand(0)))
10299     return false;
10300   Function *Callee = cast<Function>(CE->getOperand(0));
10301   Instruction *Caller = CS.getInstruction();
10302   const AttrListPtr &CallerPAL = CS.getAttributes();
10303
10304   // Okay, this is a cast from a function to a different type.  Unless doing so
10305   // would cause a type conversion of one of our arguments, change this call to
10306   // be a direct call with arguments casted to the appropriate types.
10307   //
10308   const FunctionType *FT = Callee->getFunctionType();
10309   const Type *OldRetTy = Caller->getType();
10310   const Type *NewRetTy = FT->getReturnType();
10311
10312   if (isa<StructType>(NewRetTy))
10313     return false; // TODO: Handle multiple return values.
10314
10315   // Check to see if we are changing the return type...
10316   if (OldRetTy != NewRetTy) {
10317     if (Callee->isDeclaration() &&
10318         // Conversion is ok if changing from one pointer type to another or from
10319         // a pointer to an integer of the same size.
10320         !((isa<PointerType>(OldRetTy) || !TD ||
10321            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10322           (isa<PointerType>(NewRetTy) || !TD ||
10323            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10324       return false;   // Cannot transform this return value.
10325
10326     if (!Caller->use_empty() &&
10327         // void -> non-void is handled specially
10328         !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
10329       return false;   // Cannot transform this return value.
10330
10331     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10332       Attributes RAttrs = CallerPAL.getRetAttributes();
10333       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10334         return false;   // Attribute not compatible with transformed value.
10335     }
10336
10337     // If the callsite is an invoke instruction, and the return value is used by
10338     // a PHI node in a successor, we cannot change the return type of the call
10339     // because there is no place to put the cast instruction (without breaking
10340     // the critical edge).  Bail out in this case.
10341     if (!Caller->use_empty())
10342       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10343         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10344              UI != E; ++UI)
10345           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10346             if (PN->getParent() == II->getNormalDest() ||
10347                 PN->getParent() == II->getUnwindDest())
10348               return false;
10349   }
10350
10351   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10352   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10353
10354   CallSite::arg_iterator AI = CS.arg_begin();
10355   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10356     const Type *ParamTy = FT->getParamType(i);
10357     const Type *ActTy = (*AI)->getType();
10358
10359     if (!CastInst::isCastable(ActTy, ParamTy))
10360       return false;   // Cannot transform this parameter value.
10361
10362     if (CallerPAL.getParamAttributes(i + 1) 
10363         & Attribute::typeIncompatible(ParamTy))
10364       return false;   // Attribute not compatible with transformed value.
10365
10366     // Converting from one pointer type to another or between a pointer and an
10367     // integer of the same size is safe even if we do not have a body.
10368     bool isConvertible = ActTy == ParamTy ||
10369       (TD && ((isa<PointerType>(ParamTy) ||
10370       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10371               (isa<PointerType>(ActTy) ||
10372               ActTy == TD->getIntPtrType(Caller->getContext()))));
10373     if (Callee->isDeclaration() && !isConvertible) return false;
10374   }
10375
10376   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10377       Callee->isDeclaration())
10378     return false;   // Do not delete arguments unless we have a function body.
10379
10380   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10381       !CallerPAL.isEmpty())
10382     // In this case we have more arguments than the new function type, but we
10383     // won't be dropping them.  Check that these extra arguments have attributes
10384     // that are compatible with being a vararg call argument.
10385     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10386       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10387         break;
10388       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10389       if (PAttrs & Attribute::VarArgsIncompatible)
10390         return false;
10391     }
10392
10393   // Okay, we decided that this is a safe thing to do: go ahead and start
10394   // inserting cast instructions as necessary...
10395   std::vector<Value*> Args;
10396   Args.reserve(NumActualArgs);
10397   SmallVector<AttributeWithIndex, 8> attrVec;
10398   attrVec.reserve(NumCommonArgs);
10399
10400   // Get any return attributes.
10401   Attributes RAttrs = CallerPAL.getRetAttributes();
10402
10403   // If the return value is not being used, the type may not be compatible
10404   // with the existing attributes.  Wipe out any problematic attributes.
10405   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10406
10407   // Add the new return attributes.
10408   if (RAttrs)
10409     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10410
10411   AI = CS.arg_begin();
10412   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10413     const Type *ParamTy = FT->getParamType(i);
10414     if ((*AI)->getType() == ParamTy) {
10415       Args.push_back(*AI);
10416     } else {
10417       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10418           false, ParamTy, false);
10419       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10420     }
10421
10422     // Add any parameter attributes.
10423     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10424       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10425   }
10426
10427   // If the function takes more arguments than the call was taking, add them
10428   // now.
10429   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10430     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10431
10432   // If we are removing arguments to the function, emit an obnoxious warning.
10433   if (FT->getNumParams() < NumActualArgs) {
10434     if (!FT->isVarArg()) {
10435       errs() << "WARNING: While resolving call to function '"
10436              << Callee->getName() << "' arguments were dropped!\n";
10437     } else {
10438       // Add all of the arguments in their promoted form to the arg list.
10439       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10440         const Type *PTy = getPromotedType((*AI)->getType());
10441         if (PTy != (*AI)->getType()) {
10442           // Must promote to pass through va_arg area!
10443           Instruction::CastOps opcode =
10444             CastInst::getCastOpcode(*AI, false, PTy, false);
10445           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10446         } else {
10447           Args.push_back(*AI);
10448         }
10449
10450         // Add any parameter attributes.
10451         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10452           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10453       }
10454     }
10455   }
10456
10457   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10458     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10459
10460   if (NewRetTy->isVoidTy())
10461     Caller->setName("");   // Void type should not have a name.
10462
10463   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10464                                                      attrVec.end());
10465
10466   Instruction *NC;
10467   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10468     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10469                             Args.begin(), Args.end(),
10470                             Caller->getName(), Caller);
10471     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10472     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10473   } else {
10474     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10475                           Caller->getName(), Caller);
10476     CallInst *CI = cast<CallInst>(Caller);
10477     if (CI->isTailCall())
10478       cast<CallInst>(NC)->setTailCall();
10479     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10480     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10481   }
10482
10483   // Insert a cast of the return type as necessary.
10484   Value *NV = NC;
10485   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10486     if (!NV->getType()->isVoidTy()) {
10487       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10488                                                             OldRetTy, false);
10489       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10490
10491       // If this is an invoke instruction, we should insert it after the first
10492       // non-phi, instruction in the normal successor block.
10493       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10494         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10495         InsertNewInstBefore(NC, *I);
10496       } else {
10497         // Otherwise, it's a call, just insert cast right after the call instr
10498         InsertNewInstBefore(NC, *Caller);
10499       }
10500       Worklist.AddUsersToWorkList(*Caller);
10501     } else {
10502       NV = UndefValue::get(Caller->getType());
10503     }
10504   }
10505
10506
10507   if (!Caller->use_empty())
10508     Caller->replaceAllUsesWith(NV);
10509   
10510   EraseInstFromFunction(*Caller);
10511   return true;
10512 }
10513
10514 // transformCallThroughTrampoline - Turn a call to a function created by the
10515 // init_trampoline intrinsic into a direct call to the underlying function.
10516 //
10517 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10518   Value *Callee = CS.getCalledValue();
10519   const PointerType *PTy = cast<PointerType>(Callee->getType());
10520   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10521   const AttrListPtr &Attrs = CS.getAttributes();
10522
10523   // If the call already has the 'nest' attribute somewhere then give up -
10524   // otherwise 'nest' would occur twice after splicing in the chain.
10525   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10526     return 0;
10527
10528   IntrinsicInst *Tramp =
10529     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10530
10531   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10532   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10533   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10534
10535   const AttrListPtr &NestAttrs = NestF->getAttributes();
10536   if (!NestAttrs.isEmpty()) {
10537     unsigned NestIdx = 1;
10538     const Type *NestTy = 0;
10539     Attributes NestAttr = Attribute::None;
10540
10541     // Look for a parameter marked with the 'nest' attribute.
10542     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10543          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10544       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10545         // Record the parameter type and any other attributes.
10546         NestTy = *I;
10547         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10548         break;
10549       }
10550
10551     if (NestTy) {
10552       Instruction *Caller = CS.getInstruction();
10553       std::vector<Value*> NewArgs;
10554       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10555
10556       SmallVector<AttributeWithIndex, 8> NewAttrs;
10557       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10558
10559       // Insert the nest argument into the call argument list, which may
10560       // mean appending it.  Likewise for attributes.
10561
10562       // Add any result attributes.
10563       if (Attributes Attr = Attrs.getRetAttributes())
10564         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10565
10566       {
10567         unsigned Idx = 1;
10568         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10569         do {
10570           if (Idx == NestIdx) {
10571             // Add the chain argument and attributes.
10572             Value *NestVal = Tramp->getOperand(3);
10573             if (NestVal->getType() != NestTy)
10574               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10575             NewArgs.push_back(NestVal);
10576             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10577           }
10578
10579           if (I == E)
10580             break;
10581
10582           // Add the original argument and attributes.
10583           NewArgs.push_back(*I);
10584           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10585             NewAttrs.push_back
10586               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10587
10588           ++Idx, ++I;
10589         } while (1);
10590       }
10591
10592       // Add any function attributes.
10593       if (Attributes Attr = Attrs.getFnAttributes())
10594         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10595
10596       // The trampoline may have been bitcast to a bogus type (FTy).
10597       // Handle this by synthesizing a new function type, equal to FTy
10598       // with the chain parameter inserted.
10599
10600       std::vector<const Type*> NewTypes;
10601       NewTypes.reserve(FTy->getNumParams()+1);
10602
10603       // Insert the chain's type into the list of parameter types, which may
10604       // mean appending it.
10605       {
10606         unsigned Idx = 1;
10607         FunctionType::param_iterator I = FTy->param_begin(),
10608           E = FTy->param_end();
10609
10610         do {
10611           if (Idx == NestIdx)
10612             // Add the chain's type.
10613             NewTypes.push_back(NestTy);
10614
10615           if (I == E)
10616             break;
10617
10618           // Add the original type.
10619           NewTypes.push_back(*I);
10620
10621           ++Idx, ++I;
10622         } while (1);
10623       }
10624
10625       // Replace the trampoline call with a direct call.  Let the generic
10626       // code sort out any function type mismatches.
10627       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10628                                                 FTy->isVarArg());
10629       Constant *NewCallee =
10630         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10631         NestF : ConstantExpr::getBitCast(NestF, 
10632                                          PointerType::getUnqual(NewFTy));
10633       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10634                                                    NewAttrs.end());
10635
10636       Instruction *NewCaller;
10637       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10638         NewCaller = InvokeInst::Create(NewCallee,
10639                                        II->getNormalDest(), II->getUnwindDest(),
10640                                        NewArgs.begin(), NewArgs.end(),
10641                                        Caller->getName(), Caller);
10642         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10643         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10644       } else {
10645         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10646                                      Caller->getName(), Caller);
10647         if (cast<CallInst>(Caller)->isTailCall())
10648           cast<CallInst>(NewCaller)->setTailCall();
10649         cast<CallInst>(NewCaller)->
10650           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10651         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10652       }
10653       if (!Caller->getType()->isVoidTy())
10654         Caller->replaceAllUsesWith(NewCaller);
10655       Caller->eraseFromParent();
10656       Worklist.Remove(Caller);
10657       return 0;
10658     }
10659   }
10660
10661   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10662   // parameter, there is no need to adjust the argument list.  Let the generic
10663   // code sort out any function type mismatches.
10664   Constant *NewCallee =
10665     NestF->getType() == PTy ? NestF : 
10666                               ConstantExpr::getBitCast(NestF, PTy);
10667   CS.setCalledFunction(NewCallee);
10668   return CS.getInstruction();
10669 }
10670
10671 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10672 /// and if a/b/c and the add's all have a single use, turn this into a phi
10673 /// and a single binop.
10674 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10675   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10676   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10677   unsigned Opc = FirstInst->getOpcode();
10678   Value *LHSVal = FirstInst->getOperand(0);
10679   Value *RHSVal = FirstInst->getOperand(1);
10680     
10681   const Type *LHSType = LHSVal->getType();
10682   const Type *RHSType = RHSVal->getType();
10683   
10684   // Scan to see if all operands are the same opcode, and all have one use.
10685   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10686     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10687     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10688         // Verify type of the LHS matches so we don't fold cmp's of different
10689         // types or GEP's with different index types.
10690         I->getOperand(0)->getType() != LHSType ||
10691         I->getOperand(1)->getType() != RHSType)
10692       return 0;
10693
10694     // If they are CmpInst instructions, check their predicates
10695     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10696       if (cast<CmpInst>(I)->getPredicate() !=
10697           cast<CmpInst>(FirstInst)->getPredicate())
10698         return 0;
10699     
10700     // Keep track of which operand needs a phi node.
10701     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10702     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10703   }
10704
10705   // If both LHS and RHS would need a PHI, don't do this transformation,
10706   // because it would increase the number of PHIs entering the block,
10707   // which leads to higher register pressure. This is especially
10708   // bad when the PHIs are in the header of a loop.
10709   if (!LHSVal && !RHSVal)
10710     return 0;
10711   
10712   // Otherwise, this is safe to transform!
10713   
10714   Value *InLHS = FirstInst->getOperand(0);
10715   Value *InRHS = FirstInst->getOperand(1);
10716   PHINode *NewLHS = 0, *NewRHS = 0;
10717   if (LHSVal == 0) {
10718     NewLHS = PHINode::Create(LHSType,
10719                              FirstInst->getOperand(0)->getName() + ".pn");
10720     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10721     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10722     InsertNewInstBefore(NewLHS, PN);
10723     LHSVal = NewLHS;
10724   }
10725   
10726   if (RHSVal == 0) {
10727     NewRHS = PHINode::Create(RHSType,
10728                              FirstInst->getOperand(1)->getName() + ".pn");
10729     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10730     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10731     InsertNewInstBefore(NewRHS, PN);
10732     RHSVal = NewRHS;
10733   }
10734   
10735   // Add all operands to the new PHIs.
10736   if (NewLHS || NewRHS) {
10737     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10738       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10739       if (NewLHS) {
10740         Value *NewInLHS = InInst->getOperand(0);
10741         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10742       }
10743       if (NewRHS) {
10744         Value *NewInRHS = InInst->getOperand(1);
10745         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10746       }
10747     }
10748   }
10749     
10750   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10751     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10752   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10753   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10754                          LHSVal, RHSVal);
10755 }
10756
10757 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10758   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10759   
10760   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10761                                         FirstInst->op_end());
10762   // This is true if all GEP bases are allocas and if all indices into them are
10763   // constants.
10764   bool AllBasePointersAreAllocas = true;
10765
10766   // We don't want to replace this phi if the replacement would require
10767   // more than one phi, which leads to higher register pressure. This is
10768   // especially bad when the PHIs are in the header of a loop.
10769   bool NeededPhi = false;
10770   
10771   // Scan to see if all operands are the same opcode, and all have one use.
10772   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10773     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10774     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10775       GEP->getNumOperands() != FirstInst->getNumOperands())
10776       return 0;
10777
10778     // Keep track of whether or not all GEPs are of alloca pointers.
10779     if (AllBasePointersAreAllocas &&
10780         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10781          !GEP->hasAllConstantIndices()))
10782       AllBasePointersAreAllocas = false;
10783     
10784     // Compare the operand lists.
10785     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10786       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10787         continue;
10788       
10789       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10790       // if one of the PHIs has a constant for the index.  The index may be
10791       // substantially cheaper to compute for the constants, so making it a
10792       // variable index could pessimize the path.  This also handles the case
10793       // for struct indices, which must always be constant.
10794       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10795           isa<ConstantInt>(GEP->getOperand(op)))
10796         return 0;
10797       
10798       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10799         return 0;
10800
10801       // If we already needed a PHI for an earlier operand, and another operand
10802       // also requires a PHI, we'd be introducing more PHIs than we're
10803       // eliminating, which increases register pressure on entry to the PHI's
10804       // block.
10805       if (NeededPhi)
10806         return 0;
10807
10808       FixedOperands[op] = 0;  // Needs a PHI.
10809       NeededPhi = true;
10810     }
10811   }
10812   
10813   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10814   // bother doing this transformation.  At best, this will just save a bit of
10815   // offset calculation, but all the predecessors will have to materialize the
10816   // stack address into a register anyway.  We'd actually rather *clone* the
10817   // load up into the predecessors so that we have a load of a gep of an alloca,
10818   // which can usually all be folded into the load.
10819   if (AllBasePointersAreAllocas)
10820     return 0;
10821   
10822   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10823   // that is variable.
10824   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10825   
10826   bool HasAnyPHIs = false;
10827   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10828     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10829     Value *FirstOp = FirstInst->getOperand(i);
10830     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10831                                      FirstOp->getName()+".pn");
10832     InsertNewInstBefore(NewPN, PN);
10833     
10834     NewPN->reserveOperandSpace(e);
10835     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10836     OperandPhis[i] = NewPN;
10837     FixedOperands[i] = NewPN;
10838     HasAnyPHIs = true;
10839   }
10840
10841   
10842   // Add all operands to the new PHIs.
10843   if (HasAnyPHIs) {
10844     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10845       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10846       BasicBlock *InBB = PN.getIncomingBlock(i);
10847       
10848       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10849         if (PHINode *OpPhi = OperandPhis[op])
10850           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10851     }
10852   }
10853   
10854   Value *Base = FixedOperands[0];
10855   return cast<GEPOperator>(FirstInst)->isInBounds() ?
10856     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10857                                       FixedOperands.end()) :
10858     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10859                               FixedOperands.end());
10860 }
10861
10862
10863 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10864 /// sink the load out of the block that defines it.  This means that it must be
10865 /// obvious the value of the load is not changed from the point of the load to
10866 /// the end of the block it is in.
10867 ///
10868 /// Finally, it is safe, but not profitable, to sink a load targetting a
10869 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10870 /// to a register.
10871 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10872   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10873   
10874   for (++BBI; BBI != E; ++BBI)
10875     if (BBI->mayWriteToMemory())
10876       return false;
10877   
10878   // Check for non-address taken alloca.  If not address-taken already, it isn't
10879   // profitable to do this xform.
10880   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10881     bool isAddressTaken = false;
10882     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10883          UI != E; ++UI) {
10884       if (isa<LoadInst>(UI)) continue;
10885       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10886         // If storing TO the alloca, then the address isn't taken.
10887         if (SI->getOperand(1) == AI) continue;
10888       }
10889       isAddressTaken = true;
10890       break;
10891     }
10892     
10893     if (!isAddressTaken && AI->isStaticAlloca())
10894       return false;
10895   }
10896   
10897   // If this load is a load from a GEP with a constant offset from an alloca,
10898   // then we don't want to sink it.  In its present form, it will be
10899   // load [constant stack offset].  Sinking it will cause us to have to
10900   // materialize the stack addresses in each predecessor in a register only to
10901   // do a shared load from register in the successor.
10902   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10903     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10904       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10905         return false;
10906   
10907   return true;
10908 }
10909
10910 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
10911   LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
10912   
10913   // When processing loads, we need to propagate two bits of information to the
10914   // sunk load: whether it is volatile, and what its alignment is.  We currently
10915   // don't sink loads when some have their alignment specified and some don't.
10916   // visitLoadInst will propagate an alignment onto the load when TD is around,
10917   // and if TD isn't around, we can't handle the mixed case.
10918   bool isVolatile = FirstLI->isVolatile();
10919   unsigned LoadAlignment = FirstLI->getAlignment();
10920   
10921   // We can't sink the load if the loaded value could be modified between the
10922   // load and the PHI.
10923   if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
10924       !isSafeAndProfitableToSinkLoad(FirstLI))
10925     return 0;
10926   
10927   // If the PHI is of volatile loads and the load block has multiple
10928   // successors, sinking it would remove a load of the volatile value from
10929   // the path through the other successor.
10930   if (isVolatile && 
10931       FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
10932     return 0;
10933   
10934   // Check to see if all arguments are the same operation.
10935   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10936     LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
10937     if (!LI || !LI->hasOneUse())
10938       return 0;
10939     
10940     // We can't sink the load if the loaded value could be modified between 
10941     // the load and the PHI.
10942     if (LI->isVolatile() != isVolatile ||
10943         LI->getParent() != PN.getIncomingBlock(i) ||
10944         !isSafeAndProfitableToSinkLoad(LI))
10945       return 0;
10946       
10947     // If some of the loads have an alignment specified but not all of them,
10948     // we can't do the transformation.
10949     if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
10950       return 0;
10951     
10952     LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
10953     
10954     // If the PHI is of volatile loads and the load block has multiple
10955     // successors, sinking it would remove a load of the volatile value from
10956     // the path through the other successor.
10957     if (isVolatile &&
10958         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10959       return 0;
10960   }
10961   
10962   // Okay, they are all the same operation.  Create a new PHI node of the
10963   // correct type, and PHI together all of the LHS's of the instructions.
10964   PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
10965                                    PN.getName()+".in");
10966   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10967   
10968   Value *InVal = FirstLI->getOperand(0);
10969   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10970   
10971   // Add all operands to the new PHI.
10972   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10973     Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
10974     if (NewInVal != InVal)
10975       InVal = 0;
10976     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10977   }
10978   
10979   Value *PhiVal;
10980   if (InVal) {
10981     // The new PHI unions all of the same values together.  This is really
10982     // common, so we handle it intelligently here for compile-time speed.
10983     PhiVal = InVal;
10984     delete NewPN;
10985   } else {
10986     InsertNewInstBefore(NewPN, PN);
10987     PhiVal = NewPN;
10988   }
10989   
10990   // If this was a volatile load that we are merging, make sure to loop through
10991   // and mark all the input loads as non-volatile.  If we don't do this, we will
10992   // insert a new volatile load and the old ones will not be deletable.
10993   if (isVolatile)
10994     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10995       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10996   
10997   return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
10998 }
10999
11000
11001
11002 /// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11003 /// operator and they all are only used by the PHI, PHI together their
11004 /// inputs, and do the operation once, to the result of the PHI.
11005 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11006   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11007
11008   if (isa<GetElementPtrInst>(FirstInst))
11009     return FoldPHIArgGEPIntoPHI(PN);
11010   if (isa<LoadInst>(FirstInst))
11011     return FoldPHIArgLoadIntoPHI(PN);
11012   
11013   // Scan the instruction, looking for input operations that can be folded away.
11014   // If all input operands to the phi are the same instruction (e.g. a cast from
11015   // the same type or "+42") we can pull the operation through the PHI, reducing
11016   // code size and simplifying code.
11017   Constant *ConstantOp = 0;
11018   const Type *CastSrcTy = 0;
11019   
11020   if (isa<CastInst>(FirstInst)) {
11021     CastSrcTy = FirstInst->getOperand(0)->getType();
11022
11023     // Be careful about transforming integer PHIs.  We don't want to pessimize
11024     // the code by turning an i32 into an i1293.
11025     if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
11026       if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
11027         return 0;
11028     }
11029   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
11030     // Can fold binop, compare or shift here if the RHS is a constant, 
11031     // otherwise call FoldPHIArgBinOpIntoPHI.
11032     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
11033     if (ConstantOp == 0)
11034       return FoldPHIArgBinOpIntoPHI(PN);
11035   } else {
11036     return 0;  // Cannot fold this operation.
11037   }
11038
11039   // Check to see if all arguments are the same operation.
11040   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11041     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11042     if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
11043       return 0;
11044     if (CastSrcTy) {
11045       if (I->getOperand(0)->getType() != CastSrcTy)
11046         return 0;  // Cast operation must match.
11047     } else if (I->getOperand(1) != ConstantOp) {
11048       return 0;
11049     }
11050   }
11051
11052   // Okay, they are all the same operation.  Create a new PHI node of the
11053   // correct type, and PHI together all of the LHS's of the instructions.
11054   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11055                                    PN.getName()+".in");
11056   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11057
11058   Value *InVal = FirstInst->getOperand(0);
11059   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11060
11061   // Add all operands to the new PHI.
11062   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11063     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11064     if (NewInVal != InVal)
11065       InVal = 0;
11066     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11067   }
11068
11069   Value *PhiVal;
11070   if (InVal) {
11071     // The new PHI unions all of the same values together.  This is really
11072     // common, so we handle it intelligently here for compile-time speed.
11073     PhiVal = InVal;
11074     delete NewPN;
11075   } else {
11076     InsertNewInstBefore(NewPN, PN);
11077     PhiVal = NewPN;
11078   }
11079
11080   // Insert and return the new operation.
11081   if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
11082     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
11083   
11084   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
11085     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
11086   
11087   CmpInst *CIOp = cast<CmpInst>(FirstInst);
11088   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11089                          PhiVal, ConstantOp);
11090 }
11091
11092 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11093 /// that is dead.
11094 static bool DeadPHICycle(PHINode *PN,
11095                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
11096   if (PN->use_empty()) return true;
11097   if (!PN->hasOneUse()) return false;
11098
11099   // Remember this node, and if we find the cycle, return.
11100   if (!PotentiallyDeadPHIs.insert(PN))
11101     return true;
11102   
11103   // Don't scan crazily complex things.
11104   if (PotentiallyDeadPHIs.size() == 16)
11105     return false;
11106
11107   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11108     return DeadPHICycle(PU, PotentiallyDeadPHIs);
11109
11110   return false;
11111 }
11112
11113 /// PHIsEqualValue - Return true if this phi node is always equal to
11114 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
11115 ///   z = some value; x = phi (y, z); y = phi (x, z)
11116 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
11117                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11118   // See if we already saw this PHI node.
11119   if (!ValueEqualPHIs.insert(PN))
11120     return true;
11121   
11122   // Don't scan crazily complex things.
11123   if (ValueEqualPHIs.size() == 16)
11124     return false;
11125  
11126   // Scan the operands to see if they are either phi nodes or are equal to
11127   // the value.
11128   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11129     Value *Op = PN->getIncomingValue(i);
11130     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11131       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11132         return false;
11133     } else if (Op != NonPhiInVal)
11134       return false;
11135   }
11136   
11137   return true;
11138 }
11139
11140
11141 namespace {
11142 struct PHIUsageRecord {
11143   unsigned PHIId;     // The ID # of the PHI (something determinstic to sort on)
11144   unsigned Shift;     // The amount shifted.
11145   Instruction *Inst;  // The trunc instruction.
11146   
11147   PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11148     : PHIId(pn), Shift(Sh), Inst(User) {}
11149   
11150   bool operator<(const PHIUsageRecord &RHS) const {
11151     if (PHIId < RHS.PHIId) return true;
11152     if (PHIId > RHS.PHIId) return false;
11153     if (Shift < RHS.Shift) return true;
11154     if (Shift > RHS.Shift) return false;
11155     return Inst->getType()->getPrimitiveSizeInBits() <
11156            RHS.Inst->getType()->getPrimitiveSizeInBits();
11157   }
11158 };
11159   
11160 struct LoweredPHIRecord {
11161   PHINode *PN;        // The PHI that was lowered.
11162   unsigned Shift;     // The amount shifted.
11163   unsigned Width;     // The width extracted.
11164   
11165   LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11166     : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11167   
11168   // Ctor form used by DenseMap.
11169   LoweredPHIRecord(PHINode *pn, unsigned Sh)
11170     : PN(pn), Shift(Sh), Width(0) {}
11171 };
11172 }
11173
11174 namespace llvm {
11175   template<>
11176   struct DenseMapInfo<LoweredPHIRecord> {
11177     static inline LoweredPHIRecord getEmptyKey() {
11178       return LoweredPHIRecord(0, 0);
11179     }
11180     static inline LoweredPHIRecord getTombstoneKey() {
11181       return LoweredPHIRecord(0, 1);
11182     }
11183     static unsigned getHashValue(const LoweredPHIRecord &Val) {
11184       return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11185              (Val.Width>>3);
11186     }
11187     static bool isEqual(const LoweredPHIRecord &LHS,
11188                         const LoweredPHIRecord &RHS) {
11189       return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11190              LHS.Width == RHS.Width;
11191     }
11192     static bool isPod() { return true; }
11193   };
11194 }
11195
11196
11197 /// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11198 /// illegal type: see if it is only used by trunc or trunc(lshr) operations.  If
11199 /// so, we split the PHI into the various pieces being extracted.  This sort of
11200 /// thing is introduced when SROA promotes an aggregate to large integer values.
11201 ///
11202 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11203 /// inttoptr.  We should produce new PHIs in the right type.
11204 ///
11205 Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11206   // PHIUsers - Keep track of all of the truncated values extracted from a set
11207   // of PHIs, along with their offset.  These are the things we want to rewrite.
11208   SmallVector<PHIUsageRecord, 16> PHIUsers;
11209   
11210   // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11211   // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11212   // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11213   // check the uses of (to ensure they are all extracts).
11214   SmallVector<PHINode*, 8> PHIsToSlice;
11215   SmallPtrSet<PHINode*, 8> PHIsInspected;
11216   
11217   PHIsToSlice.push_back(&FirstPhi);
11218   PHIsInspected.insert(&FirstPhi);
11219   
11220   for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11221     PHINode *PN = PHIsToSlice[PHIId];
11222     
11223     for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11224          UI != E; ++UI) {
11225       Instruction *User = cast<Instruction>(*UI);
11226       
11227       // If the user is a PHI, inspect its uses recursively.
11228       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11229         if (PHIsInspected.insert(UserPN))
11230           PHIsToSlice.push_back(UserPN);
11231         continue;
11232       }
11233       
11234       // Truncates are always ok.
11235       if (isa<TruncInst>(User)) {
11236         PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11237         continue;
11238       }
11239       
11240       // Otherwise it must be a lshr which can only be used by one trunc.
11241       if (User->getOpcode() != Instruction::LShr ||
11242           !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11243           !isa<ConstantInt>(User->getOperand(1)))
11244         return 0;
11245       
11246       unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11247       PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
11248     }
11249   }
11250   
11251   // If we have no users, they must be all self uses, just nuke the PHI.
11252   if (PHIUsers.empty())
11253     return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
11254   
11255   // If this phi node is transformable, create new PHIs for all the pieces
11256   // extracted out of it.  First, sort the users by their offset and size.
11257   array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11258   
11259   DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11260             for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11261               errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11262         );
11263   
11264   // PredValues - This is a temporary used when rewriting PHI nodes.  It is
11265   // hoisted out here to avoid construction/destruction thrashing.
11266   DenseMap<BasicBlock*, Value*> PredValues;
11267   
11268   // ExtractedVals - Each new PHI we introduce is saved here so we don't
11269   // introduce redundant PHIs.
11270   DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11271   
11272   for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11273     unsigned PHIId = PHIUsers[UserI].PHIId;
11274     PHINode *PN = PHIsToSlice[PHIId];
11275     unsigned Offset = PHIUsers[UserI].Shift;
11276     const Type *Ty = PHIUsers[UserI].Inst->getType();
11277     
11278     PHINode *EltPHI;
11279     
11280     // If we've already lowered a user like this, reuse the previously lowered
11281     // value.
11282     if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
11283       
11284       // Otherwise, Create the new PHI node for this user.
11285       EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11286       assert(EltPHI->getType() != PN->getType() &&
11287              "Truncate didn't shrink phi?");
11288     
11289       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11290         BasicBlock *Pred = PN->getIncomingBlock(i);
11291         Value *&PredVal = PredValues[Pred];
11292         
11293         // If we already have a value for this predecessor, reuse it.
11294         if (PredVal) {
11295           EltPHI->addIncoming(PredVal, Pred);
11296           continue;
11297         }
11298
11299         // Handle the PHI self-reuse case.
11300         Value *InVal = PN->getIncomingValue(i);
11301         if (InVal == PN) {
11302           PredVal = EltPHI;
11303           EltPHI->addIncoming(PredVal, Pred);
11304           continue;
11305         } else if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
11306           // If the incoming value was a PHI, and if it was one of the PHIs we
11307           // already rewrote it, just use the lowered value.
11308           if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11309             PredVal = Res;
11310             EltPHI->addIncoming(PredVal, Pred);
11311             continue;
11312           }
11313         }
11314         
11315         // Otherwise, do an extract in the predecessor.
11316         Builder->SetInsertPoint(Pred, Pred->getTerminator());
11317         Value *Res = InVal;
11318         if (Offset)
11319           Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11320                                                           Offset), "extract");
11321         Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11322         PredVal = Res;
11323         EltPHI->addIncoming(Res, Pred);
11324         
11325         // If the incoming value was a PHI, and if it was one of the PHIs we are
11326         // rewriting, we will ultimately delete the code we inserted.  This
11327         // means we need to revisit that PHI to make sure we extract out the
11328         // needed piece.
11329         if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11330           if (PHIsInspected.count(OldInVal)) {
11331             unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11332                                           OldInVal)-PHIsToSlice.begin();
11333             PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset, 
11334                                               cast<Instruction>(Res)));
11335             ++UserE;
11336           }
11337       }
11338       PredValues.clear();
11339       
11340       DEBUG(errs() << "  Made element PHI for offset " << Offset << ": "
11341                    << *EltPHI << '\n');
11342       ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
11343     }
11344     
11345     // Replace the use of this piece with the PHI node.
11346     ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
11347   }
11348   
11349   // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11350   // with undefs.
11351   Value *Undef = UndefValue::get(FirstPhi.getType());
11352   for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11353     ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11354   return ReplaceInstUsesWith(FirstPhi, Undef);
11355 }
11356
11357 // PHINode simplification
11358 //
11359 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
11360   // If LCSSA is around, don't mess with Phi nodes
11361   if (MustPreserveLCSSA) return 0;
11362   
11363   if (Value *V = PN.hasConstantValue())
11364     return ReplaceInstUsesWith(PN, V);
11365
11366   // If all PHI operands are the same operation, pull them through the PHI,
11367   // reducing code size.
11368   if (isa<Instruction>(PN.getIncomingValue(0)) &&
11369       isa<Instruction>(PN.getIncomingValue(1)) &&
11370       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11371       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11372       // FIXME: The hasOneUse check will fail for PHIs that use the value more
11373       // than themselves more than once.
11374       PN.getIncomingValue(0)->hasOneUse())
11375     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11376       return Result;
11377
11378   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
11379   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11380   // PHI)... break the cycle.
11381   if (PN.hasOneUse()) {
11382     Instruction *PHIUser = cast<Instruction>(PN.use_back());
11383     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
11384       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
11385       PotentiallyDeadPHIs.insert(&PN);
11386       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
11387         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11388     }
11389    
11390     // If this phi has a single use, and if that use just computes a value for
11391     // the next iteration of a loop, delete the phi.  This occurs with unused
11392     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
11393     // common case here is good because the only other things that catch this
11394     // are induction variable analysis (sometimes) and ADCE, which is only run
11395     // late.
11396     if (PHIUser->hasOneUse() &&
11397         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11398         PHIUser->use_back() == &PN) {
11399       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11400     }
11401   }
11402
11403   // We sometimes end up with phi cycles that non-obviously end up being the
11404   // same value, for example:
11405   //   z = some value; x = phi (y, z); y = phi (x, z)
11406   // where the phi nodes don't necessarily need to be in the same block.  Do a
11407   // quick check to see if the PHI node only contains a single non-phi value, if
11408   // so, scan to see if the phi cycle is actually equal to that value.
11409   {
11410     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11411     // Scan for the first non-phi operand.
11412     while (InValNo != NumOperandVals && 
11413            isa<PHINode>(PN.getIncomingValue(InValNo)))
11414       ++InValNo;
11415
11416     if (InValNo != NumOperandVals) {
11417       Value *NonPhiInVal = PN.getOperand(InValNo);
11418       
11419       // Scan the rest of the operands to see if there are any conflicts, if so
11420       // there is no need to recursively scan other phis.
11421       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11422         Value *OpVal = PN.getIncomingValue(InValNo);
11423         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11424           break;
11425       }
11426       
11427       // If we scanned over all operands, then we have one unique value plus
11428       // phi values.  Scan PHI nodes to see if they all merge in each other or
11429       // the value.
11430       if (InValNo == NumOperandVals) {
11431         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11432         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11433           return ReplaceInstUsesWith(PN, NonPhiInVal);
11434       }
11435     }
11436   }
11437
11438   // If there are multiple PHIs, sort their operands so that they all list
11439   // the blocks in the same order. This will help identical PHIs be eliminated
11440   // by other passes. Other passes shouldn't depend on this for correctness
11441   // however.
11442   PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11443   if (&PN != FirstPN)
11444     for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
11445       BasicBlock *BBA = PN.getIncomingBlock(i);
11446       BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11447       if (BBA != BBB) {
11448         Value *VA = PN.getIncomingValue(i);
11449         unsigned j = PN.getBasicBlockIndex(BBB);
11450         Value *VB = PN.getIncomingValue(j);
11451         PN.setIncomingBlock(i, BBB);
11452         PN.setIncomingValue(i, VB);
11453         PN.setIncomingBlock(j, BBA);
11454         PN.setIncomingValue(j, VA);
11455         // NOTE: Instcombine normally would want us to "return &PN" if we
11456         // modified any of the operands of an instruction.  However, since we
11457         // aren't adding or removing uses (just rearranging them) we don't do
11458         // this in this case.
11459       }
11460     }
11461
11462   // If this is an integer PHI and we know that it has an illegal type, see if
11463   // it is only used by trunc or trunc(lshr) operations.  If so, we split the
11464   // PHI into the various pieces being extracted.  This sort of thing is
11465   // introduced when SROA promotes an aggregate to a single large integer type.
11466   if (isa<IntegerType>(PN.getType()) && TD &&
11467       !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11468     if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11469       return Res;
11470   
11471   return 0;
11472 }
11473
11474 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11475   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
11476
11477   if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
11478     return ReplaceInstUsesWith(GEP, V);
11479
11480   Value *PtrOp = GEP.getOperand(0);
11481
11482   if (isa<UndefValue>(GEP.getOperand(0)))
11483     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
11484
11485   // Eliminate unneeded casts for indices.
11486   if (TD) {
11487     bool MadeChange = false;
11488     unsigned PtrSize = TD->getPointerSizeInBits();
11489     
11490     gep_type_iterator GTI = gep_type_begin(GEP);
11491     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11492          I != E; ++I, ++GTI) {
11493       if (!isa<SequentialType>(*GTI)) continue;
11494       
11495       // If we are using a wider index than needed for this platform, shrink it
11496       // to what we need.  If narrower, sign-extend it to what we need.  This
11497       // explicit cast can make subsequent optimizations more obvious.
11498       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11499       if (OpBits == PtrSize)
11500         continue;
11501       
11502       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
11503       MadeChange = true;
11504     }
11505     if (MadeChange) return &GEP;
11506   }
11507
11508   // Combine Indices - If the source pointer to this getelementptr instruction
11509   // is a getelementptr instruction, combine the indices of the two
11510   // getelementptr instructions into a single instruction.
11511   //
11512   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11513     // Note that if our source is a gep chain itself that we wait for that
11514     // chain to be resolved before we perform this transformation.  This
11515     // avoids us creating a TON of code in some cases.
11516     //
11517     if (GetElementPtrInst *SrcGEP =
11518           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11519       if (SrcGEP->getNumOperands() == 2)
11520         return 0;   // Wait until our source is folded to completion.
11521
11522     SmallVector<Value*, 8> Indices;
11523
11524     // Find out whether the last index in the source GEP is a sequential idx.
11525     bool EndsWithSequential = false;
11526     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11527          I != E; ++I)
11528       EndsWithSequential = !isa<StructType>(*I);
11529
11530     // Can we combine the two pointer arithmetics offsets?
11531     if (EndsWithSequential) {
11532       // Replace: gep (gep %P, long B), long A, ...
11533       // With:    T = long A+B; gep %P, T, ...
11534       //
11535       Value *Sum;
11536       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11537       Value *GO1 = GEP.getOperand(1);
11538       if (SO1 == Constant::getNullValue(SO1->getType())) {
11539         Sum = GO1;
11540       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11541         Sum = SO1;
11542       } else {
11543         // If they aren't the same type, then the input hasn't been processed
11544         // by the loop above yet (which canonicalizes sequential index types to
11545         // intptr_t).  Just avoid transforming this until the input has been
11546         // normalized.
11547         if (SO1->getType() != GO1->getType())
11548           return 0;
11549         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11550       }
11551
11552       // Update the GEP in place if possible.
11553       if (Src->getNumOperands() == 2) {
11554         GEP.setOperand(0, Src->getOperand(0));
11555         GEP.setOperand(1, Sum);
11556         return &GEP;
11557       }
11558       Indices.append(Src->op_begin()+1, Src->op_end()-1);
11559       Indices.push_back(Sum);
11560       Indices.append(GEP.op_begin()+2, GEP.op_end());
11561     } else if (isa<Constant>(*GEP.idx_begin()) &&
11562                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11563                Src->getNumOperands() != 1) {
11564       // Otherwise we can do the fold if the first index of the GEP is a zero
11565       Indices.append(Src->op_begin()+1, Src->op_end());
11566       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
11567     }
11568
11569     if (!Indices.empty())
11570       return (cast<GEPOperator>(&GEP)->isInBounds() &&
11571               Src->isInBounds()) ?
11572         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11573                                           Indices.end(), GEP.getName()) :
11574         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11575                                   Indices.end(), GEP.getName());
11576   }
11577   
11578   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11579   if (Value *X = getBitCastOperand(PtrOp)) {
11580     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11581
11582     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
11583     // want to change the gep until the bitcasts are eliminated.
11584     if (getBitCastOperand(X)) {
11585       Worklist.AddValue(PtrOp);
11586       return 0;
11587     }
11588     
11589     bool HasZeroPointerIndex = false;
11590     if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
11591       HasZeroPointerIndex = C->isZero();
11592     
11593     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11594     // into     : GEP [10 x i8]* X, i32 0, ...
11595     //
11596     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11597     //           into     : GEP i8* X, ...
11598     // 
11599     // This occurs when the program declares an array extern like "int X[];"
11600     if (HasZeroPointerIndex) {
11601       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11602       const PointerType *XTy = cast<PointerType>(X->getType());
11603       if (const ArrayType *CATy =
11604           dyn_cast<ArrayType>(CPTy->getElementType())) {
11605         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11606         if (CATy->getElementType() == XTy->getElementType()) {
11607           // -> GEP i8* X, ...
11608           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11609           return cast<GEPOperator>(&GEP)->isInBounds() ?
11610             GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11611                                               GEP.getName()) :
11612             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11613                                       GEP.getName());
11614         }
11615         
11616         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11617           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11618           if (CATy->getElementType() == XATy->getElementType()) {
11619             // -> GEP [10 x i8]* X, i32 0, ...
11620             // At this point, we know that the cast source type is a pointer
11621             // to an array of the same type as the destination pointer
11622             // array.  Because the array type is never stepped over (there
11623             // is a leading zero) we can fold the cast into this GEP.
11624             GEP.setOperand(0, X);
11625             return &GEP;
11626           }
11627         }
11628       }
11629     } else if (GEP.getNumOperands() == 2) {
11630       // Transform things like:
11631       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11632       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11633       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11634       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11635       if (TD && isa<ArrayType>(SrcElTy) &&
11636           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11637           TD->getTypeAllocSize(ResElTy)) {
11638         Value *Idx[2];
11639         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11640         Idx[1] = GEP.getOperand(1);
11641         Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11642           Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11643           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11644         // V and GEP are both pointer types --> BitCast
11645         return new BitCastInst(NewGEP, GEP.getType());
11646       }
11647       
11648       // Transform things like:
11649       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11650       //   (where tmp = 8*tmp2) into:
11651       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11652       
11653       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11654         uint64_t ArrayEltSize =
11655             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11656         
11657         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11658         // allow either a mul, shift, or constant here.
11659         Value *NewIdx = 0;
11660         ConstantInt *Scale = 0;
11661         if (ArrayEltSize == 1) {
11662           NewIdx = GEP.getOperand(1);
11663           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11664         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11665           NewIdx = ConstantInt::get(CI->getType(), 1);
11666           Scale = CI;
11667         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11668           if (Inst->getOpcode() == Instruction::Shl &&
11669               isa<ConstantInt>(Inst->getOperand(1))) {
11670             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11671             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11672             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11673                                      1ULL << ShAmtVal);
11674             NewIdx = Inst->getOperand(0);
11675           } else if (Inst->getOpcode() == Instruction::Mul &&
11676                      isa<ConstantInt>(Inst->getOperand(1))) {
11677             Scale = cast<ConstantInt>(Inst->getOperand(1));
11678             NewIdx = Inst->getOperand(0);
11679           }
11680         }
11681         
11682         // If the index will be to exactly the right offset with the scale taken
11683         // out, perform the transformation. Note, we don't know whether Scale is
11684         // signed or not. We'll use unsigned version of division/modulo
11685         // operation after making sure Scale doesn't have the sign bit set.
11686         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11687             Scale->getZExtValue() % ArrayEltSize == 0) {
11688           Scale = ConstantInt::get(Scale->getType(),
11689                                    Scale->getZExtValue() / ArrayEltSize);
11690           if (Scale->getZExtValue() != 1) {
11691             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11692                                                        false /*ZExt*/);
11693             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11694           }
11695
11696           // Insert the new GEP instruction.
11697           Value *Idx[2];
11698           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11699           Idx[1] = NewIdx;
11700           Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11701             Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11702             Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11703           // The NewGEP must be pointer typed, so must the old one -> BitCast
11704           return new BitCastInst(NewGEP, GEP.getType());
11705         }
11706       }
11707     }
11708   }
11709   
11710   /// See if we can simplify:
11711   ///   X = bitcast A* to B*
11712   ///   Y = gep X, <...constant indices...>
11713   /// into a gep of the original struct.  This is important for SROA and alias
11714   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11715   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11716     if (TD &&
11717         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11718       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11719       // a constant back from EmitGEPOffset.
11720       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
11721       int64_t Offset = OffsetV->getSExtValue();
11722       
11723       // If this GEP instruction doesn't move the pointer, just replace the GEP
11724       // with a bitcast of the real input to the dest type.
11725       if (Offset == 0) {
11726         // If the bitcast is of an allocation, and the allocation will be
11727         // converted to match the type of the cast, don't touch this.
11728         if (isa<AllocaInst>(BCI->getOperand(0)) ||
11729             isMalloc(BCI->getOperand(0))) {
11730           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11731           if (Instruction *I = visitBitCast(*BCI)) {
11732             if (I != BCI) {
11733               I->takeName(BCI);
11734               BCI->getParent()->getInstList().insert(BCI, I);
11735               ReplaceInstUsesWith(*BCI, I);
11736             }
11737             return &GEP;
11738           }
11739         }
11740         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11741       }
11742       
11743       // Otherwise, if the offset is non-zero, we need to find out if there is a
11744       // field at Offset in 'A's type.  If so, we can pull the cast through the
11745       // GEP.
11746       SmallVector<Value*, 8> NewIndices;
11747       const Type *InTy =
11748         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11749       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11750         Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11751           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11752                                      NewIndices.end()) :
11753           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11754                              NewIndices.end());
11755         
11756         if (NGEP->getType() == GEP.getType())
11757           return ReplaceInstUsesWith(GEP, NGEP);
11758         NGEP->takeName(&GEP);
11759         return new BitCastInst(NGEP, GEP.getType());
11760       }
11761     }
11762   }    
11763     
11764   return 0;
11765 }
11766
11767 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
11768   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
11769   if (AI.isArrayAllocation()) {  // Check C != 1
11770     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11771       const Type *NewTy = 
11772         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11773       assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11774       AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11775       New->setAlignment(AI.getAlignment());
11776
11777       // Scan to the end of the allocation instructions, to skip over a block of
11778       // allocas if possible...also skip interleaved debug info
11779       //
11780       BasicBlock::iterator It = New;
11781       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11782
11783       // Now that I is pointing to the first non-allocation-inst in the block,
11784       // insert our getelementptr instruction...
11785       //
11786       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11787       Value *Idx[2];
11788       Idx[0] = NullIdx;
11789       Idx[1] = NullIdx;
11790       Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11791                                                    New->getName()+".sub", It);
11792
11793       // Now make everything use the getelementptr instead of the original
11794       // allocation.
11795       return ReplaceInstUsesWith(AI, V);
11796     } else if (isa<UndefValue>(AI.getArraySize())) {
11797       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11798     }
11799   }
11800
11801   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11802     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11803     // Note that we only do this for alloca's, because malloc should allocate
11804     // and return a unique pointer, even for a zero byte allocation.
11805     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11806       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11807
11808     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11809     if (AI.getAlignment() == 0)
11810       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11811   }
11812
11813   return 0;
11814 }
11815
11816 Instruction *InstCombiner::visitFree(Instruction &FI) {
11817   Value *Op = FI.getOperand(1);
11818
11819   // free undef -> unreachable.
11820   if (isa<UndefValue>(Op)) {
11821     // Insert a new store to null because we cannot modify the CFG here.
11822     new StoreInst(ConstantInt::getTrue(*Context),
11823            UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11824     return EraseInstFromFunction(FI);
11825   }
11826   
11827   // If we have 'free null' delete the instruction.  This can happen in stl code
11828   // when lots of inlining happens.
11829   if (isa<ConstantPointerNull>(Op))
11830     return EraseInstFromFunction(FI);
11831
11832   // If we have a malloc call whose only use is a free call, delete both.
11833   if (isMalloc(Op)) {
11834     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11835       if (Op->hasOneUse() && CI->hasOneUse()) {
11836         EraseInstFromFunction(FI);
11837         EraseInstFromFunction(*CI);
11838         return EraseInstFromFunction(*cast<Instruction>(Op));
11839       }
11840     } else {
11841       // Op is a call to malloc
11842       if (Op->hasOneUse()) {
11843         EraseInstFromFunction(FI);
11844         return EraseInstFromFunction(*cast<Instruction>(Op));
11845       }
11846     }
11847   }
11848
11849   return 0;
11850 }
11851
11852 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11853 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11854                                         const TargetData *TD) {
11855   User *CI = cast<User>(LI.getOperand(0));
11856   Value *CastOp = CI->getOperand(0);
11857   LLVMContext *Context = IC.getContext();
11858
11859   const PointerType *DestTy = cast<PointerType>(CI->getType());
11860   const Type *DestPTy = DestTy->getElementType();
11861   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11862
11863     // If the address spaces don't match, don't eliminate the cast.
11864     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11865       return 0;
11866
11867     const Type *SrcPTy = SrcTy->getElementType();
11868
11869     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11870          isa<VectorType>(DestPTy)) {
11871       // If the source is an array, the code below will not succeed.  Check to
11872       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11873       // constants.
11874       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11875         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11876           if (ASrcTy->getNumElements() != 0) {
11877             Value *Idxs[2];
11878             Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11879             Idxs[1] = Idxs[0];
11880             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11881             SrcTy = cast<PointerType>(CastOp->getType());
11882             SrcPTy = SrcTy->getElementType();
11883           }
11884
11885       if (IC.getTargetData() &&
11886           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11887             isa<VectorType>(SrcPTy)) &&
11888           // Do not allow turning this into a load of an integer, which is then
11889           // casted to a pointer, this pessimizes pointer analysis a lot.
11890           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11891           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11892                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11893
11894         // Okay, we are casting from one integer or pointer type to another of
11895         // the same size.  Instead of casting the pointer before the load, cast
11896         // the result of the loaded value.
11897         Value *NewLoad = 
11898           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11899         // Now cast the result of the load.
11900         return new BitCastInst(NewLoad, LI.getType());
11901       }
11902     }
11903   }
11904   return 0;
11905 }
11906
11907 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11908   Value *Op = LI.getOperand(0);
11909
11910   // Attempt to improve the alignment.
11911   if (TD) {
11912     unsigned KnownAlign =
11913       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11914     if (KnownAlign >
11915         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11916                                   LI.getAlignment()))
11917       LI.setAlignment(KnownAlign);
11918   }
11919
11920   // load (cast X) --> cast (load X) iff safe.
11921   if (isa<CastInst>(Op))
11922     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11923       return Res;
11924
11925   // None of the following transforms are legal for volatile loads.
11926   if (LI.isVolatile()) return 0;
11927   
11928   // Do really simple store-to-load forwarding and load CSE, to catch cases
11929   // where there are several consequtive memory accesses to the same location,
11930   // separated by a few arithmetic operations.
11931   BasicBlock::iterator BBI = &LI;
11932   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11933     return ReplaceInstUsesWith(LI, AvailableVal);
11934
11935   // load(gep null, ...) -> unreachable
11936   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11937     const Value *GEPI0 = GEPI->getOperand(0);
11938     // TODO: Consider a target hook for valid address spaces for this xform.
11939     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11940       // Insert a new store to null instruction before the load to indicate
11941       // that this code is not reachable.  We do this instead of inserting
11942       // an unreachable instruction directly because we cannot modify the
11943       // CFG.
11944       new StoreInst(UndefValue::get(LI.getType()),
11945                     Constant::getNullValue(Op->getType()), &LI);
11946       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11947     }
11948   } 
11949
11950   // load null/undef -> unreachable
11951   // TODO: Consider a target hook for valid address spaces for this xform.
11952   if (isa<UndefValue>(Op) ||
11953       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11954     // Insert a new store to null instruction before the load to indicate that
11955     // this code is not reachable.  We do this instead of inserting an
11956     // unreachable instruction directly because we cannot modify the CFG.
11957     new StoreInst(UndefValue::get(LI.getType()),
11958                   Constant::getNullValue(Op->getType()), &LI);
11959     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11960   }
11961
11962   // Instcombine load (constantexpr_cast global) -> cast (load global)
11963   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11964     if (CE->isCast())
11965       if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11966         return Res;
11967   
11968   if (Op->hasOneUse()) {
11969     // Change select and PHI nodes to select values instead of addresses: this
11970     // helps alias analysis out a lot, allows many others simplifications, and
11971     // exposes redundancy in the code.
11972     //
11973     // Note that we cannot do the transformation unless we know that the
11974     // introduced loads cannot trap!  Something like this is valid as long as
11975     // the condition is always false: load (select bool %C, int* null, int* %G),
11976     // but it would not be valid if we transformed it to load from null
11977     // unconditionally.
11978     //
11979     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11980       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11981       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11982           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11983         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11984                                         SI->getOperand(1)->getName()+".val");
11985         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11986                                         SI->getOperand(2)->getName()+".val");
11987         return SelectInst::Create(SI->getCondition(), V1, V2);
11988       }
11989
11990       // load (select (cond, null, P)) -> load P
11991       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11992         if (C->isNullValue()) {
11993           LI.setOperand(0, SI->getOperand(2));
11994           return &LI;
11995         }
11996
11997       // load (select (cond, P, null)) -> load P
11998       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11999         if (C->isNullValue()) {
12000           LI.setOperand(0, SI->getOperand(1));
12001           return &LI;
12002         }
12003     }
12004   }
12005   return 0;
12006 }
12007
12008 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
12009 /// when possible.  This makes it generally easy to do alias analysis and/or
12010 /// SROA/mem2reg of the memory object.
12011 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12012   User *CI = cast<User>(SI.getOperand(1));
12013   Value *CastOp = CI->getOperand(0);
12014
12015   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
12016   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12017   if (SrcTy == 0) return 0;
12018   
12019   const Type *SrcPTy = SrcTy->getElementType();
12020
12021   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12022     return 0;
12023   
12024   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12025   /// to its first element.  This allows us to handle things like:
12026   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12027   /// on 32-bit hosts.
12028   SmallVector<Value*, 4> NewGEPIndices;
12029   
12030   // If the source is an array, the code below will not succeed.  Check to
12031   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
12032   // constants.
12033   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12034     // Index through pointer.
12035     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
12036     NewGEPIndices.push_back(Zero);
12037     
12038     while (1) {
12039       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
12040         if (!STy->getNumElements()) /* Struct can be empty {} */
12041           break;
12042         NewGEPIndices.push_back(Zero);
12043         SrcPTy = STy->getElementType(0);
12044       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12045         NewGEPIndices.push_back(Zero);
12046         SrcPTy = ATy->getElementType();
12047       } else {
12048         break;
12049       }
12050     }
12051     
12052     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
12053   }
12054
12055   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12056     return 0;
12057   
12058   // If the pointers point into different address spaces or if they point to
12059   // values with different sizes, we can't do the transformation.
12060   if (!IC.getTargetData() ||
12061       SrcTy->getAddressSpace() != 
12062         cast<PointerType>(CI->getType())->getAddressSpace() ||
12063       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12064       IC.getTargetData()->getTypeSizeInBits(DestPTy))
12065     return 0;
12066
12067   // Okay, we are casting from one integer or pointer type to another of
12068   // the same size.  Instead of casting the pointer before 
12069   // the store, cast the value to be stored.
12070   Value *NewCast;
12071   Value *SIOp0 = SI.getOperand(0);
12072   Instruction::CastOps opcode = Instruction::BitCast;
12073   const Type* CastSrcTy = SIOp0->getType();
12074   const Type* CastDstTy = SrcPTy;
12075   if (isa<PointerType>(CastDstTy)) {
12076     if (CastSrcTy->isInteger())
12077       opcode = Instruction::IntToPtr;
12078   } else if (isa<IntegerType>(CastDstTy)) {
12079     if (isa<PointerType>(SIOp0->getType()))
12080       opcode = Instruction::PtrToInt;
12081   }
12082   
12083   // SIOp0 is a pointer to aggregate and this is a store to the first field,
12084   // emit a GEP to index into its first field.
12085   if (!NewGEPIndices.empty())
12086     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12087                                            NewGEPIndices.end());
12088   
12089   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12090                                    SIOp0->getName()+".c");
12091   return new StoreInst(NewCast, CastOp);
12092 }
12093
12094 /// equivalentAddressValues - Test if A and B will obviously have the same
12095 /// value. This includes recognizing that %t0 and %t1 will have the same
12096 /// value in code like this:
12097 ///   %t0 = getelementptr \@a, 0, 3
12098 ///   store i32 0, i32* %t0
12099 ///   %t1 = getelementptr \@a, 0, 3
12100 ///   %t2 = load i32* %t1
12101 ///
12102 static bool equivalentAddressValues(Value *A, Value *B) {
12103   // Test if the values are trivially equivalent.
12104   if (A == B) return true;
12105   
12106   // Test if the values come form identical arithmetic instructions.
12107   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12108   // its only used to compare two uses within the same basic block, which
12109   // means that they'll always either have the same value or one of them
12110   // will have an undefined value.
12111   if (isa<BinaryOperator>(A) ||
12112       isa<CastInst>(A) ||
12113       isa<PHINode>(A) ||
12114       isa<GetElementPtrInst>(A))
12115     if (Instruction *BI = dyn_cast<Instruction>(B))
12116       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
12117         return true;
12118   
12119   // Otherwise they may not be equivalent.
12120   return false;
12121 }
12122
12123 // If this instruction has two uses, one of which is a llvm.dbg.declare,
12124 // return the llvm.dbg.declare.
12125 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12126   if (!V->hasNUses(2))
12127     return 0;
12128   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12129        UI != E; ++UI) {
12130     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12131       return DI;
12132     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12133       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12134         return DI;
12135       }
12136   }
12137   return 0;
12138 }
12139
12140 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12141   Value *Val = SI.getOperand(0);
12142   Value *Ptr = SI.getOperand(1);
12143
12144   // If the RHS is an alloca with a single use, zapify the store, making the
12145   // alloca dead.
12146   // If the RHS is an alloca with a two uses, the other one being a 
12147   // llvm.dbg.declare, zapify the store and the declare, making the
12148   // alloca dead.  We must do this to prevent declare's from affecting
12149   // codegen.
12150   if (!SI.isVolatile()) {
12151     if (Ptr->hasOneUse()) {
12152       if (isa<AllocaInst>(Ptr)) {
12153         EraseInstFromFunction(SI);
12154         ++NumCombined;
12155         return 0;
12156       }
12157       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12158         if (isa<AllocaInst>(GEP->getOperand(0))) {
12159           if (GEP->getOperand(0)->hasOneUse()) {
12160             EraseInstFromFunction(SI);
12161             ++NumCombined;
12162             return 0;
12163           }
12164           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12165             EraseInstFromFunction(*DI);
12166             EraseInstFromFunction(SI);
12167             ++NumCombined;
12168             return 0;
12169           }
12170         }
12171       }
12172     }
12173     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12174       EraseInstFromFunction(*DI);
12175       EraseInstFromFunction(SI);
12176       ++NumCombined;
12177       return 0;
12178     }
12179   }
12180
12181   // Attempt to improve the alignment.
12182   if (TD) {
12183     unsigned KnownAlign =
12184       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12185     if (KnownAlign >
12186         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12187                                   SI.getAlignment()))
12188       SI.setAlignment(KnownAlign);
12189   }
12190
12191   // Do really simple DSE, to catch cases where there are several consecutive
12192   // stores to the same location, separated by a few arithmetic operations. This
12193   // situation often occurs with bitfield accesses.
12194   BasicBlock::iterator BBI = &SI;
12195   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12196        --ScanInsts) {
12197     --BBI;
12198     // Don't count debug info directives, lest they affect codegen,
12199     // and we skip pointer-to-pointer bitcasts, which are NOPs.
12200     // It is necessary for correctness to skip those that feed into a
12201     // llvm.dbg.declare, as these are not present when debugging is off.
12202     if (isa<DbgInfoIntrinsic>(BBI) ||
12203         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12204       ScanInsts++;
12205       continue;
12206     }    
12207     
12208     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12209       // Prev store isn't volatile, and stores to the same location?
12210       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12211                                                           SI.getOperand(1))) {
12212         ++NumDeadStore;
12213         ++BBI;
12214         EraseInstFromFunction(*PrevSI);
12215         continue;
12216       }
12217       break;
12218     }
12219     
12220     // If this is a load, we have to stop.  However, if the loaded value is from
12221     // the pointer we're loading and is producing the pointer we're storing,
12222     // then *this* store is dead (X = load P; store X -> P).
12223     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
12224       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12225           !SI.isVolatile()) {
12226         EraseInstFromFunction(SI);
12227         ++NumCombined;
12228         return 0;
12229       }
12230       // Otherwise, this is a load from some other location.  Stores before it
12231       // may not be dead.
12232       break;
12233     }
12234     
12235     // Don't skip over loads or things that can modify memory.
12236     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
12237       break;
12238   }
12239   
12240   
12241   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
12242
12243   // store X, null    -> turns into 'unreachable' in SimplifyCFG
12244   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
12245     if (!isa<UndefValue>(Val)) {
12246       SI.setOperand(0, UndefValue::get(Val->getType()));
12247       if (Instruction *U = dyn_cast<Instruction>(Val))
12248         Worklist.Add(U);  // Dropped a use.
12249       ++NumCombined;
12250     }
12251     return 0;  // Do not modify these!
12252   }
12253
12254   // store undef, Ptr -> noop
12255   if (isa<UndefValue>(Val)) {
12256     EraseInstFromFunction(SI);
12257     ++NumCombined;
12258     return 0;
12259   }
12260
12261   // If the pointer destination is a cast, see if we can fold the cast into the
12262   // source instead.
12263   if (isa<CastInst>(Ptr))
12264     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12265       return Res;
12266   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
12267     if (CE->isCast())
12268       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12269         return Res;
12270
12271   
12272   // If this store is the last instruction in the basic block (possibly
12273   // excepting debug info instructions and the pointer bitcasts that feed
12274   // into them), and if the block ends with an unconditional branch, try
12275   // to move it to the successor block.
12276   BBI = &SI; 
12277   do {
12278     ++BBI;
12279   } while (isa<DbgInfoIntrinsic>(BBI) ||
12280            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
12281   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
12282     if (BI->isUnconditional())
12283       if (SimplifyStoreAtEndOfBlock(SI))
12284         return 0;  // xform done!
12285   
12286   return 0;
12287 }
12288
12289 /// SimplifyStoreAtEndOfBlock - Turn things like:
12290 ///   if () { *P = v1; } else { *P = v2 }
12291 /// into a phi node with a store in the successor.
12292 ///
12293 /// Simplify things like:
12294 ///   *P = v1; if () { *P = v2; }
12295 /// into a phi node with a store in the successor.
12296 ///
12297 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12298   BasicBlock *StoreBB = SI.getParent();
12299   
12300   // Check to see if the successor block has exactly two incoming edges.  If
12301   // so, see if the other predecessor contains a store to the same location.
12302   // if so, insert a PHI node (if needed) and move the stores down.
12303   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12304   
12305   // Determine whether Dest has exactly two predecessors and, if so, compute
12306   // the other predecessor.
12307   pred_iterator PI = pred_begin(DestBB);
12308   BasicBlock *OtherBB = 0;
12309   if (*PI != StoreBB)
12310     OtherBB = *PI;
12311   ++PI;
12312   if (PI == pred_end(DestBB))
12313     return false;
12314   
12315   if (*PI != StoreBB) {
12316     if (OtherBB)
12317       return false;
12318     OtherBB = *PI;
12319   }
12320   if (++PI != pred_end(DestBB))
12321     return false;
12322
12323   // Bail out if all the relevant blocks aren't distinct (this can happen,
12324   // for example, if SI is in an infinite loop)
12325   if (StoreBB == DestBB || OtherBB == DestBB)
12326     return false;
12327
12328   // Verify that the other block ends in a branch and is not otherwise empty.
12329   BasicBlock::iterator BBI = OtherBB->getTerminator();
12330   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12331   if (!OtherBr || BBI == OtherBB->begin())
12332     return false;
12333   
12334   // If the other block ends in an unconditional branch, check for the 'if then
12335   // else' case.  there is an instruction before the branch.
12336   StoreInst *OtherStore = 0;
12337   if (OtherBr->isUnconditional()) {
12338     --BBI;
12339     // Skip over debugging info.
12340     while (isa<DbgInfoIntrinsic>(BBI) ||
12341            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12342       if (BBI==OtherBB->begin())
12343         return false;
12344       --BBI;
12345     }
12346     // If this isn't a store, isn't a store to the same location, or if the
12347     // alignments differ, bail out.
12348     OtherStore = dyn_cast<StoreInst>(BBI);
12349     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12350         OtherStore->getAlignment() != SI.getAlignment())
12351       return false;
12352   } else {
12353     // Otherwise, the other block ended with a conditional branch. If one of the
12354     // destinations is StoreBB, then we have the if/then case.
12355     if (OtherBr->getSuccessor(0) != StoreBB && 
12356         OtherBr->getSuccessor(1) != StoreBB)
12357       return false;
12358     
12359     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12360     // if/then triangle.  See if there is a store to the same ptr as SI that
12361     // lives in OtherBB.
12362     for (;; --BBI) {
12363       // Check to see if we find the matching store.
12364       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12365         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12366             OtherStore->getAlignment() != SI.getAlignment())
12367           return false;
12368         break;
12369       }
12370       // If we find something that may be using or overwriting the stored
12371       // value, or if we run out of instructions, we can't do the xform.
12372       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12373           BBI == OtherBB->begin())
12374         return false;
12375     }
12376     
12377     // In order to eliminate the store in OtherBr, we have to
12378     // make sure nothing reads or overwrites the stored value in
12379     // StoreBB.
12380     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12381       // FIXME: This should really be AA driven.
12382       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12383         return false;
12384     }
12385   }
12386   
12387   // Insert a PHI node now if we need it.
12388   Value *MergedVal = OtherStore->getOperand(0);
12389   if (MergedVal != SI.getOperand(0)) {
12390     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12391     PN->reserveOperandSpace(2);
12392     PN->addIncoming(SI.getOperand(0), SI.getParent());
12393     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12394     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12395   }
12396   
12397   // Advance to a place where it is safe to insert the new store and
12398   // insert it.
12399   BBI = DestBB->getFirstNonPHI();
12400   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12401                                     OtherStore->isVolatile(),
12402                                     SI.getAlignment()), *BBI);
12403   
12404   // Nuke the old stores.
12405   EraseInstFromFunction(SI);
12406   EraseInstFromFunction(*OtherStore);
12407   ++NumCombined;
12408   return true;
12409 }
12410
12411
12412 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12413   // Change br (not X), label True, label False to: br X, label False, True
12414   Value *X = 0;
12415   BasicBlock *TrueDest;
12416   BasicBlock *FalseDest;
12417   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12418       !isa<Constant>(X)) {
12419     // Swap Destinations and condition...
12420     BI.setCondition(X);
12421     BI.setSuccessor(0, FalseDest);
12422     BI.setSuccessor(1, TrueDest);
12423     return &BI;
12424   }
12425
12426   // Cannonicalize fcmp_one -> fcmp_oeq
12427   FCmpInst::Predicate FPred; Value *Y;
12428   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12429                              TrueDest, FalseDest)) &&
12430       BI.getCondition()->hasOneUse())
12431     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12432         FPred == FCmpInst::FCMP_OGE) {
12433       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12434       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12435       
12436       // Swap Destinations and condition.
12437       BI.setSuccessor(0, FalseDest);
12438       BI.setSuccessor(1, TrueDest);
12439       Worklist.Add(Cond);
12440       return &BI;
12441     }
12442
12443   // Cannonicalize icmp_ne -> icmp_eq
12444   ICmpInst::Predicate IPred;
12445   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12446                       TrueDest, FalseDest)) &&
12447       BI.getCondition()->hasOneUse())
12448     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12449         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12450         IPred == ICmpInst::ICMP_SGE) {
12451       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12452       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12453       // Swap Destinations and condition.
12454       BI.setSuccessor(0, FalseDest);
12455       BI.setSuccessor(1, TrueDest);
12456       Worklist.Add(Cond);
12457       return &BI;
12458     }
12459
12460   return 0;
12461 }
12462
12463 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12464   Value *Cond = SI.getCondition();
12465   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12466     if (I->getOpcode() == Instruction::Add)
12467       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12468         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12469         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12470           SI.setOperand(i,
12471                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12472                                                 AddRHS));
12473         SI.setOperand(0, I->getOperand(0));
12474         Worklist.Add(I);
12475         return &SI;
12476       }
12477   }
12478   return 0;
12479 }
12480
12481 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12482   Value *Agg = EV.getAggregateOperand();
12483
12484   if (!EV.hasIndices())
12485     return ReplaceInstUsesWith(EV, Agg);
12486
12487   if (Constant *C = dyn_cast<Constant>(Agg)) {
12488     if (isa<UndefValue>(C))
12489       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12490       
12491     if (isa<ConstantAggregateZero>(C))
12492       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12493
12494     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12495       // Extract the element indexed by the first index out of the constant
12496       Value *V = C->getOperand(*EV.idx_begin());
12497       if (EV.getNumIndices() > 1)
12498         // Extract the remaining indices out of the constant indexed by the
12499         // first index
12500         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12501       else
12502         return ReplaceInstUsesWith(EV, V);
12503     }
12504     return 0; // Can't handle other constants
12505   } 
12506   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12507     // We're extracting from an insertvalue instruction, compare the indices
12508     const unsigned *exti, *exte, *insi, *inse;
12509     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12510          exte = EV.idx_end(), inse = IV->idx_end();
12511          exti != exte && insi != inse;
12512          ++exti, ++insi) {
12513       if (*insi != *exti)
12514         // The insert and extract both reference distinctly different elements.
12515         // This means the extract is not influenced by the insert, and we can
12516         // replace the aggregate operand of the extract with the aggregate
12517         // operand of the insert. i.e., replace
12518         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12519         // %E = extractvalue { i32, { i32 } } %I, 0
12520         // with
12521         // %E = extractvalue { i32, { i32 } } %A, 0
12522         return ExtractValueInst::Create(IV->getAggregateOperand(),
12523                                         EV.idx_begin(), EV.idx_end());
12524     }
12525     if (exti == exte && insi == inse)
12526       // Both iterators are at the end: Index lists are identical. Replace
12527       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12528       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12529       // with "i32 42"
12530       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12531     if (exti == exte) {
12532       // The extract list is a prefix of the insert list. i.e. replace
12533       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12534       // %E = extractvalue { i32, { i32 } } %I, 1
12535       // with
12536       // %X = extractvalue { i32, { i32 } } %A, 1
12537       // %E = insertvalue { i32 } %X, i32 42, 0
12538       // by switching the order of the insert and extract (though the
12539       // insertvalue should be left in, since it may have other uses).
12540       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12541                                                  EV.idx_begin(), EV.idx_end());
12542       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12543                                      insi, inse);
12544     }
12545     if (insi == inse)
12546       // The insert list is a prefix of the extract list
12547       // We can simply remove the common indices from the extract and make it
12548       // operate on the inserted value instead of the insertvalue result.
12549       // i.e., replace
12550       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12551       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12552       // with
12553       // %E extractvalue { i32 } { i32 42 }, 0
12554       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12555                                       exti, exte);
12556   }
12557   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
12558     // We're extracting from an intrinsic, see if we're the only user, which
12559     // allows us to simplify multiple result intrinsics to simpler things that
12560     // just get one value..
12561     if (II->hasOneUse()) {
12562       // Check if we're grabbing the overflow bit or the result of a 'with
12563       // overflow' intrinsic.  If it's the latter we can remove the intrinsic
12564       // and replace it with a traditional binary instruction.
12565       switch (II->getIntrinsicID()) {
12566       case Intrinsic::uadd_with_overflow:
12567       case Intrinsic::sadd_with_overflow:
12568         if (*EV.idx_begin() == 0) {  // Normal result.
12569           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12570           II->replaceAllUsesWith(UndefValue::get(II->getType()));
12571           EraseInstFromFunction(*II);
12572           return BinaryOperator::CreateAdd(LHS, RHS);
12573         }
12574         break;
12575       case Intrinsic::usub_with_overflow:
12576       case Intrinsic::ssub_with_overflow:
12577         if (*EV.idx_begin() == 0) {  // Normal result.
12578           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12579           II->replaceAllUsesWith(UndefValue::get(II->getType()));
12580           EraseInstFromFunction(*II);
12581           return BinaryOperator::CreateSub(LHS, RHS);
12582         }
12583         break;
12584       case Intrinsic::umul_with_overflow:
12585       case Intrinsic::smul_with_overflow:
12586         if (*EV.idx_begin() == 0) {  // Normal result.
12587           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
12588           II->replaceAllUsesWith(UndefValue::get(II->getType()));
12589           EraseInstFromFunction(*II);
12590           return BinaryOperator::CreateMul(LHS, RHS);
12591         }
12592         break;
12593       default:
12594         break;
12595       }
12596     }
12597   }
12598   // Can't simplify extracts from other values. Note that nested extracts are
12599   // already simplified implicitely by the above (extract ( extract (insert) )
12600   // will be translated into extract ( insert ( extract ) ) first and then just
12601   // the value inserted, if appropriate).
12602   return 0;
12603 }
12604
12605 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12606 /// is to leave as a vector operation.
12607 static bool CheapToScalarize(Value *V, bool isConstant) {
12608   if (isa<ConstantAggregateZero>(V)) 
12609     return true;
12610   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12611     if (isConstant) return true;
12612     // If all elts are the same, we can extract.
12613     Constant *Op0 = C->getOperand(0);
12614     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12615       if (C->getOperand(i) != Op0)
12616         return false;
12617     return true;
12618   }
12619   Instruction *I = dyn_cast<Instruction>(V);
12620   if (!I) return false;
12621   
12622   // Insert element gets simplified to the inserted element or is deleted if
12623   // this is constant idx extract element and its a constant idx insertelt.
12624   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12625       isa<ConstantInt>(I->getOperand(2)))
12626     return true;
12627   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12628     return true;
12629   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12630     if (BO->hasOneUse() &&
12631         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12632          CheapToScalarize(BO->getOperand(1), isConstant)))
12633       return true;
12634   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12635     if (CI->hasOneUse() &&
12636         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12637          CheapToScalarize(CI->getOperand(1), isConstant)))
12638       return true;
12639   
12640   return false;
12641 }
12642
12643 /// Read and decode a shufflevector mask.
12644 ///
12645 /// It turns undef elements into values that are larger than the number of
12646 /// elements in the input.
12647 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12648   unsigned NElts = SVI->getType()->getNumElements();
12649   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12650     return std::vector<unsigned>(NElts, 0);
12651   if (isa<UndefValue>(SVI->getOperand(2)))
12652     return std::vector<unsigned>(NElts, 2*NElts);
12653
12654   std::vector<unsigned> Result;
12655   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12656   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12657     if (isa<UndefValue>(*i))
12658       Result.push_back(NElts*2);  // undef -> 8
12659     else
12660       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12661   return Result;
12662 }
12663
12664 /// FindScalarElement - Given a vector and an element number, see if the scalar
12665 /// value is already around as a register, for example if it were inserted then
12666 /// extracted from the vector.
12667 static Value *FindScalarElement(Value *V, unsigned EltNo,
12668                                 LLVMContext *Context) {
12669   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12670   const VectorType *PTy = cast<VectorType>(V->getType());
12671   unsigned Width = PTy->getNumElements();
12672   if (EltNo >= Width)  // Out of range access.
12673     return UndefValue::get(PTy->getElementType());
12674   
12675   if (isa<UndefValue>(V))
12676     return UndefValue::get(PTy->getElementType());
12677   else if (isa<ConstantAggregateZero>(V))
12678     return Constant::getNullValue(PTy->getElementType());
12679   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12680     return CP->getOperand(EltNo);
12681   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12682     // If this is an insert to a variable element, we don't know what it is.
12683     if (!isa<ConstantInt>(III->getOperand(2))) 
12684       return 0;
12685     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12686     
12687     // If this is an insert to the element we are looking for, return the
12688     // inserted value.
12689     if (EltNo == IIElt) 
12690       return III->getOperand(1);
12691     
12692     // Otherwise, the insertelement doesn't modify the value, recurse on its
12693     // vector input.
12694     return FindScalarElement(III->getOperand(0), EltNo, Context);
12695   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12696     unsigned LHSWidth =
12697       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12698     unsigned InEl = getShuffleMask(SVI)[EltNo];
12699     if (InEl < LHSWidth)
12700       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12701     else if (InEl < LHSWidth*2)
12702       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12703     else
12704       return UndefValue::get(PTy->getElementType());
12705   }
12706   
12707   // Otherwise, we don't know.
12708   return 0;
12709 }
12710
12711 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12712   // If vector val is undef, replace extract with scalar undef.
12713   if (isa<UndefValue>(EI.getOperand(0)))
12714     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12715
12716   // If vector val is constant 0, replace extract with scalar 0.
12717   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12718     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12719   
12720   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12721     // If vector val is constant with all elements the same, replace EI with
12722     // that element. When the elements are not identical, we cannot replace yet
12723     // (we do that below, but only when the index is constant).
12724     Constant *op0 = C->getOperand(0);
12725     for (unsigned i = 1; i != C->getNumOperands(); ++i)
12726       if (C->getOperand(i) != op0) {
12727         op0 = 0; 
12728         break;
12729       }
12730     if (op0)
12731       return ReplaceInstUsesWith(EI, op0);
12732   }
12733   
12734   // If extracting a specified index from the vector, see if we can recursively
12735   // find a previously computed scalar that was inserted into the vector.
12736   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12737     unsigned IndexVal = IdxC->getZExtValue();
12738     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12739       
12740     // If this is extracting an invalid index, turn this into undef, to avoid
12741     // crashing the code below.
12742     if (IndexVal >= VectorWidth)
12743       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12744     
12745     // This instruction only demands the single element from the input vector.
12746     // If the input vector has a single use, simplify it based on this use
12747     // property.
12748     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12749       APInt UndefElts(VectorWidth, 0);
12750       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12751       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12752                                                 DemandedMask, UndefElts)) {
12753         EI.setOperand(0, V);
12754         return &EI;
12755       }
12756     }
12757     
12758     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12759       return ReplaceInstUsesWith(EI, Elt);
12760     
12761     // If the this extractelement is directly using a bitcast from a vector of
12762     // the same number of elements, see if we can find the source element from
12763     // it.  In this case, we will end up needing to bitcast the scalars.
12764     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12765       if (const VectorType *VT = 
12766               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12767         if (VT->getNumElements() == VectorWidth)
12768           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12769                                              IndexVal, Context))
12770             return new BitCastInst(Elt, EI.getType());
12771     }
12772   }
12773   
12774   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12775     // Push extractelement into predecessor operation if legal and
12776     // profitable to do so
12777     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12778       if (I->hasOneUse() &&
12779           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12780         Value *newEI0 =
12781           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12782                                         EI.getName()+".lhs");
12783         Value *newEI1 =
12784           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12785                                         EI.getName()+".rhs");
12786         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12787       }
12788     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12789       // Extracting the inserted element?
12790       if (IE->getOperand(2) == EI.getOperand(1))
12791         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12792       // If the inserted and extracted elements are constants, they must not
12793       // be the same value, extract from the pre-inserted value instead.
12794       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12795         Worklist.AddValue(EI.getOperand(0));
12796         EI.setOperand(0, IE->getOperand(0));
12797         return &EI;
12798       }
12799     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12800       // If this is extracting an element from a shufflevector, figure out where
12801       // it came from and extract from the appropriate input element instead.
12802       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12803         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12804         Value *Src;
12805         unsigned LHSWidth =
12806           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12807
12808         if (SrcIdx < LHSWidth)
12809           Src = SVI->getOperand(0);
12810         else if (SrcIdx < LHSWidth*2) {
12811           SrcIdx -= LHSWidth;
12812           Src = SVI->getOperand(1);
12813         } else {
12814           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12815         }
12816         return ExtractElementInst::Create(Src,
12817                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12818                                           false));
12819       }
12820     }
12821     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12822   }
12823   return 0;
12824 }
12825
12826 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12827 /// elements from either LHS or RHS, return the shuffle mask and true. 
12828 /// Otherwise, return false.
12829 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12830                                          std::vector<Constant*> &Mask,
12831                                          LLVMContext *Context) {
12832   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12833          "Invalid CollectSingleShuffleElements");
12834   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12835
12836   if (isa<UndefValue>(V)) {
12837     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12838     return true;
12839   } else if (V == LHS) {
12840     for (unsigned i = 0; i != NumElts; ++i)
12841       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12842     return true;
12843   } else if (V == RHS) {
12844     for (unsigned i = 0; i != NumElts; ++i)
12845       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12846     return true;
12847   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12848     // If this is an insert of an extract from some other vector, include it.
12849     Value *VecOp    = IEI->getOperand(0);
12850     Value *ScalarOp = IEI->getOperand(1);
12851     Value *IdxOp    = IEI->getOperand(2);
12852     
12853     if (!isa<ConstantInt>(IdxOp))
12854       return false;
12855     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12856     
12857     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12858       // Okay, we can handle this if the vector we are insertinting into is
12859       // transitively ok.
12860       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12861         // If so, update the mask to reflect the inserted undef.
12862         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12863         return true;
12864       }      
12865     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12866       if (isa<ConstantInt>(EI->getOperand(1)) &&
12867           EI->getOperand(0)->getType() == V->getType()) {
12868         unsigned ExtractedIdx =
12869           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12870         
12871         // This must be extracting from either LHS or RHS.
12872         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12873           // Okay, we can handle this if the vector we are insertinting into is
12874           // transitively ok.
12875           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12876             // If so, update the mask to reflect the inserted value.
12877             if (EI->getOperand(0) == LHS) {
12878               Mask[InsertedIdx % NumElts] = 
12879                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12880             } else {
12881               assert(EI->getOperand(0) == RHS);
12882               Mask[InsertedIdx % NumElts] = 
12883                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12884               
12885             }
12886             return true;
12887           }
12888         }
12889       }
12890     }
12891   }
12892   // TODO: Handle shufflevector here!
12893   
12894   return false;
12895 }
12896
12897 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12898 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12899 /// that computes V and the LHS value of the shuffle.
12900 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12901                                      Value *&RHS, LLVMContext *Context) {
12902   assert(isa<VectorType>(V->getType()) && 
12903          (RHS == 0 || V->getType() == RHS->getType()) &&
12904          "Invalid shuffle!");
12905   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12906
12907   if (isa<UndefValue>(V)) {
12908     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12909     return V;
12910   } else if (isa<ConstantAggregateZero>(V)) {
12911     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12912     return V;
12913   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12914     // If this is an insert of an extract from some other vector, include it.
12915     Value *VecOp    = IEI->getOperand(0);
12916     Value *ScalarOp = IEI->getOperand(1);
12917     Value *IdxOp    = IEI->getOperand(2);
12918     
12919     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12920       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12921           EI->getOperand(0)->getType() == V->getType()) {
12922         unsigned ExtractedIdx =
12923           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12924         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12925         
12926         // Either the extracted from or inserted into vector must be RHSVec,
12927         // otherwise we'd end up with a shuffle of three inputs.
12928         if (EI->getOperand(0) == RHS || RHS == 0) {
12929           RHS = EI->getOperand(0);
12930           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12931           Mask[InsertedIdx % NumElts] = 
12932             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12933           return V;
12934         }
12935         
12936         if (VecOp == RHS) {
12937           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12938                                             RHS, Context);
12939           // Everything but the extracted element is replaced with the RHS.
12940           for (unsigned i = 0; i != NumElts; ++i) {
12941             if (i != InsertedIdx)
12942               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12943           }
12944           return V;
12945         }
12946         
12947         // If this insertelement is a chain that comes from exactly these two
12948         // vectors, return the vector and the effective shuffle.
12949         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12950                                          Context))
12951           return EI->getOperand(0);
12952         
12953       }
12954     }
12955   }
12956   // TODO: Handle shufflevector here!
12957   
12958   // Otherwise, can't do anything fancy.  Return an identity vector.
12959   for (unsigned i = 0; i != NumElts; ++i)
12960     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12961   return V;
12962 }
12963
12964 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12965   Value *VecOp    = IE.getOperand(0);
12966   Value *ScalarOp = IE.getOperand(1);
12967   Value *IdxOp    = IE.getOperand(2);
12968   
12969   // Inserting an undef or into an undefined place, remove this.
12970   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12971     ReplaceInstUsesWith(IE, VecOp);
12972   
12973   // If the inserted element was extracted from some other vector, and if the 
12974   // indexes are constant, try to turn this into a shufflevector operation.
12975   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12976     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12977         EI->getOperand(0)->getType() == IE.getType()) {
12978       unsigned NumVectorElts = IE.getType()->getNumElements();
12979       unsigned ExtractedIdx =
12980         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12981       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12982       
12983       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12984         return ReplaceInstUsesWith(IE, VecOp);
12985       
12986       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12987         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12988       
12989       // If we are extracting a value from a vector, then inserting it right
12990       // back into the same place, just use the input vector.
12991       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12992         return ReplaceInstUsesWith(IE, VecOp);      
12993       
12994       // If this insertelement isn't used by some other insertelement, turn it
12995       // (and any insertelements it points to), into one big shuffle.
12996       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12997         std::vector<Constant*> Mask;
12998         Value *RHS = 0;
12999         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
13000         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
13001         // We now have a shuffle of LHS, RHS, Mask.
13002         return new ShuffleVectorInst(LHS, RHS,
13003                                      ConstantVector::get(Mask));
13004       }
13005     }
13006   }
13007
13008   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13009   APInt UndefElts(VWidth, 0);
13010   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13011   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13012     return &IE;
13013
13014   return 0;
13015 }
13016
13017
13018 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13019   Value *LHS = SVI.getOperand(0);
13020   Value *RHS = SVI.getOperand(1);
13021   std::vector<unsigned> Mask = getShuffleMask(&SVI);
13022
13023   bool MadeChange = false;
13024
13025   // Undefined shuffle mask -> undefined value.
13026   if (isa<UndefValue>(SVI.getOperand(2)))
13027     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
13028
13029   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
13030
13031   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13032     return 0;
13033
13034   APInt UndefElts(VWidth, 0);
13035   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13036   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
13037     LHS = SVI.getOperand(0);
13038     RHS = SVI.getOperand(1);
13039     MadeChange = true;
13040   }
13041   
13042   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
13043   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13044   if (LHS == RHS || isa<UndefValue>(LHS)) {
13045     if (isa<UndefValue>(LHS) && LHS == RHS) {
13046       // shuffle(undef,undef,mask) -> undef.
13047       return ReplaceInstUsesWith(SVI, LHS);
13048     }
13049     
13050     // Remap any references to RHS to use LHS.
13051     std::vector<Constant*> Elts;
13052     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13053       if (Mask[i] >= 2*e)
13054         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13055       else {
13056         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
13057             (Mask[i] <  e && isa<UndefValue>(LHS))) {
13058           Mask[i] = 2*e;     // Turn into undef.
13059           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13060         } else {
13061           Mask[i] = Mask[i] % e;  // Force to LHS.
13062           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
13063         }
13064       }
13065     }
13066     SVI.setOperand(0, SVI.getOperand(1));
13067     SVI.setOperand(1, UndefValue::get(RHS->getType()));
13068     SVI.setOperand(2, ConstantVector::get(Elts));
13069     LHS = SVI.getOperand(0);
13070     RHS = SVI.getOperand(1);
13071     MadeChange = true;
13072   }
13073   
13074   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
13075   bool isLHSID = true, isRHSID = true;
13076     
13077   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13078     if (Mask[i] >= e*2) continue;  // Ignore undef values.
13079     // Is this an identity shuffle of the LHS value?
13080     isLHSID &= (Mask[i] == i);
13081       
13082     // Is this an identity shuffle of the RHS value?
13083     isRHSID &= (Mask[i]-e == i);
13084   }
13085
13086   // Eliminate identity shuffles.
13087   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13088   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
13089   
13090   // If the LHS is a shufflevector itself, see if we can combine it with this
13091   // one without producing an unusual shuffle.  Here we are really conservative:
13092   // we are absolutely afraid of producing a shuffle mask not in the input
13093   // program, because the code gen may not be smart enough to turn a merged
13094   // shuffle into two specific shuffles: it may produce worse code.  As such,
13095   // we only merge two shuffles if the result is one of the two input shuffle
13096   // masks.  In this case, merging the shuffles just removes one instruction,
13097   // which we know is safe.  This is good for things like turning:
13098   // (splat(splat)) -> splat.
13099   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13100     if (isa<UndefValue>(RHS)) {
13101       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13102
13103       if (LHSMask.size() == Mask.size()) {
13104         std::vector<unsigned> NewMask;
13105         for (unsigned i = 0, e = Mask.size(); i != e; ++i)
13106           if (Mask[i] >= e)
13107             NewMask.push_back(2*e);
13108           else
13109             NewMask.push_back(LHSMask[Mask[i]]);
13110       
13111         // If the result mask is equal to the src shuffle or this
13112         // shuffle mask, do the replacement.
13113         if (NewMask == LHSMask || NewMask == Mask) {
13114           unsigned LHSInNElts =
13115             cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13116             getNumElements();
13117           std::vector<Constant*> Elts;
13118           for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13119             if (NewMask[i] >= LHSInNElts*2) {
13120               Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13121             } else {
13122               Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13123                                               NewMask[i]));
13124             }
13125           }
13126           return new ShuffleVectorInst(LHSSVI->getOperand(0),
13127                                        LHSSVI->getOperand(1),
13128                                        ConstantVector::get(Elts));
13129         }
13130       }
13131     }
13132   }
13133
13134   return MadeChange ? &SVI : 0;
13135 }
13136
13137
13138
13139
13140 /// TryToSinkInstruction - Try to move the specified instruction from its
13141 /// current block into the beginning of DestBlock, which can only happen if it's
13142 /// safe to move the instruction past all of the instructions between it and the
13143 /// end of its block.
13144 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13145   assert(I->hasOneUse() && "Invariants didn't hold!");
13146
13147   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
13148   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
13149     return false;
13150
13151   // Do not sink alloca instructions out of the entry block.
13152   if (isa<AllocaInst>(I) && I->getParent() ==
13153         &DestBlock->getParent()->getEntryBlock())
13154     return false;
13155
13156   // We can only sink load instructions if there is nothing between the load and
13157   // the end of block that could change the value.
13158   if (I->mayReadFromMemory()) {
13159     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
13160          Scan != E; ++Scan)
13161       if (Scan->mayWriteToMemory())
13162         return false;
13163   }
13164
13165   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
13166
13167   CopyPrecedingStopPoint(I, InsertPos);
13168   I->moveBefore(InsertPos);
13169   ++NumSunkInst;
13170   return true;
13171 }
13172
13173
13174 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13175 /// all reachable code to the worklist.
13176 ///
13177 /// This has a couple of tricks to make the code faster and more powerful.  In
13178 /// particular, we constant fold and DCE instructions as we go, to avoid adding
13179 /// them to the worklist (this significantly speeds up instcombine on code where
13180 /// many instructions are dead or constant).  Additionally, if we find a branch
13181 /// whose condition is a known constant, we only visit the reachable successors.
13182 ///
13183 static bool AddReachableCodeToWorklist(BasicBlock *BB, 
13184                                        SmallPtrSet<BasicBlock*, 64> &Visited,
13185                                        InstCombiner &IC,
13186                                        const TargetData *TD) {
13187   bool MadeIRChange = false;
13188   SmallVector<BasicBlock*, 256> Worklist;
13189   Worklist.push_back(BB);
13190   
13191   std::vector<Instruction*> InstrsForInstCombineWorklist;
13192   InstrsForInstCombineWorklist.reserve(128);
13193
13194   SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13195   
13196   while (!Worklist.empty()) {
13197     BB = Worklist.back();
13198     Worklist.pop_back();
13199     
13200     // We have now visited this block!  If we've already been here, ignore it.
13201     if (!Visited.insert(BB)) continue;
13202
13203     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13204       Instruction *Inst = BBI++;
13205       
13206       // DCE instruction if trivially dead.
13207       if (isInstructionTriviallyDead(Inst)) {
13208         ++NumDeadInst;
13209         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
13210         Inst->eraseFromParent();
13211         continue;
13212       }
13213       
13214       // ConstantProp instruction if trivially constant.
13215       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
13216         if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
13217           DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13218                        << *Inst << '\n');
13219           Inst->replaceAllUsesWith(C);
13220           ++NumConstProp;
13221           Inst->eraseFromParent();
13222           continue;
13223         }
13224       
13225       
13226       
13227       if (TD) {
13228         // See if we can constant fold its operands.
13229         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13230              i != e; ++i) {
13231           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13232           if (CE == 0) continue;
13233           
13234           // If we already folded this constant, don't try again.
13235           if (!FoldedConstants.insert(CE))
13236             continue;
13237           
13238           Constant *NewC = ConstantFoldConstantExpression(CE, TD);
13239           if (NewC && NewC != CE) {
13240             *i = NewC;
13241             MadeIRChange = true;
13242           }
13243         }
13244       }
13245       
13246
13247       InstrsForInstCombineWorklist.push_back(Inst);
13248     }
13249
13250     // Recursively visit successors.  If this is a branch or switch on a
13251     // constant, only visit the reachable successor.
13252     TerminatorInst *TI = BB->getTerminator();
13253     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13254       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13255         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
13256         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
13257         Worklist.push_back(ReachableBB);
13258         continue;
13259       }
13260     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13261       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13262         // See if this is an explicit destination.
13263         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13264           if (SI->getCaseValue(i) == Cond) {
13265             BasicBlock *ReachableBB = SI->getSuccessor(i);
13266             Worklist.push_back(ReachableBB);
13267             continue;
13268           }
13269         
13270         // Otherwise it is the default destination.
13271         Worklist.push_back(SI->getSuccessor(0));
13272         continue;
13273       }
13274     }
13275     
13276     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13277       Worklist.push_back(TI->getSuccessor(i));
13278   }
13279   
13280   // Once we've found all of the instructions to add to instcombine's worklist,
13281   // add them in reverse order.  This way instcombine will visit from the top
13282   // of the function down.  This jives well with the way that it adds all uses
13283   // of instructions to the worklist after doing a transformation, thus avoiding
13284   // some N^2 behavior in pathological cases.
13285   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13286                               InstrsForInstCombineWorklist.size());
13287   
13288   return MadeIRChange;
13289 }
13290
13291 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
13292   MadeIRChange = false;
13293   
13294   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13295         << F.getNameStr() << "\n");
13296
13297   {
13298     // Do a depth-first traversal of the function, populate the worklist with
13299     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
13300     // track of which blocks we visit.
13301     SmallPtrSet<BasicBlock*, 64> Visited;
13302     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
13303
13304     // Do a quick scan over the function.  If we find any blocks that are
13305     // unreachable, remove any instructions inside of them.  This prevents
13306     // the instcombine code from having to deal with some bad special cases.
13307     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13308       if (!Visited.count(BB)) {
13309         Instruction *Term = BB->getTerminator();
13310         while (Term != BB->begin()) {   // Remove instrs bottom-up
13311           BasicBlock::iterator I = Term; --I;
13312
13313           DEBUG(errs() << "IC: DCE: " << *I << '\n');
13314           // A debug intrinsic shouldn't force another iteration if we weren't
13315           // going to do one without it.
13316           if (!isa<DbgInfoIntrinsic>(I)) {
13317             ++NumDeadInst;
13318             MadeIRChange = true;
13319           }
13320
13321           // If I is not void type then replaceAllUsesWith undef.
13322           // This allows ValueHandlers and custom metadata to adjust itself.
13323           if (!I->getType()->isVoidTy())
13324             I->replaceAllUsesWith(UndefValue::get(I->getType()));
13325           I->eraseFromParent();
13326         }
13327       }
13328   }
13329
13330   while (!Worklist.isEmpty()) {
13331     Instruction *I = Worklist.RemoveOne();
13332     if (I == 0) continue;  // skip null values.
13333
13334     // Check to see if we can DCE the instruction.
13335     if (isInstructionTriviallyDead(I)) {
13336       DEBUG(errs() << "IC: DCE: " << *I << '\n');
13337       EraseInstFromFunction(*I);
13338       ++NumDeadInst;
13339       MadeIRChange = true;
13340       continue;
13341     }
13342
13343     // Instruction isn't dead, see if we can constant propagate it.
13344     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
13345       if (Constant *C = ConstantFoldInstruction(I, TD)) {
13346         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
13347
13348         // Add operands to the worklist.
13349         ReplaceInstUsesWith(*I, C);
13350         ++NumConstProp;
13351         EraseInstFromFunction(*I);
13352         MadeIRChange = true;
13353         continue;
13354       }
13355
13356     // See if we can trivially sink this instruction to a successor basic block.
13357     if (I->hasOneUse()) {
13358       BasicBlock *BB = I->getParent();
13359       Instruction *UserInst = cast<Instruction>(I->use_back());
13360       BasicBlock *UserParent;
13361       
13362       // Get the block the use occurs in.
13363       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13364         UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13365       else
13366         UserParent = UserInst->getParent();
13367       
13368       if (UserParent != BB) {
13369         bool UserIsSuccessor = false;
13370         // See if the user is one of our successors.
13371         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13372           if (*SI == UserParent) {
13373             UserIsSuccessor = true;
13374             break;
13375           }
13376
13377         // If the user is one of our immediate successors, and if that successor
13378         // only has us as a predecessors (we'd have to split the critical edge
13379         // otherwise), we can keep going.
13380         if (UserIsSuccessor && UserParent->getSinglePredecessor())
13381           // Okay, the CFG is simple enough, try to sink this instruction.
13382           MadeIRChange |= TryToSinkInstruction(I, UserParent);
13383       }
13384     }
13385
13386     // Now that we have an instruction, try combining it to simplify it.
13387     Builder->SetInsertPoint(I->getParent(), I);
13388     
13389 #ifndef NDEBUG
13390     std::string OrigI;
13391 #endif
13392     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
13393     DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13394
13395     if (Instruction *Result = visit(*I)) {
13396       ++NumCombined;
13397       // Should we replace the old instruction with a new one?
13398       if (Result != I) {
13399         DEBUG(errs() << "IC: Old = " << *I << '\n'
13400                      << "    New = " << *Result << '\n');
13401
13402         // Everything uses the new instruction now.
13403         I->replaceAllUsesWith(Result);
13404
13405         // Push the new instruction and any users onto the worklist.
13406         Worklist.Add(Result);
13407         Worklist.AddUsersToWorkList(*Result);
13408
13409         // Move the name to the new instruction first.
13410         Result->takeName(I);
13411
13412         // Insert the new instruction into the basic block...
13413         BasicBlock *InstParent = I->getParent();
13414         BasicBlock::iterator InsertPos = I;
13415
13416         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13417           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13418             ++InsertPos;
13419
13420         InstParent->getInstList().insert(InsertPos, Result);
13421
13422         EraseInstFromFunction(*I);
13423       } else {
13424 #ifndef NDEBUG
13425         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13426                      << "    New = " << *I << '\n');
13427 #endif
13428
13429         // If the instruction was modified, it's possible that it is now dead.
13430         // if so, remove it.
13431         if (isInstructionTriviallyDead(I)) {
13432           EraseInstFromFunction(*I);
13433         } else {
13434           Worklist.Add(I);
13435           Worklist.AddUsersToWorkList(*I);
13436         }
13437       }
13438       MadeIRChange = true;
13439     }
13440   }
13441
13442   Worklist.Zap();
13443   return MadeIRChange;
13444 }
13445
13446
13447 bool InstCombiner::runOnFunction(Function &F) {
13448   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13449   Context = &F.getContext();
13450   TD = getAnalysisIfAvailable<TargetData>();
13451
13452   
13453   /// Builder - This is an IRBuilder that automatically inserts new
13454   /// instructions into the worklist when they are created.
13455   IRBuilder<true, TargetFolder, InstCombineIRInserter> 
13456     TheBuilder(F.getContext(), TargetFolder(TD),
13457                InstCombineIRInserter(Worklist));
13458   Builder = &TheBuilder;
13459   
13460   bool EverMadeChange = false;
13461
13462   // Iterate while there is work to do.
13463   unsigned Iteration = 0;
13464   while (DoOneIteration(F, Iteration++))
13465     EverMadeChange = true;
13466   
13467   Builder = 0;
13468   return EverMadeChange;
13469 }
13470
13471 FunctionPass *llvm::createInstructionCombiningPass() {
13472   return new InstCombiner();
13473 }